<?php
class Service_EtpOrderTrackingProcess {
    protected $_error = array();
    protected $_content;
    protected $_date;
    protected $_apiKey;

    public function __construct() {
        $this->_date = date('Y-m-d H:i:s');
    }
    /*
     *
     */
    public static function addSendList( $orderCode ) {
        $orderRow = Service_Orders::getByField( $orderCode, 'order_code' );
        if( $orderRow && Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $orderRow['customer_code'] ) ) {
            $sendRow = Service_EtpOrderTrackingInfo::getByField( $orderCode, 'order_code' );
            if( empty( $sendRow ) ) {
                $add = array(
                    'order_code' => $orderRow['order_code'],
                    'order_status' => $orderRow['order_status'],
                    'add_time' => date('Y-m-d H:i:s'),
                );
                $adapter = Common_Common::getAdapter();
                $adapter->beginTransaction();
                try{
                    $result = Service_EtpOrderTrackingInfo::add( $add );
                    if( !$result )
                        throw new Exception('添加ETP物流签收信息失败');

                    unset($add['add_time']);
                    $add['eoti_id'] = $result;

                    $result = Service_EtpOrderTrackingInfoTmp::add( $add );
                    if( !$result )
                        throw new Exception('添加ETP物流签收信息失败');

                    $adapter->commit();
                    return true;
                } catch( Exception $e ) {
                    $adapter->rollBack();
                    return false;
                }
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public function getError() {
        return $this->_error;
    }

    protected function addError( $error ) {
        $this->_error[] = $error;
    }

    protected function setPost() {
        $content = json_encode( $this->_content );
        $postArr = array(
            'appKey'=>$this->_apiKey,
            'timestamp'=>time(),
            'version'=>'1.0',
            'content'=>$content
         );
        $this->_post = $postArr;
    }

    protected function initService( $service ) {
        $etp = new Common_Etp();
        $this->_scheme = $etp->getScheme();
        $this->_host = $etp->getHost();
        $this->_port = $etp->getPort();
        $this->_service = $etp->getService( $service );
        $this->_apiKey = $etp->getApiKey();

    }
    /* @todo:确认收货
     *
     */
    public function confirmReceivedOrder( $id ) {
        if( empty( $id ) ) {
            $this->addError( 'ID不能为空' );
            return false;
        }
        $send = Service_EtpOrderTrackingInfoTmp::getByField( $id );
        if( empty( $send ) ){
            $this->addError( '发送队列不存在' );
            return false;
        }
        $orderRow = Service_Orders::getByField( $send['order_code'], 'order_code');

        if( $orderRow ) {

            $this->_content = array(
                'plateCode'=>'globalsource',
                'referenceNo'=>$orderRow['reference_no'],
            );

            $this->initService('confirmReceivedOrder');
            $this->setPost();
            $result = $this->doRequest();
            if( $result ===  false )
                return false;

            $flag = false;
            $adapter = Common_Common::getAdapter();
            $adapter->beginTransaction();
            try{
                //更新备案清单状态
                if( $result['state'] == 1 ) {
                    $update = array(
                        'send_time'      => $this->_date,
                        'is_sent'         => 2,
                        'remark'          => '发送成功',
                    );
                    $result = Service_EtpOrderTrackingInfoTmp::delete( $send['id'], 'id');
                    if( !$result )
                        throw new Exception('删除发送队列失败');

                    $flag = true;
                } else {
                    if( !empty( $result['error'] ) ) {
                        foreach( $result['error'] as $value ) {
                            $this->addError( 'code: '.$value['errorCode'].', msg: '.$value['errorMsg'] );
                        }
                    } else {
                        $this->addError( $result['message'] );
                    }
                    $msg = implode( ',', $this->_error );

                    $update = array(
                        'send_time'      => $this->_date,
                        'is_sent'        => 1,
                        'send_remark'         => $msg,
                    );

                    $result = Service_EtpOrderTrackingInfoTmp::update( array(
                        'failed_count' => $send['failed_count'] + 1,
                        'send_remark'        => $msg,
                        'send_time'     => $this->_date,
                    ), $send['id'], 'id' );
                    if( !$result )
                        throw new Exception('更新发送队列失败');

                }
                $r = Service_EtpOrderTrackingInfo::update( $update, $send['eoti_id'], 'eoti_id');
                if( !$r )
                    throw new Exception('更新etp_order_tracking_info状态失败');

                $adapter->commit();
            } catch( Exception $e ) {
                $adapter->rollBack();
                $this->addError( $e->getMessage() );
            }
        } else {
            $this->addError('订单信息不存在');
        }
        return $flag;
    }

    public function doRequest(){
        $httpClient = new Common_HttpClient( $this->_scheme.'://'.$this->_host,$this->_port );
        $httpClient->setDebug(true);
        $isSuccessful = $httpClient->post( $this->_service, $this->_post );
        if( !$isSuccessful ) {
            $this->addError( $httpClient->getError() );
            return false;
        }

        $content = $httpClient->getContent();
        $result = $this->getResult( $content );
        return $result;
    }

    /**
     * @将数据处理成统一的格式
     *  $mark =1记录到api访问请求的日志中.否则不记录
     */
    private function getResult( $data ){
        $result = array(
            'state'=>'0',
            'message'=>'',
            'error'=>array(
            )
        );
        $info = json_decode($data,true);
        if(!empty($info) && is_array($info)){
            if($info['ack']=='Success'){
                $result['state']='1';
                $result['message'] = $info['ack'];
            }elseif($info['ack']=='Failure'){
                $error = array(
                    'errorCode'=>$info['errorCode'],
                    'errorMsg'=>$info['errorMsg'].( isset( $info['reference'] ) ? $info['reference'] : '')
                );
                $result['error'][]=$error;
            }else{
                $result['message'] = "未知接口返回标示:".$info['ack'];
            }
        }else{
            $result['message'] = '接口返回数据['.var_export($data,true).']无法解析.';
        }
        return $result;
    }


}