﻿<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 14-6-3
 * Time: 下午5:04
 * To change this template use File | Settings | File Templates.
 */
class Api_ServiceForExchangeOrder
{
    protected $_customerId = null;

    protected $_customer = 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->_token = (string) $headerRequest['appToken'];
        $this->_key = (string) $headerRequest['appKey'];
    }
    /**
     * @author william-fan
     * @todo Authenticate
     */
    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;
        }
        $this->_customer = $customer;
        $customerAuth = Service_CustomerApi::getByField($this->_customerId, 'customer_code');

        if ($customerAuth && $customerAuth['ca_token'] == $this->_token && $customerAuth['ca_key'] == $this->_key) {
            $this->_auth = true;
            return true;
        }
        $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 . 'api-exchangeorder.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 createExchangeOrder($data){
        $this->common($data);
        $result = array(
            'ask' => '0',
            'orderCode' => '',
            'time'=>date("Y-m-d H:i:s"),
			'error'=>array(),
        );
		 if ($this->_error) {
            $result['error']['errorMessage']	= $this->_error;
            return $result;
        }
        $headerRequest = $this->_paramterArr['HeaderRequest'] ;
        $customerCode = $headerRequest['customerCode'];
        $customerRow = Service_Customer::getByField($customerCode,'customer_code',"*");

        $orderInfo = $this->_paramterArr['createExchangeOrderInfo'];
        $order = array();
        $parcelDetail = array();
        $parcelProduct = array();
        foreach($orderInfo as $key=>$value){
            if($key=="ParcelDetail"){
                $parcelDetail = $value;
            }else{
                if($key=="shipper_country"){
                    $shipCountry = Service_Country::getByField($value,'country_code',"*");
                    $order['shipper_country_id'] = $shipCountry['country_id'];
                }elseif($key=="recipient_country"){
                    $shipCountry = Service_Country::getByField($value,'country_code',"*");
                    $order['recipient_country_id'] = $shipCountry['country_id'];
                }else{
                    $order[$key] = $value;
                }
            }
        }
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            $ordersCode = Common_GetNumbers::getCode('order', $customerRow['customer_code'], 'SO');
            $order['order_code'] = $ordersCode;
            Service_ExchangeOrder::add($order);

            $pdRow = array();
            $parcelproductRow = array();
            foreach($parcelDetail as $pk=>$pv){
                if(is_numeric($pk)){
                    $pdRow = $pv;
                    unset($pdRow['ParcelProduct']);
                    $pdRow['order_code'] = $ordersCode;
                    $pdRow['parcel_code'] = Common_GetNumbers::getCode('order', $customerRow['customer_code'], 'PA');
                    $pdid = Service_ParcelDetail::add($pdRow);
                    $pp = $pv['ParcelProduct'];
                    foreach($pp as $ppk=>$ppv){
                        if(is_numeric($ppk)){
                            $parcelproduct = array(
                                'parcel_code'=>$pdRow['parcel_code'],
                                'harmonized_code'=>$ppv['harmonized_code'],
                                'commodity_description'=>$ppv['commodity_description'],
                                'commodity_sku'=>$ppv['commodity_sku'],
                                'commodity_value'=>$ppv['commodity_value'],
                                'commodity_weight'=>$ppv['commodity_weight'],
								'commodity_qty'=>$ppv['commodity_qty'],
                            );
                            Service_ParcelProduct::add($parcelproduct);
                            unset($parcelproduct);
                        }else{
                            $parcelproductRow[$ppk] = $ppv;
                        }
                    }
                    if(!empty($parcelproductRow)) $parcelproductRow['parcel_code'] = $pdRow['parcel_code'];
                    unset($pdRow);
                }else{
                    $pdRow['order_code'] = $ordersCode;
                    $pdRow['parcel_code'] = Common_GetNumbers::getCode('order', $customerRow['customer_code'], 'PA');
                    if($pk!="ParcelProduct"){
                        $pdRow[$pk] = $pv;
                    }else{
                        $pp = $pv;
                    }
                    foreach($pp as $ppk=>$ppv){
                        if(is_numeric($ppk)){
                            $parcelproduct = array(
                                'parcel_code'=>$pdRow['parcel_code'],
                                'harmonized_code'=>$ppv['harmonized_code'],
                                'commodity_description'=>$ppv['commodity_description'],
                                'commodity_sku'=>$ppv['commodity_sku'],
                                'commodity_value'=>$ppv['commodity_value'],
                                'commodity_weight'=>$ppv['commodity_weight'],
								'commodity_qty'=>$ppv['commodity_qty'],
                            );
                            Service_ParcelProduct::add($parcelproduct);
                            unset($parcelproduct);
                        }else{
                            $parcelproductRow[$ppk] = $ppv;
                        }
                    }
                    if(!empty($parcelproductRow)) $parcelproductRow['parcel_code'] = $pdRow['parcel_code'];
                }

            }
            if(!empty($pdRow)) $pdid = Service_ParcelDetail::add($pdRow);
            if(!empty($parcelproductRow)) Service_ParcelProduct::add($parcelproductRow);
            $result['ask'] = 1;
            $result['orderCode'] = $ordersCode;
            $db->commit();
        }catch (Exception $e){
            $db->rollback();
            $result['error']['errorMessage'] = $e->getMessage();
        }
        return $result;
    }
}
