<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-5-26
 * Time: 下午3:22
 * To change this template use File | Settings | File Templates.
 */
class Api_ServiceForOrderTracking
{
    protected $_customerId = null;

    protected $_customer = null;//认证用户

    protected $_targetCustomerCode = null;//认证用户想要操作的客户

    protected $_token = null;

    protected $_key = null;

    protected $_auth = false;

    protected $_error = null;

    protected $_date = null;

    protected $_paramterArr = array();//将传递过来的对象转为数组存储

    private function _init ($headerRequest) {
        $this->_customerId = (string) $headerRequest['customerCode'];
        $this->_targetCustomerCode = (string) $headerRequest['operationCustomerCode'];
        $this->_token = (string) $headerRequest['appToken'];
        $this->_key = (string) $headerRequest['appKey'];
    }

    private function authenticate(){
        $customer = Service_Customer::getByField($this->_customerId, 'customer_code');
        if (! $customer || $customer['customer_status'] != 2) {
            $this->_error = 'No Authority For ' . $this->_customerId . '.';
            return false;
        }

        $customerAuth = Service_CustomerApi::getByField($this->_customerId, 'customer_code');
        //判断授权用户的权限
        if ($customerAuth && $customerAuth['ca_token'] == $this->_token && $customerAuth['ca_key'] == $this->_key) {
            //因为是操作目标客户，客户信息要设成目标客户的
            if( $this->_targetCustomerCode !== null && $this->_targetCustomerCode !== '' ) {
                $rc = Service_CustomerRegister::getByCondition( array( 'customer_code' => $this->_targetCustomerCode, 'regis_customer_code' => $this->_customerId ) );
                if( empty( $rc ) ) {
                    $this->_error = '操作客户 ' . $this->_targetCustomerCode . ' 不属于你.';
                    $path = APPLICATION_PATH.'/../data/log/888.txt';
                    file_put_contents($path, var_export($this->_targetCustomerCode,true), FILE_APPEND);
                    return false;
                }

                $customer = Service_Customer::getByField($this->_targetCustomerCode, 'customer_code');
                if( empty( $customer ) ) {
                    $this->_error = '操作客户 ' . $this->_targetCustomerCode . ' 不存在.';
                    return false;
                }
                $this->_customerId = $this->_targetCustomerCode;//将用户信息设成目标客户的
            }
            $this->_customer = $customer;
            $this->_auth = true;
            return true;
        } else {
            $this->_error = 'App Token/App Key Not match for ' . $this->_customerId . '.';
            return false;
        }
    }

    /**
     * @todo 写日志
     */
    private function logError ($error) {
        $logger = new Zend_Log();
        $uploadDir = APPLICATION_PATH . "/../data/log/";
        $writer = new Zend_Log_Writer_Stream($uploadDir . 'order-tracking.log');
        $logger->addWriter($writer);
        $logger->info(date('Y-m-d H:i:s') . ': ' . $error . " \n");
    }

    private function common ($paramter) {

        $this->_paramterArr = Common_Common::objectToArray($paramter);//对象转数组
        $headRequest = $this->_paramterArr['HeaderRequest'];
        $this->_init($headRequest);

        $this->_date = date('Y-m-d H:i:s');
        $this->authenticate();

    }

    public function createOrderTracking($paramter){
		$time	= date("Y-m-d H:i:s");
        $this->common($paramter);
		$result = array(
            'ask' => '0',
            'trackNumber' => '',
            'time'=>$time,
			'error'=>array(),
        );
        if ($this->_error) {
            $result['error']['errorMessage']	= $this->_error;
            return $result;
        }
		$orderTrackingInfo = $this->_paramterArr['createOrderTrackingInfo'];
		$orderLogisticsOrderInfo	= Service_LogisticsOrder::getByField($orderTrackingInfo['tracking_number'],'ref_tracking_number',"*");
		if(!empty($orderLogisticsOrderInfo)){
			$shippingOrderTrackingInfo	= Service_ShippingOrderTracking::getByField($orderTrackingInfo['tracking_number'],'tracking_number',"*");
			if(empty($shippingOrderTrackingInfo)){
				$shippingOrderTrackingParam	= array(
					'tracking_number'	=> $orderTrackingInfo['tracking_number'],
					'scan_code'			=> $orderTrackingInfo['scan_code'],
					'location'			=> $orderTrackingInfo['location'],
					'country'			=> $orderTrackingInfo['country'],
					'remark'			=> $orderTrackingInfo['remark'],
					'weight'			=> $orderTrackingInfo['weight'],
					'url_for_image'		=> $orderTrackingInfo['url_for_image'],
					'sot_status'		=> 0,
					'date_time'			=> $time,
				);
				Service_ShippingOrderTracking::add($shippingOrderTrackingParam);
			}else{
				$this->_error = "This tracking number already exist.";
			}
		}else{
			$this->_error = "This tracking number is not exist.";
		}
		if ($this->_error) {
            $result['error']['errorMessage'] = $this->_error;
            return $result;
        }
        $result['ask'] = "1";
        $result['trackNumber'] = $orderTrackingInfo['tracking_number'];
        return $result;
    }

    public function getOrderTracking( $parameter ) {
        $result = array(
            'ask' => '0',
            'message'=>'Failure',
        );
        $time	= date("Y-m-d H:i:s");
        $this->common($parameter);
        if( $this->_error ) {
            $result['message'] = $this->_error;
            return $result;
        }
        $this->_error = array();
        if( !isset( $this->_paramterArr['code'] ) ||  $this->_paramterArr['code'] === '' || $this->_paramterArr['code'] === null) {
            $result['message'] = '单号不能为空';
            return $result;
        }

        $code = $this->_paramterArr['code'];

        $orders = Service_Orders::getByCondition( array( 'order_code' => $code, 'customer_code' => $this->_customerId ) );
        if( empty( $orders ) ) {
            $orders = Service_Orders::getByCondition( array( 'reference_no' => $code, 'customer_code' => $this->_customerId ) );
            if( empty( $orders ) ) {
                $result['message'] = '订单不存在';
                return $result;
            }
        }
        $order = $orders[0];

        $fields = array('sotLocation'=>'sot_location','sotAddTime'=>'sot_add_time','sotDescription'=>'sot_description','trackingNumber'=>'tracking_number');
        $trackingInfo = Service_ShipOrderTracking::getByCondition( array( 'order_code' => $order['order_code'] ), $fields );
        $result = array(
            'ask'=>'1',
            'message'=>'Success',
            'orderCode'=>$order['order_code'],
            'orderStatus'=>$order['order_status'],
            'trackingInfo'=>$trackingInfo
        );
        if( empty( $trackingInfo ) ) {
            $result['message'] = '跟踪信息未生成';
        }
        return $result;
    }
}
