<?php
class Service_OrderProcess
{
    private $_parcel        = array();
    private $_order         = array();
    private $_ordersCode    = '';
    private $_order_product = array();
    private $_opType        = '';
    private $_order_weight  = 0;
    private $_feeErr        = false;
    private $_inventoryErr  = false;
    private $_productErr    = false;

    /*集货订单的状态*/
    public static function getOrderStatus()
    {
        /* $status[0] = '删除';
        $status[1] = '草稿';
        $status[2] = '确认';
        $status[3] = '异常';
        $status[4] = '已提交';
        $status[5] = '已打印';
        $status[6] = '已下架';
        $status[7] = '已打包';
        $status[8] = '已装袋';
        $status[9] = '装袋完成';
        $status[10] = '已加挂';
        $status[11] = '物流完成';
        $status[12] = '物流发货';
        $status[13] = '已签收'; */
        //前台只显示部分状态
        $status['0']          = Ec_Lang::getInstance()->getTranslate('delete'); //'删除';
        $status['1']          = Ec_Lang::getInstance()->getTranslate('Draft'); //'草稿';
        $status['2']          = Ec_Lang::getInstance()->getTranslate('Confirm'); //'确认';
        $status['3']          = Ec_Lang::getInstance()->getTranslate('Abnormal'); //'异常';
        $status['4,5,6,7,14'] = Ec_Lang::getInstance()->getTranslate('Submitted'); //'已提交';
        /* $status['5'] = '已打印';
        $status['6'] = '已下架';
        $status['7'] = '已打包'; *///这几个状态都在已提交中
        $status['8,9,10,11,12'] = Ec_Lang::getInstance()->getTranslate('WarehouseShipments'); //'仓库出货';
        /* $status['9'] = '装袋完成';
        $status['10'] = '已加挂';
        $status['11'] = '物流完成';
        $status['12'] = '物流发货'; *///这几个状态在仓库出货中
        $status['13'] = Ec_Lang::getInstance()->getTranslate('Received'); //'已签收';

        return $status;
    }

    public static function getUnBatterySm(){
        $smArr = array('SZY-ETK','SZY-EMS','CJ-DGMG','CJ-DGMP','HKPP','HJPG','WG-EMS','WG-EUB','WG-EUB-EBAY');
        return $smArr;
    }

    private function initPieceDetail() {
        $this->_pieceDetail = array();
    }

    //@author 订单状态翻译成文字(集货模式)
    //@todo 订单状态翻译成文字
    public static function getJHStatusText($orderStatus = 0)
    {

        switch ($orderStatus) {
            case '0':
                return '删除';
                break;
            case '1':
                return '草稿';
                break;
            case '2':
                return '确认';
                break;
            case '3':
                return '异常';
                break;
            case '4':
            case '5':
            case '6':
            case '7':
                return '已提交';
                break;
            case '8':
            case '9':
            case '10':
            case '11':
                return '仓库出货';
                break;
            case '13':
                return '已签收';
                break;
        } //switch
        return '未知状态';
    }

    //@author 订单状态翻译成文字(集货模式)
    //@todo 订单状态翻译成文字
    public static function getJHStatusText2($orderStatus = 0)
    {

        switch ($orderStatus) {
            case '0':
                return '删除';
                break;
            case '1':
                return '草稿';
                break;
            case '2':
                return '确认';
                break;
            case '3':
                return '异常';
                break;
            case '4':
                return '已提交';
            case '5':
                return '已打印';
            case '6':
                return '已下架';
            case '7':
                return '已打包';
                break;
            case '8':
                return '已装袋';
            case '9':
                return '装袋完成';
            case '10':
                return '已加挂';
            case '11':
                return '仓库出货';
                break;
            case '13':
                return '已签收';
                break;
        } //switch
        return '未知状态';
    }
    /**
     * @author willliam-fan
     * @todo 用于得到集货模式的订单
     */
    public static function getjiOrderStatus()
    {
        //前台只显示部分状态
        $status['0'] = Ec_Lang::getInstance()->getTranslate('delete'); //'删除';
        $status['1'] = Ec_Lang::getInstance()->getTranslate('Draft'); //'草稿';
        $status['2'] = Ec_Lang::getInstance()->getTranslate('Confirm'); //'确认';
        //$status['3'] = Ec_Lang::getInstance()->getTranslate('Abnormal');//'异常';
        $status['4,5,6,7,14'] = Ec_Lang::getInstance()->getTranslate('Submitted'); //'已提交';
        /* $status['5'] = '已打印';
        $status['6'] = '已下架';
        $status['7'] = '已打包'; *///这几个状态都在已提交中
        $status['8,9,10,11,12'] = Ec_Lang::getInstance()->getTranslate('WarehouseShipments'); //'仓库出货';
        /* $status['9'] = '装袋完成';
        $status['10'] = '已加挂';
        $status['11'] = '物流完成';
        $status['12'] = '物流发货'; *///这几个状态在仓库出货中
        $status['13'] = Ec_Lang::getInstance()->getTranslate('Received'); //'已签收';

        return $status;
    }
    public static $operationArr = array(
        0  => array(1 => 'Draft'),
        1  => array(0 => 'Delete', 2 => 'Confirm'),
        2  => array(0 => 'Delete', 1 => 'Draft', 3 => 'Submit'),
        99 => array(0 => 'Delete', 1 => 'Draft', 3 => 'Submit'),
        3  => array(),
        4  => array(), //待发货
        5  => array(), //已发货
        6  => array(), //已完成
    );

    public static function getOrderTypeArr()
    {
        $status[0] = Ec_Lang::getInstance()->getTranslate('General'); //'普通';
        $status[1] = Ec_Lang::getInstance()->getTranslate('Rollover'); //'转仓';
        $status[2] = Ec_Lang::getInstance()->getTranslate('ReturnGoods'); //'退货';
        return $status;
    }

    public static $abnormalText = array(
        0 => '无异常',
        1 => 'Out of stock', //库存不足
        2 => 'Insufficient funds', //余额不足
        3 => 'stop order',
    );

    private function validator()
    {
        $this->_order['order_product'] = $this->_order_product;
        $result                        = Merchant_Service_FactoryValidate::factoryMethod($this->_order);
        unset($this->_order['order_product']);
        return $result;
    }

    /*
     * 获取物流费用
     */
    private function getFee()
    {
        $this->_order_weight = 0;
        foreach ($this->_order_product as $p) {
            $this->_order_weight += $p['op_weight'] * $p['op_quantity'];
        }
        $array = array(
            'warehouseId' => $this->_order['warehouse_id'],
            'countryId'   => $this->_order['consignee_country_id'],
//          'provinceId'=>6,
            'weight'      => $this->_order_weight,
            'length'      => 0,
            'width'       => 0,
            'height'      => 0,
            'customerId'  => $this->_order['customer_id'],
            'stCode'      => $this->_order['shipping_method'],
            'zip'         => $this->_order['consignee_zip'],
        );

        $obj = new Default_Service_TCCP($array);
        $fee = $obj->getFeeByType();
        if ($fee['ask']) {
            $fee = $fee['result'];
        } else {
            throw new Exception('Can Not Get Order Shpping Cost,' . $fee['message'], '10069');
        }
        return $fee;
    }

    private function holdInventory($ordersCode = '')
    {
        // print_r($this->_order_product);exit;
        $process = new Merchant_Service_ProductInventoryProcess();
        $err     = array();
        foreach ($this->_order_product as $orderProduct) {
            try {
                $invRow = array(
                    'product_id'       => $orderProduct['product_id'],
                    'quantity'         => $orderProduct['op_quantity'],
                    'unsellable_qty'   => 0,
                    'type'             => 4,
                    'warehouse_id'     => $this->_order['warehouse_id'],
                    'application_id'   => $this->_order['orders_code'],
                    'application_type' => 'order',
                    'note'             => 'Hold Inventory',
                );
                $return = $process->update($invRow);

                if (empty($return['ask'])) {
                    $this->_inventoryErr = 1;
                    throw new Exception('Hold Inventory Fail-->SKU:[' . $orderProduct['product_sku'] . '](ID:[' . $orderProduct['product_id'] . '])', '10066');
                }
            } catch (Exception $e) {
                $err[] = $e->getCode() . " " . $e->getMessage() . '-->' . $this->_ordersCode;
            }
        }
        return $err;
    }
    //订单拆分记录
    private function addOrderProductSeparate()
    {
        Merchant_Service_OrderProductSeparate::delete($this->_ordersCode, 'orders_code');
        $process = new Merchant_Service_OrderProductSeparate();
        foreach ($this->_order_product as $orderProduct) {
            $invRow = array(
                'orders_code'     => $this->_order['orders_code'],
                'product_id'      => $orderProduct['product_id'],
                'product_barcode' => $orderProduct['product_barcode'],
                'ops_quantity'    => $orderProduct['op_quantity'],
                'ops_weight'      => $orderProduct['op_weight'],
                'ops_unit_price'  => $orderProduct['op_unit_price'],
                'ops_last_update' => date('Y-m-d H:i:s'),
            );
            if (!Merchant_Service_OrderProductSeparate::add($invRow)) {
                throw new Exception("Internal Err.Add Order Product Separate Fail", '50000');
            }
        }
    }

    //订单赠品
    private function getOrderInsertProduct()
    {

    }

    public function validateInput($row)
    {
        $errorInfo = array();
        $error = array();
        if (!($row['order_mode_type'] == '0' || $row['order_mode_type'] == '1')) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrderModeOnlyBeCollectingModeOrDeliveryMode');
        }
        if (isset($row['is_fba'])) {
            if ($row['is_fba'] !== '') {
                if (!in_array($row['is_fba'], array('0', '1'))) {
                    $error[] = 'FBA填写错误！';
                }
            }
        }
        if (isset($row['is_fba_tax'])) {
            if ($row['is_fba_tax'] !== '') {
                if (!in_array($row['is_fba_tax'], array('0', '1'))) {
                    $error[] = '目的地关税填写错误！';
                }
            }
        }
        if (isset($row['is_pod'])) {
            if ($row['is_pod'] !== '') {
                if (!in_array($row['is_pod'], array('0', '1'))) {
                    $error[] = 'POD数据填写错误！';
                }
            }
        }
        //检查产品重量尺寸 环球客户
        $row['customer_code'] = isset($row['customer_code'])?$row['customer_code']:'';
        if( in_array($row['customer_code'],array('E0693')) && in_array( $row['sm_code'], array('HKDHL','BH-HKDHL')) ) {
            $pieces = isset( $row['piecesDetail'] ) ? $row['piecesDetail'] : array();
            if( false === $this->checkPieces( $pieces ) ) {
                $error[] = 'piecesDetail数据异常';
            }
        }
        //检查国家
        $country = array();
        if( isset( $row['oab_country_id'] ) ) {
            $country = Service_Country::getByField($row['oab_country_id'], 'country_id');
            if( empty( $country ) ) {
                $error[] = '国家不存在';
            }
        } else {
            $error[] = '缺少国家';
        }

        //订单模式 0:备货模式 1:集货模式
        if ($row['order_mode_type'] == '1') {
            if ($row['change_order'] != '1' && $row['change_order'] != '0') {
                $error[] = Ec_Lang::getInstance()->getTranslate('WhetherChangeSingle') . Ec_Lang::getInstance()->getTranslate('require');
            }
            if ($row['change_order'] == "0" && $row['delivery_address'] == "") {
                $error[] = "派送地址必填";
            }
            //假如是集货模式  如果选了 使用自有渠道 是的情况  服务商单号就必填
            if ($row['change_order'] == '0' && $row['ref_tracking_number'] == '') {
                $error[] = "服务商单号必填";
            } else {
                if ($row['ref_tracking_number'] != '') {
                    //验证同一个运输方式的服务商单号的唯一性
                    $refTrackCondition = array(
                        //'sm_code'=>$row['sm_code'],
                        'ref_tracking_number'        => $row['ref_tracking_number'],
                        'except_order_status_delete' => true,
                    );
                    $numberRefTrack  = Service_Orders::getByCondition($refTrackCondition);
                    $serviceTracking = Service_ServiceTrackingNumber::getByField($row['ref_tracking_number'], 'stn_code');
                    /*if(($numberRefTrack>0 || !empty($serviceTracking)) && !isset($row['order_code'])){
                    $error[] = '服务商单号重复';
                    }*/
                    if (isset($row['order_code'])) {
                        // 编辑模式
                        if (count($numberRefTrack) > 0) {
                            foreach ($numberRefTrack as $item) {
                                if (trim($item['order_code']) !== trim($row['order_code'])) {
                                    $errorInfo['order_code'] = $item['order_code'];
                                    $error[] = '服务商单号已经存在';
                                    break;
                                }
                            }
                        } elseif (!empty($serviceTracking) && trim($serviceTracking['order_code']) !== $row['order_code']) {
                            $errorInfo['order_code'] = $serviceTracking['order_code'];
                            $error[] = '服务商单号已经存在';
                        }
                    } else {
                        // 新增模式
                        if (count($numberRefTrack) > 0 || (!empty($serviceTracking) && 0 !== (int) $serviceTracking['stn_status'])) {
                            if(count($numberRefTrack) > 0){
                                $errorInfo['order_code'] = $numberRefTrack[0]['order_code'];
                            }else{
                                $errorInfo['order_code'] = $serviceTracking['order_code'];
                            }
                            $error[] = '服务商单号已经存在';
                        }
                    }
                }
                //服务商单号服务商单号+交易订单号需全局唯一
                /*$refTrackCondition = array(
            'reference_no'=>$row['reference_no'],
            'ref_tracking_number'=>$row['ref_tracking_number'],
            );
            if(isset($row['ordersCode']) && $row['ordersCode']!=''){
            $refTrackCondition['not_order_code'] = $row['ordersCode'];
            }
            if($row['order_mode_type']=='1'){
            if($row['change_order']=='0'){
            $numberRefTrack = Service_Orders::getByCondition($refTrackCondition,'count(*)');
            if($numberRefTrack>0&&!isset($row['order_code'])){
            $error[] = '服务商单号+交易订单号重复';
            }
            }
            }*/
            }
            //不换单，运输方式只能是Other
            /*if($row['change_order']=='0' && $row['sm_code']!='Other') {
        $error[] = '不换单运输方式只能是Other';
        } else if($row['change_order']=='1' && $row['sm_code']=='Other') {
        $error[] = '要换单运输方式不能是Other';
        }*/
        }
        if ("" == $row['warehouse_id']) {
            $error[] = Ec_Lang::getInstance()->getTranslate('MustSelectWarehouse'); //"必须选择仓库";
        }
        /*
        if("3" != $row['order_type']){
        if ("2" == $row['order_type'] && empty($row['to_warehouse_id'])) {
        $error[] = "10074 To Warehouse  required";
        }

        }//if("3" != $row['order_type'])
         */
        $customer   = Service_Customer::getByField($row['customer_id'], 'customer_id');
        if($row['sm_code']=="CNDHL"){
            $ftpMessageType = Service_FtpMessageType::getByField($customer['customer_code']."-CNDHL","fmt_code");
            if(empty($ftpMessageType)) $error[] = "运输方式CNDHL不可用";
        }
        $error1 = array();
        if($row['change_order'] != '0'){
            if ($row['order_type'] != 3) {
                $error1 = $this->validateCountryShippingMethod($row['oab_country_id'], $row['sm_code']);
            }
        }
        if ($error1) {$error = array_merge($error, $error1);}

        if ("" == $row['oab_firstname']) {
            $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '姓名必填'; //"姓必须填写";
        }else{
            if(strlen($row['oab_firstname'])>64){
                $error[] = "收件人姓名最长只能是64个字符";
            }
        }
        if ("" == $row['oab_company']) {
            //$error[] = "收件人公司名必填";//"收件人公司名必填";
        } else {
            if(strlen($row['oab_company'])>128){
                $error[] = "公司名最长128个字符";
            }
            if ($row['sm_code'] == 'HKDHL' || $row['sm_code'] == 'BH-HKDHL'||$row['sm_code'] == 'CNDHL'||$row['sm_code'] == 'WWDHLP'||$row['sm_code'] == 'WWDHLU') {
                if (strlen($row['oab_company']) > 35) {
                    $error[] = "WWDHLP,WWDHLU,HKDHL,CNDHL,BH-HKDHL公司名必须小于等于35个字符";
                }
            }
        }
        if(strlen($row['oab_state'])>60){
            $error[] = "州/区域最长60字符";
        }
        if(strlen($row['oab_city'])>60){
            $error[] = "收件人城市最长60字符";
        }
        //美国必填省份
        if ($row['oab_country_id'] == '253') {
            if ($row['oab_state'] == '') {
                $error[] = "州/区域必填";
            }
        }else{
            if($row['sm_code'] === '4PX-RU_POST-LINK_RMAIL'){
                if($row['oab_state'] == ''){
                    $error[] = "州/区域必填";
                }
            }
        }
        $needCity = array('WWDHLP','WWDHLU','HKDHL','BH-HKDHL','CNDHL','4PX-RU_POST-LINK_RMAIL','DHL-TH');
        if (in_array( $row['sm_code'],$needCity ) ) {
            if ($row['oab_city'] == '') {
                $error[] = "城市必填";
            }
        }

        if ($row['sm_code'] == "CJ-DGMG" || $row['sm_code'] == "CJ-DGMP") {
            if ($row['oab_state'] == '' && $row['oab_country_id'] != '253') {
                $error[] = "州/区域必填";
            }
            if ($row['oab_city'] == '') {
                $error[] = "城市必填";
            }
            if (empty($row['oab_postcode'])) {
                $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
            }
        }
        if(strlen($row['oab_postcode'])>60){
            $error[] = "邮编最长60字符";
        }

        if(($row['sm_code'] === 'CJ-DGMP'|| $row['sm_code'] === 'CJ-DGMG') && $row['order_type'] == '0'){
            $search = array(" ","　","\n","\r","\t");
            $row['oab_street_address1'] = str_replace($search,"",$row['oab_street_address1']);
            if(strstr(strtoupper($row['oab_street_address1']),'PACKSTATION')){
                $error[] = "当运输方式为{$row['sm_code']}时，地址1内不能包含‘PACKSTATION’";
            }
            $row['oab_street_address2'] = str_replace($search,"",$row['oab_street_address2']);
            if(strstr(strtoupper($row['oab_street_address2']),'PACKSTATION')){
                $error[] = "当运输方式为{$row['sm_code']}时，地址2内不能包含‘PACKSTATION’";
            }
        }

        //如果运输方式是HKDHL，要验证城市和邮编
        if ($row['sm_code'] === 'HKDHL' || $row['sm_code'] === 'BH-HKDHL'||$row['sm_code'] === 'CNDHL' || $row['sm_code'] === '4PX-HKDHL' || $row['sm_code'] === 'DGM-US'||$row['sm_code'] === 'WWDHLP'||$row['sm_code'] === 'WWDHLU') {
            /*if(empty($row['oab_postcode'])){
            $error[] = Ec_Lang::getInstance()->getTranslate('consignee').'邮编必填';;
            }*/
            if (empty($row['oab_city'])) {
                $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '城市必填';
            } else {
                $aCity = Service_City::getByWhere(array('country_id' => $row['oab_country_id'],'city_name' => $row['oab_city'],'sm_code' => $row['sm_code']));
                $is_exist = empty($list) && Service_City::getByWhere(array('country_id' => $row['oab_country_id'],'sm_code' => $row['sm_code']));
                if(empty($aCity) && empty($is_exist)){ 
                    $aCity = Service_City::getByWhere(array('country_id' => $row['oab_country_id'], 'city_name' => $row['oab_city'],'sm_code' =>'0'));
                }
                if (empty($aCity)) {
                    $error[] = '请填写正确的' . Ec_Lang::getInstance()->getTranslate('consignee') . '城市';
                } else { 
                    //非环球资源才验证邮编
                    if(Service_CustomerProcess::$HuanQiu != Service_CustomerProcess::getOwner( $customer['customer_code'] ) ){
                        $existPostcode = Service_Postcode::getByCondition(array('city_id' => $aCity['city_id']), "count(*)");
                        //某些城市不需要邮编
                        if ($existPostcode) {
                            if (!empty($row['oab_postcode'])) {
                                $tempPostCode=$row['oab_postcode'];
                                if($row['sm_code'] === 'BH-HKDHL'){
                                    //英国补两位后两位是字母
                                    if($row['oab_country_id']=='252'){
                                        if(!preg_match('/[A-Z0-9]{3,5}[A-Z]{2}$/',$row['oab_postcode'])){
                                            $error[]='邮编格式为城市邮编+两位大写字母补码';
                                        }else{
                                            $tempPostCode=  substr($row['oab_postcode'], 0, -2);
                                        }
                                    }
                                    //加拿大 A9A9A9 手动补1位
                                    if($row['oab_country_id']=='41'){
                                        if(!preg_match('/^([A-Z]{1}[0-9]{1}){3}$/',$row['oab_postcode'])){
                                            $error[]='邮编格式为城市邮编+一位数字补码';
                                        }else{
                                            $tempPostCode=  substr($row['oab_postcode'], 0, -1);
                                        }
                                    }
                                    //泽西岛（AA9 9AA，手动补3位）根西岛（AA9 9AA手动补三位）
                                    if($row['oab_country_id']=='119'||$row['oab_country_id']=='473'){
                                        if(!preg_match('/^[A-Z]{2}[0-9]{2}[A-Z]{2}$/',$row['oab_postcode'])){
                                            $error[]='邮编格式为城市邮编+一位数字和两位大写字母补码';
                                        }else{
                                            $tempPostCode=  substr($row['oab_postcode'], 0, -3);
                                        }
                                    }
                                }
                                $postcodes = Service_Postcode::getPostcodes($aCity['city_id'], $tempPostCode);
                                if (empty($postcodes)) {
                                    $error[] = '请填写正确的' . Ec_Lang::getInstance()->getTranslate('consignee') . '邮编';
                                    //$row['oab_postcode'] = '';
                                } else {
                                    if (!in_array($tempPostCode, $postcodes)) {
                                        $error[] = '请填写正确的' . Ec_Lang::getInstance()->getTranslate('consignee') . '邮编';
                                    }
                                }
                            } else {
                                if (empty($row['oab_postcode'])) {
                                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
                                }
                            }
                        }
                    }
                }
            }
        }
        $specialSmCodeArr = array(
            '4PX-OZXBTH',
            '4PX-LYT_GH',
            '4PX-EU_PACKET',
            '4PX-RU_POST-LINK_RMAIL',
            '4PX-Singapo_SPack_IMAIR',
            '4PX-SG_ordinary_mail+',
            'LYT-SMTGH-X',
        );
        if (in_array($row['sm_code'],$specialSmCodeArr)){
            foreach ($row['order_product'] as $key => $value) {
                if (strpos(strtolower($value['product_title_en']), 'gift') !== false || strpos(strtolower($value['product_title_en']), 'sample') !== false){
                    $error[] = "申报品名不能为GIFT，SAMPLE等笼统的品名";
                    break;
                }
            }
        }        
        
        switch ($row['sm_code']) {
            case "BH-AZAT-G";
                if(strlen($row['oab_firstname'])>50){
                    $error[] = "收件人姓名最长只能是50个字符";
                }
                if ($row['oab_state'] == '') {
                    $error[] = "州/区域必填";
                }else if(strlen($row['oab_state'])>50){
                    $error[] = "州/区域必填不能大于50个字符";
                }
                if ($row['oab_city'] == '') {
                    $error[] = "城市必填";
                }else if(strlen($row['oab_city'])>50){
                    $error[] = "城市不能大于50个字符";
                }
                if (empty($row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
                }else if(strlen($row['oab_postcode'])>20){
                    $error[] = "邮编长度不能大于20个字符";
                }
                break;
            case "WG-EUB-EBAY":
                if (empty($row['ref_tracking_number'])) {
                    $error[] = "服务商单号必填";
                }
                break;
            case "HKPG":
                if ($row['oab_state'] == '') {
                    $error[] = "州/区域必填";
                }
                if ($row['oab_city'] == '') {
                    $error[] = "城市必填";
                }
                if (empty($row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
                }
                if (strlen($row['oab_street_address1']) > 60) {
                    $error[] = "{$row['sm_code']}地址1不能大于60个字符";
                }
                if (strlen($row['oab_street_address2']) > 60) {
                    $error[] = "{$row['sm_code']}地址2不能大于60个字符";
                }
                break;
            case "SF-RUPR":
                @$re = self::validateMingan($row['order_product'],$row['sm_code']);
                if (!empty($re)) {
                    foreach ($re as $key => $s) {
                        $error[] = "英文申报品名根据服务商要求，申报品名包含敏感词[".$s."]禁止运输，请选择其他运输方式！";
                    }

                }
                break;
            case "PNLN":
                @$re = self::validateMingan($row['order_product'],$row['sm_code']);
                if (!empty($re)) {
                    foreach ($re as $key => $s) {
                        $error[] = "英文申报品名根据服务商要求，申报品名包含敏感词[".$s."]禁止运输，请选择其他运输方式！";
                    }

                }
                break;
            case "PNLG":
                @$re = self::validateMingan($row['order_product'],$row['sm_code']);
                if (!empty($re)) {
                    foreach ($re as $key => $s) {
                        $error[] = "英文申报品名根据服务商要求，申报品名包含敏感词[".$s."]禁止运输，请选择其他运输方式！";
                    }

                }
                break;
            case "SF-RUPT":
                @$re = self::validateMingan($row['order_product'],$row['sm_code']);
                if (!empty($re)) {
                    foreach ($re as $key => $s) {
                        $error[] = "英文申报品名根据服务商要求，申报品名包含敏感词[".$s."]禁止运输，请选择其他运输方式！";
                    }

                }
                break;
            case "HKPP":
                if ($row['oab_state'] == '') {
                    $error[] = "州/区域必填";
                }
                if ($row['oab_city'] == '') {
                    $error[] = "城市必填";
                }
                if (empty($row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
                }
                break;
            case "HKDHL":
                if (strlen($row['oab_street_address1']) > 35) {
                    $error[] = "{$row['sm_code']}地址1不能大于35个字符";
                }
                if (strlen($row['oab_street_address2']) > 70) {
                    $error[] = "{$row['sm_code']}地址2不能大于70个字符";
                }
                if (strlen($row['oab_firstname']) > 35) {
                    $error[] = "收件人姓名不能超过35个字符";

                }
                break;
            case 'WWDHLP':
            case 'WWDHLU':
            case "CNDHL":
                if (strlen($row['oab_street_address1']) > 35) {
                    $error[] = "{$row['sm_code']}地址1不能大于35个字符";
                }
                if (strlen($row['oab_street_address2']) > 70) {
                    $error[] = "{$row['sm_code']}地址2不能大于70个字符";
                }
                if (strlen($row['oab_firstname']) > 35) {
                    $error[] = "收件人姓名不能超过35个字符";

                }
                break;
            case "BH-HKDHL":
                if (strlen($row['oab_street_address1']) > 35) {
                    $error[] = "{$row['sm_code']}地址1不能大于35个字符";
                }
                if (strlen($row['oab_street_address2']) > 70) {
                    $error[] = "{$row['sm_code']}地址2不能大于35个字符";
                }
                if (strlen($row['oab_firstname']) > 35) {
                    $error[] = "收件人姓名不能超过35个字符";

                }
                foreach ($row['order_product'] as $key => $value) {
                    $p = Service_Product::getByField($value['product_id']);
                    if($p['with_battery']=="1"){
                        $filePath = APPLICATION_PATH . '/../data/file/BH-HKDHL-limit-country.xls';
                        $fileData = Common_Upload::readEXCEL($filePath);
                        $res      = 0;
                        foreach ($fileData as $k => $v) {
                            if ($k == 0) {
                                continue;
                            }
                            if( $country ) {
                                $str = strpos(strtolower($country['country_name']), strtolower($v[0]));
                                if (is_numeric($str)) {
                                    $res = 1;
                                    break;
                                }
                            }
                        }
                        if ($res) {
                            $error[] = "渠道【{$row['sm_code']}】国家【{$country['country_name']}】限制运输带电产品[{$p['product_sku']}]";
                        }
                    }
                }
                break;
            case 'UKTL':
                if (strlen($row['oab_firstname']) > 30) {
                    $error[] = "收件人姓名不能超过30个字符";
                }
                if (empty($row['oab_city'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '城市必填';
                }
                if (strlen($row['oab_city']) > 20) {
                    $error[] = "{$row['sm_code']}收件人城市长度不能超过20字符";
                }
                if (strlen($row['oab_street_address1']) > 30) {
                    $error[] = "{$row['sm_code']}地址1长度不能超过30个字符";
                }
                if ($row['oab_street_address1'] != "" && strpos($row['oab_street_address1'], ",") !== false) {
                    $error[] = "{$row['sm_code']}地址1不能有逗号";
                }
                if (strlen($row['oab_street_address2']) > 60) {
                    $error[] = "{$row['sm_code']}地址2长度不能超过60个字符";
                }
                if ($row['oab_street_address2'] != "" && strpos($row['oab_street_address2'], ",") !== false) {
                    $error[] = "{$row['sm_code']}地址2不能有逗号";
                }
                /*if(strlen($row['oab_street_address3'])>30){
                $error[] = "{$row['sm_code']}地址3不能大于30个字符";
                }*/
                if (strlen($row['oab_company']) > 30) {
                    $error[] = "UKTL公司名长度不能超过30个字符";
                }
                if (empty($row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
                }
                break;
            case "SZY-EUB":
            case "WG-EUB":
                //美国
                if ($row['oab_country_id'] == '253') {
                    if (!preg_match("/^[0-9]{5}(\-[0-9]{4}){0,1}+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:5位数字+短横线+4位数字或者5位数字";
                    }
                }
                //澳大利亚
                if ($row['oab_country_id'] == '13') {
                    if (!preg_match("/^[0-9]{4}+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:4位数字";
                    }
                }
                //英国
                if ($row['oab_country_id'] == '252') {
                    if (!preg_match("/^[0-9A-Za-z]{2,4}(\s)[0-9A-Za-z]{3}+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:2-4位数字或字母+空格+3位数字或字母";
                    }
                }
                //法国、乌克兰
                if ($row['oab_country_id'] == '82' || $row['oab_country_id'] == '250') {
                    if (!preg_match("/^[0-9]{5}+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:5位数字";
                    }
                }
                //俄罗斯
                if ($row['oab_country_id'] == '201') {
                    if (!preg_match("/^[0-9]{6}+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:6位数字";
                    }
                }
                //沙特阿拉伯
                if ($row['oab_country_id'] == '208') {
                    if (!preg_match("/^(\d{5}|\d{7}|(\d{5}\-\d{4}))$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:5位数字+短横线+4位数字 或 5位数字 或 7位数字";
                    }
                }
                if ($row['oab_country_id'] == "41") {
                    if (!preg_match("/^[A-Za-z]{1}[0-9]{1}[A-Za-z]{1}(\s){0,1}[0-9]{1}[A-Za-z]{1}[0-9]{1}+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:字母+数字+字母+空格+数字+字母+数字或字母+数字+字母+数字+字母+数字";
                    }
                }

                if ($row['oab_state'] == '') {
                    $error[] = "州/区域必填";
                }
                if ($row['oab_street_address1'] != "" && strpos($row['oab_street_address1'], "&") !== false) {
                    $error[] = "地址1不能有特殊字符&";
                }
                if ($row['oab_street_address2'] != "" && strpos($row['oab_street_address2'], "&") !== false) {
                    $error[] = "地址2不能有特殊字符&";
                }

                break;
            case "SZY-ETK":
                if ($row['oab_country_id'] == "33") {
                    if (!preg_match("/^[0-9]{5}(\-[0-9]{3})+$/", $row['oab_postcode'])) {
                        $error[] = "邮编格式不正确;正确格式:5位数字+短横线+3位数字";
                    }
                }
                //ETK到俄罗斯
                if ($row['oab_country_id'] == "201" && !preg_match("/^[0-9]{6}+$/", $row['oab_postcode'])) {
                    $error[] = "邮编格式不正确;正确格式:6位数字";
                }
                //ETK到白俄罗斯
                if ($row['oab_country_id'] == "39" && !preg_match("/^[0-9]{6}+$/", $row['oab_postcode'])) {
                    $error[] = "邮编格式不正确;正确格式:6位数字";
                }
                break;
            case 'BH-SFEP':
            case 'BH-USPS':
                if (!preg_match("/^[0-9]{5}(\-[0-9]{4}){0,1}+$/", $row['oab_postcode'])) {
                    $error[] = "邮编格式不正确;正确格式:5位数字+短横线+4位数字或者5位数字";
                }
                if ($row['oab_state'] == '') {
                    $error[] = "州/区域必填";
                }
                $validatorState = array("Alabama", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming");
                //州限制不区分大小写
                $validatorStateInArray = false;
                foreach ($validatorState as $validatorStateValue) {
                    if (strtolower($validatorStateValue) == strtolower($row['oab_state'])) {
                        $validatorStateInArray = true;
                    }
                }
                if (!$validatorStateInArray) {
                    $error[] = "州/区域不正确，必须填写美国的州/区域名称！";
                }
                if ($row['oab_street_address1'] != "" && strpos($row['oab_street_address1'], "&") !== false) {
                    $error[] = "地址1不能有特殊字符&";
                }
                if ($row['oab_street_address2'] != "" && strpos($row['oab_street_address2'], "&") !== false) {
                    $error[] = "地址2不能有特殊字符&";
                }
                if ((strlen($row['oab_street_address1']) + strlen($row['oab_street_address2'])) > 49) {
                    $error[] = "收件人地址1+地址2长度不能超过50";
                }
                @$re = self::validateMingan($row['order_product'],$row['sm_code']);
                if (!empty($re)) {
                    foreach ($re as $key => $s) {
                        $error[] = "英文申报品名根据服务商要求，申报品名包含[".$s."]禁止运输，请选择其他运输方式！";
                    }

                }
                break;
            case 'BH-DPD':
//                $supportCountry = array("AT", "BE", "BG", "HR", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "GB");
//                if (!in_array($reCountry['country_code'], $supportCountry)) {
//                    $error[] = "国家 {$reCountry['country_code']} 不支持 BH-DPD 运输方式 ";
//                }
                if( $country ) {
                    $result = @self::validatePostcode($country['country_code'], $row['oab_postcode']);
                    if (!$result) {
                        $error[] = "当前运输方式暂时不支持该国家此邮编的派送";
                    }
                }
                if (strlen($row['oab_city']) > 30 || empty($row['oab_city'])) {
                    $error[] = "收件人城市必填且长度不能超过30个字符";
                }
                if (strlen($row['oab_postcode']) > 9 || empty($row['oab_postcode'])) {
                    $error[] = "邮编必填且长度不能超过9个字符";
                }
                if (strlen($row['oab_firstname']) > 35) {
                    $error[] = "收件人姓名不能超过35个字符";
                }
                if (strlen($row['oab_street_address1'].$row['oab_street_address2']) > 70) {
                    $error[] = "收件人地址1+地址2不得超过70个字符";
                }
                @$re = self::validateMingan($row['order_product'],$row['sm_code']);
                if (!empty($re)) {
                    foreach ($re as $key => $s) {
                        $error[] = "英文申报品名根据服务商要求，申报品名包含[".$s."]禁止运输，请选择其他运输方式！";
                    }

                }
                break;
            case 'UTK':
                if (strlen($row['oab_firstname']) > 35) {
                    $error[] = "收件人姓名不能超过35个字符";

                }
                break;
            case "TWPG":
            case 'TWPP':
                if (strlen($row['oab_firstname']) > 15) {
                    $error[] = "收件人姓名不能超过15个字符";
                }
                if ((strlen($row['oab_street_address1']) + strlen($row['oab_street_address2'])) > 100) {
                    $error[] = "收件人地址1+地址2长度不能超过100";
                }
                if (!empty($row['oab_phone']) && strlen($row['oab_phone'])>20) {
                    $error[] = '收件人电话不能超过20个字符';
                 }
                 if (empty($row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee') . '邮编必填';
                }else{
                     if (strlen($row['oab_postcode']) > 10) {
                        $error[] = Ec_Lang::getInstance()->getTranslate('consignee')."邮编长度不能超过10个字符";
                     }
                }
                break;
            case '4PX-LYT_GH':
                if ($row['oab_country_id'] == 89) {
                    if ((strlen($row['oab_street_address1']) + strlen($row['oab_street_address2'])) > 35) {
                        $error[] = "收件人地址1+地址2不能超35个字符";
                    }
                    $address = $row['oab_street_address1']." ".$row['oab_street_address2'];
                    $addressArr = explode(" ",trim($address));
                    if(count($addressArr)>=2){
                        $regAddress = isset($addressArr[2])?$addressArr[1].$addressArr[2]:$addressArr[1];
                        if(!preg_match("/[0-9]{1,}/", $regAddress)){
                            $error[] = "渠道4PX-LYT_GH到德国地址的第二或第三个单词必须有数字";
                        }
                    }else{
                        if(!preg_match("/[0-9]{1,}/", $addressArr[0])){
                            $error[] = "渠道4PX-LYT_GH到德国地址必须有数字";
                        }
                    }
                    if ('1' == preg_match('/(P.O.BOX)/i', $row['oab_street_address1']) || '1' == preg_match('/(P.O.BOX)/i', $row['oab_street_address2'])){
                        $error[] = "不提供邮政信箱 (P.O.BOX) 地址派送服务，请重新提交";
                    }
                }
                if($row['oab_country_id']==253){
                   if(!in_array($row['is_pod'],array('0','1'))){
                        $error[] = "POD 必填";
                   }
                }
                //英国
                if($row['oab_country_id']==252){
                    if ('1' == preg_match('/(P.O.BOX)|(BFPO)/i', $row['oab_street_address1']) || '1' == preg_match('/(P.O.BOX)|(BFPO)/i', $row['oab_street_address2'])){
                        $error[] = "不提供邮政信箱 (P.O.BOX) 及英军信箱 (BFPO) 地址派送服务，请重新提交";
                    }
                }
            case '4PX-HKDHL':
                foreach ($row['order_product'] as $key => $value) {
                    $p = Service_Product::getByField($value['product_id']);
                    if($p['with_battery']=="1"){
                        $filePath = APPLICATION_PATH . '/../data/file/4PX-HKDHL-limit-country.xls';
                        $fileData = Common_Upload::readEXCEL($filePath);
                        $res      = 0;
                        foreach ($fileData as $k => $v) {
                            if ($k == 0) {
                                continue;
                            }
                            if( $country ) {
                                $str = strpos(strtolower($country['country_name']), strtolower($v[0]));
                                if (is_numeric($str)) {
                                    $res = 1;
                                    break;
                                }
                            }
                        }
                        if ($res) {
                            $error[] = "渠道【{$row['sm_code']}】国家【{$country['country_name']}】限制运输带电产品[{$p['product_sku']}]";
                        }
                    }
                }
                break;
			/*
            case 'BH-3H':
            case 'BH-UKECSLTYD':
            case 'BH-UKECSLTRM':
                $pattern = '/^(AB|BT|TD|DD|PH|ZE|KW|HS|IM|JE|GY|DG1[0-6]|G8[34]|KY(9|1[0456])|FK(1[489]|2[01])|IV([1245]|3[0126]|63)|EH(3[5-9]|4[0,2-6])|ML1[12]|PO[34]|KA2[78]|PA([2678]|3[0-8]|4[1-9])|TR2[1-5])/';
                if (preg_match($pattern, $row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee')."该邮编为偏远地区";
                }
                break;
			*/
            case 'BH-CORREOS':
                $pattern = '/^(5[12]|07|3[58])/';
                if (preg_match($pattern, $row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee')."该邮编为偏远地区";
                }
                break;
            case 'BH-19EURDPDDE':
                $pattern = '/^(18565|83(209|256)|258(45|49|59|63|69)|259(38|46|80|92|96|99)|264(65|74|86)|265(48|71|79)|26757|2749[89])$/';
                if (preg_match($pattern, $row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee')."该邮编为偏远地区";
                }
                break;
            case 'BH-DAC':
                $pattern = '/^(3012[1-6]|04027|3013[23]|30135|3014[12]|5703[0-4,6-9]|58012|8007[1,3-7,9]|910(17|23)|98055|0[7-9][\d]{3}|8[7-9][\d]{3}|9[\d]{4})$/';
                if (preg_match($pattern, $row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee')."该邮编为偏远地区";
                }
                break;
            case 'BH-SL018':
                $pattern = '/^9(7[1-8]|8[4,6-8])/';
                if (preg_match($pattern, $row['oab_postcode'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('consignee')."该邮编为偏远地区";
                }
                break;
            case "DHL-TH":
                if (strlen($row['oab_street_address1']) > 35) {
                    $error[] = "{$row['sm_code']}地址1不能大于35个字符";
                }
                if (strlen($row['oab_street_address2']) > 35) {
                    $error[] = "{$row['sm_code']}地址2不能大于70个字符";
                }
                break;
            default:
                break;
        }
        if (in_array($row['sm_code'], array('4PX-LYT_GH', '4PX-EU_PACKET', '4PX-RU_POST-LINK_RMAIL', '4PX-HKDHL', '4PX-Singapo_SPack_IMAIR', '4PX-SG_ordinary_mail+', '4PX-OZXBTH','LYT-SMTGH-X'))) {
            if ((strlen($row['oab_street_address1']) + strlen($row['oab_street_address2'])) >= 120) {
                $error[] = "收件人地址1+地址2长度不能超过120个字符";
            }
        }

        if ("" == $row['reference_no']) {
            //$error[] =  '交易订单号'.Ec_Lang::getInstance()->getTranslate('require');//"姓必须填写";
        } else {

            if (!preg_match("/^[0-9a-zA-Z-_]{1,18}$/", $row['reference_no'])) {
                //$error[] = '交易订单号必须由字母或数字或横杠或下划线构成，并且最多18位.';
            }

            $condition = array(
                'reference_no'=>$row['reference_no'],
                'order_status_arr'=>array(1,2,3,4,5,6,7,8,9,10,11,12,13,14),
            );
            $os = Service_Orders::getByCondition($condition);
            //$os = Service_Orders::getByCondition(array('reference_no'=>$row['reference_no'],'customer_id'=>$row['customer_id']));
            if($row['action']=='add' && $os){
              $error[] = "系统已存在交易订单号";
              $errorInfo['order_code'] = isset($os['order_code'])?$os['order_code']:'';
          }
            if( isset($row['action']) && $row['action']=='update'){
                if($os){
                    foreach($os as $o){
                        if($o['order_code']!=$row['ordersCode']){
                            $error[] = "系统已存在交易订单号";
                            $errorInfo['order_code'] = $o[0]['order_code'];
                        }
                    }
                }
            }

            /*
        if(0==2){

        $orders = Service_Orders::getByCondition(array('reference_no'=>$row['reference_no'],'customer_id'=>$row['customer_id']));
        if($row['ordersCode']){
        if($orders){
        foreach($orders as $o){
        if($o['order_code']!=$row['ordersCode']){
        $error[] = '交易订单号已经存在'."-->{$ordersCode}";
        }
        }
        }

        }

        if(empty($row['ordersCode'])){
        if(!empty($orders)){
        $error[] = "交易订单号已经存在--->".$row['reference_no'];
        }
        }

        }
         */
        }

        if ("" == $row['oab_street_address1']) {
            // $error[] = I18n::getInstance()->translate("0000012");//产品重量不能为空
            $error[] = Ec_Lang::getInstance()->getTranslate('AddressOneRequired'); //"地址一必须填写";
        }

        if ("" == $row['oab_phone']) {
            $error[] = "收件人电话必须填写";
        } else {
            if(strlen($row['oab_phone'])>25){
                $error[] = "收件人电话最长只能是25个字符";
            }
            if ($row['sm_code'] == 'SF-RUPR' || $row['sm_code'] == 'SF-RUPT') {
                if (!(preg_match("/^[0-9-+\s]{5,}$/", $row['oab_phone']))) {
                    $error[] = "收件人电话必须为数字或横杠或者加号或者空格并且至少5位数";
                }
            } else {
                if (!(preg_match("/^[0-9-+\/()\s]+$/", $row['oab_phone']))) {
                    $error[] = "收件人电话必须为数字或横杠或斜杠或者加号.";
                }
            }

        }
        if ("" != $row['oab_email'] && preg_match("/^[a-zA-Z0-9_\.-]+\@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}$/i", $row['oab_email']) === false) {
            $error[] = Ec_Lang::getInstance()->getTranslate('EmaiFormatError'); //"Emai格式错误";
        }

        if ($row['currency_code'] == "") {
            //$error[] = "成交币种必须选择."; //"成交价格";
        } else {
            $currency = Service_Currency::getByField($row['currency_code'], 'currency_code', "*");
            if (!$currency) {
                $error[] = "非法的交易币种."; //"成交价格";
            }
        }
        if ($row['charge'] == '') {
            //$error[] = "成交总价必填."; //"成交价格";
        } else {
            if (!(is_numeric($row['charge']) && $row['charge'] > 0)) {
                $error[] = "成交总价必须是大于0的数值."; //"成交价格";
            }
        }

        //检查保险
        $buyInsuranceShipMethod = Service_ShippingMethod::getBuyInsuranceShipMethod();
        if( isset( $row['sm_code'] ) && $row['sm_code'] !== '' && isset( $row['insurance'] ) &&  $row['insurance'] == 1 ) {
            if( isset( $row['currency_code'] ) && $row['currency_code'] === '' ) {
                $error[] = '币种必填';
            }
            if( !in_array( $row['sm_code'],$buyInsuranceShipMethod) ) {
                $error[] = "运输方式".$row['sm_code'].'未支持购买保险';
            }
            if( $row['charge'] === '' ){
                $error[] = "成交总价必填";
            }
            if( !isset($row['insurance_code']) || trim($row['insurance_code']) === '' ) {
                $error[] = "保险项目不能为空";
            } else {
                //检查保险项目是否存在
                $tmpItem = Service_OtherFee::getByField(trim($row['insurance_code']),'fee_code');
                if( empty($tmpItem) )
                    $error[] = "保险项目不存在";
                else if($tmpItem['status'] != 1)
                    $error[] = "保险不可用";
            }

            if( !isset($row['insurance_rate']) || !is_numeric($row['insurance_rate']) || $row['insurance_rate'] < 1 || $row['insurance_rate'] > 1.1) {
                $error[] = "投保金额率大于等于1，且小于等于1.1，有效小数位：2位";
            }
        }

        // HKDHL对收件人信息进行验证，指接收英文字符，所有出现在LABEL上的信息都应该验证
        if (in_array(strtoupper(trim($row['sm_code'])), array('HKDHL','BH-HKDHL','CNDHL','DHL-TH','WWDHLU','WWDHLP'))) {
            // HKDHL不接受&，否则&及其之后的内容会被清掉
            $hkdhlPattern = '/^[a-zA-Z0-9' . preg_quote('~`!@#$%^*()_-+={[}]|\:;"\'<,>.?/ ', '/') . ']+$/';

            // 收件人姓名
            if (!empty($row['oab_firstname']) && !preg_match($hkdhlPattern, $row['oab_firstname'])) {
                $error[] = '收件人姓名含有非英语字符或&字符';
            }

            // 收件人公司
            if (!empty($row['oab_company']) && !preg_match($hkdhlPattern, $row['oab_company'])) {
                $error[] = '收件人公司含有非英语字符或&字符';
            }

            // 收件人省份/州
            if (!empty($row['oab_state']) && !preg_match($hkdhlPattern, $row['oab_state'])) {
                $error[] = '收件人州/区域含有非英语字符或&字符';
            }

            // 收件人城市
            if (!empty($row['oab_city']) && !preg_match($hkdhlPattern, $row['oab_city'])) {
                $error[] = '收件人城市含有非英语字符或&字符';
            }

            // 收件人地址1
            if (!empty($row['oab_street_address1']) && !preg_match($hkdhlPattern, $row['oab_street_address1'])) {
                $error[] = '收件人地址1含有非英语字符或&字符';
            }

            // 收件人地址2
            if (!empty($row['oab_street_address2']) && !preg_match($hkdhlPattern, $row['oab_street_address2'])) {
                $error[] = '收件人地址2含有非英语字符或&字符';
            }

            // 收件人邮编
            if (!empty($row['oab_postcode']) && !preg_match($hkdhlPattern, $row['oab_postcode'])) {
                $error[] = '收件人邮编含有非英语字符或&字符';
            }

            // 收件人电话
            if (!empty($row['oab_phone']) && !preg_match($hkdhlPattern, $row['oab_phone'])) {
                $error[] = '收件人电话含有非英语字符或&字符';
            }
        }

        //hkdhl验证发件人
        /* if($row['sm_code']=='HKDHL'){
        if(!isset($row['addressSender'])){
        $error[] = '地址信息必须填写';
        }else{
        $addressSender = $row['addressSender'];
        if ("" == $addressSender['oab_firstname']) {
        $error[] = '发件人姓名必填';//"姓必须填写";
        }
        if ("" == $addressSender['oab_state']) {
        $error[] = '发件人省份必填';//"姓必须填写";
        }
        if ("" == $addressSender['oab_city']) {
        $error[] = '发件人城市必填';//"姓必须填写";
        }
        if ("" == $addressSender['oab_street_address1']) {
        $error[] = '发件人地址必填';//"地址一必须填写";
        }

        if ("" == $addressSender['oab_phone']) {
        //$error[] = "10079 Consignee PhoneNo required";
        }else{
        if (!(preg_match("/^[0-9-\/]+$/",$addressSender['oab_phone']) )) {
        $error[] = "发件人电话必须为数字或横杠或斜杠.";
        }

        }
        if ("" != $addressSender['oab_email'] &&  preg_match("/^[a-zA-Z0-9_\.-]+\@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}$/i", $addressSender['oab_email'])===false) {
        $error[] = '发件人Email必填';//"Emai格式错误";
        }
        }
        } */

        //检查物流信息
        if( $row['sm_code']=="DGF-CARGO"){
            $shippingInfo = isset( $row['shippingInfo'] ) ? $row['shippingInfo'] : array();
            if(empty($shippingInfo)){
                $error[] = '缺少物流信息';
            }else{
                //校验具体每一项，机场三字码
                if(isset($shippingInfo['destination']) && $shippingInfo['destination']!='' && !empty( $country ) ){
                    //查找目的港的有效性,加上国家
                    //$airMap = Service_AirportCountryMap::getByField($shippingInfo['destination'],'airport_destination');
                    $condition = array(
                        'airport_destination' => $shippingInfo['destination'],
                        'country_code' => $country['country_code'],
                    );
                    $airMap = Service_AirportCountryMap::getByCondition( $condition );
                    if(empty($airMap)){
                        $error[] = "目的港无效";
                    }
                }else{
                    $error[] = "目的港必填";
                }
                //校验具体每一项，isDGD	是(1)/否(0)危险货品申报
                if(isset($shippingInfo['isDGD'])){
                    if(!in_array($shippingInfo['isDGD'],array('0','1'))){
                        $error[] = "是否危险品只能填0或者1";
                    }
                }else{
                    $shippingInfo['isDGD']='0';
                }
                //校验具体每一项，hsDescription 货物描述及唛头
                if(!(isset($shippingInfo['hsDescription']) && $shippingInfo['hsDescription']!='')){
                    $error[] = "货物描述及唛头必填";
                }
                //校验insuredAccount
                if( isset($shippingInfo['insuredAccount']) && $shippingInfo['insuredAccount']!=='' && !is_null( $shippingInfo['insuredAccount'] ) ){
                    if( !is_numeric($shippingInfo['insuredAccount']) || $shippingInfo['insuredAccount'] <= 0){
                        $error[] = "投保金额必须是正数";
                    }
                }
            }
        }
        $errorInfo['error'] = $error;
        return $errorInfo;
    }
    public static function validateMingan($row,$sm_code)
    {
        // print_r($row);exit;
        $keyData = array('顺丰国际电商专递'=>array('BH-DPD'),'顺丰国际小包挂号'=>array('PNLG','SF-RUPR'),'顺丰国际小包挂号（美国）'=>array('BH-USPS','BH-SFEP'),'顺丰国际小包平邮'=>array('PNLN','SF-RUPT'));
        $keyMinGan = '';
        foreach ($keyData as $key => $value) {
            if(in_array($sm_code, $value)){
                $keyMinGan = $key;
                break;
            }
        }
        $filePath = APPLICATION_PATH . '/../data/file/mingan.xls';
        $fileData = Common_Upload::readEXCEL($filePath);
        $return   = array();
        if (!empty($row)) {
            foreach ($row as $key => $value) {
                foreach ($fileData as $k => $file) {
                    if ($k == 0) {
                        continue;
                    }
                    if($file[0]==$keyMinGan){
                        $str = strpos(strtolower($value['product_title_en']), strtolower($file[1]));
                        if (is_numeric($str)) {
                            $return[] = $file[1];
                            break;
                        }
                    }
                }
            }
        }
        return $return;
    }
    public static function validatePostcode($countryCode, $postCode)
    {
        $filePath = APPLICATION_PATH . '/../data/file/BH-DPDPostcode.xlsx';
        $fileData = Common_Upload::readEXCEL($filePath);
        $return   = 1;
        if (!empty($fileData)) {
            foreach ($fileData as $key => $value) {
                if ($key == 0) {
                    continue;
                }

                $country[] = $value[1];
                if ($countryCode == $value[1]) {
                    if (strlen($postCode) == strlen($value[2])) {
                        if(is_numeric($value[2])&&is_numeric($value[2])&&is_numeric($postCode)){
                            if ( $postCode >= $value[2] && $postCode <= $value[3]) {
                                $return = 0;
                                break;
                            }
                        }
                    }
                    /*if (!is_numeric($postCode) && $countryCode == 'NL') {
                        $rule = "/^\d{4}[a-zA-Z]{2}$/";
                        preg_match($rule, $postCode, $result);
                        if ($result) {
                            $str = substr($postCode, 0, 4);
                            if ($str >= 1011) {
                                $return = $result;
                                break;
                            }
                        }
                    }*/
                }
            }
//            if (!in_array($countryCode, $country)) {
//                $return = 1;
//            }
        }
        return $return;
    }
    private function validateProduct($order_product, $orderRow = '')
    {
        $err = array();

        if (empty($order_product) || !is_array($order_product)) {
            $err[] = Ec_Lang::getInstance()->getTranslate('ProductsMusBeSelected'); //"必须选择产品";
        }

        $parcelArr = array(
            'parcel_declared_value' => '',
            'parcel_contents'       => '',
            'parcel_quantity'       => '',
        );
        $total_purpose_declare = 0;
        $productHscode         = array();
        $withBatteryQuantity   = 0;//统计一个订单内，带电池产品数量
        foreach ($order_product as $v) {
            $product_id  = $v['product_id'];
            $qty         = trim($v['qty']);
            $haveDeclare = false;

            $product_title_en = $v['product_title_en'];
            if (trim($product_title_en) == '') {
                $err[] = '英文名称不能为空';
            } else {
                /*if (in_array($orderRow['sm_code'],array('4PX-EU_PACKET','4PX-HKDHL','4PX-LYT_GH','4PX-RU_POST-LINK_RMAIL','4PX-SG_ordinary_mail+','4PX-Singapo_SPack_IMAIR')) && !preg_match("/^[0-9a-zA-Z\- ]+$/", trim($product_title_en))){
                    $err[] = "英文名称[".$product_title_en."] 只能包含英文字母、数字、空格和 - ";
                }*/
            }

            $product = Service_Product::getByField($product_id, 'product_id');
            if($product['product_status']!="1"){
                $err[] = $product['product_sku']." 未备案";
            }
            /*if(in_array($product['hs_code'],array('8504409999','9023009000','8414809090','9018909010'))){
            $err[] = "海关编码是8504409999、9023009000、8414809090、9018909010的产品不能下单";
            }*/
            //限制运输带电产品的渠道
            if( $product['with_battery'] == 1 ) {
                $allow = self::allowTakeBattery( $orderRow['sm_code'], $orderRow['oab_country_id'], $product['battery_type'] );
                if( !$allow['allow'] ) {
                    $err[] = '产品sku['. $product['product_sku'] .']:'.$allow['msg'];
                }
		$withBatteryQuantity += $qty;

                if(in_array($orderRow['sm_code'], array( 'CJ-DGMG','CJ-DGMP'))){
                    if($withBatteryQuantity > 2){
                        $err[0] = '当运输方式为:CJ-DGMG/CJ-DGMP,订单内的带电产品数量不能超过2个!';
                        return $err;
                    }
                }
            }


            if (!in_array($product['hs_code'], $productHscode)) {
                $productHscode[] = $product['hs_code'];
            }
            $hs_code = Service_Hscodes::getByField($product['hs_code'], 'hs_code');
            if ($hs_code['hs_code_status'] == '-1') {
                $err[] = "产品sku:" . $product['product_sku'] . "海关编码{$product['hs_code']}已废止";
            }
            if (isset($v['declare_price']) && $v['declare_price'] != "") {
                $declare_price = trim($v['declare_price']);
                $haveDeclare   = true;
            } else {
                $declare_price = $product['product_declared_value'];
            }
            $purpose_declared_value = $v['op_declared_value'];
            if (empty($product)) {
//忽略不存在的产品
                $err[] = "找不到ID为{$product_id}的产品.";
                //continue;
            }

            if (!(preg_match("/^[0-9]+$/", $qty) && is_numeric($qty) && $qty > 0)) {
                $err[] = "产品sku{$product['product_sku']}数量必须大于0的整数-->[{$product['product_sku']}]";
                //continue;
            }
            if ($haveDeclare) {
                if (!is_numeric($declare_price) || $declare_price <= 0) {
                    $err[] = "产品sku{$product['product_sku']}申报单价必须大于0的数字-->[{$product['product_sku']}]";
                } /*elseif($declare_price<($product['product_declared_value']*0.8)){
            $err[] = "产品sku{$product['product_sku']}申报单价必须不能低于产品的备案价值的80%";
            }elseif($declare_price>$product['product_declared_value']*1.2){
            $err[] = "产品sku{$product['product_sku']}申报单价不能高与产品备案价值的120%";
            }*/
            }
            if (empty($purpose_declared_value) || !(is_numeric($purpose_declared_value) && $purpose_declared_value > 0)) {
                $err[] = "产品sku{$product['product_sku']}目的海关申报单价大于0的数字-->[{$product['product_sku']}]";
            }
            if (isset($orderRow['sm_code']) && $orderRow['sm_code'] == 'HKDHL' || $orderRow['sm_code'] == "SZY-EUB" || $orderRow['sm_code'] == "WG-EUB" || $orderRow['sm_code'] == "CJ-DGMG" || $orderRow['sm_code'] == "CJ-DGMP" || $orderRow['sm_code'] == 'BH-HKDHL'||$orderRow['sm_code'] == 'CNDHL'||$orderRow['sm_code'] == 'WWDHLP'||$orderRow['sm_code'] == 'WWDHLU') {
                if (empty($product_title_en)) {
                    $err[] = "产品sku{$product['product_sku']}英文品名必填-->[{$product['product_sku']}]";
                }
            }
            if ($product['currency_code'] != "") {
                $currency = Service_Currency::getByField($product['currency_code'], 'currency_code', "*");
            } else {
                $currency = Service_Currency::getByField('RMB', 'currency_code', "*");
            }

            $parcelArr['parcel_declared_value'] += $declare_price * $qty * $currency['currency_rate'];
            $parcelArr['parcel_contents'] .= $product['product_title'] . "[" . $product['product_sku'] . "]x" . $qty . "<br/>";
            $parcelArr['parcel_quantity'] += $qty;
            $total_purpose_declare += $purpose_declared_value * $qty;
            if ($v['ebay_item_id'] == "" && $orderRow['sm_code'] == "WG-EUB-EBAY") {
                $err[] = "WG-EUB-EBAY产品sku[{$product['product_sku']}]ebay物品号必填";
            }
            if ($v['ebay_item_id'] == "" && $orderRow['sm_code'] == "WG-EUB-EBAY") {
                $err[] = "WG-EUB-EBAY产品sku[{$product['product_sku']}]ebay交易订单号必填";
            }
            if ($v['ebay_item_id'] == "" && $orderRow['sm_code'] == "WG-EUB-EBAY") {
                $err[] = "WG-EUB-EBAY产品sku[{$product['product_sku']}]ebay卖家id必填";
            }
            if (($orderRow['sm_code'] == 'BH-USPS'||$orderRow['sm_code'] == 'BH-SFEP' || $orderRow['sm_code'] == 'BH-DPD' || $orderRow['sm_code'] == 'SF-RUPT' || $orderRow['sm_code'] == 'SF-RUPR' || $orderRow['sm_code'] == 'PNLN' || $orderRow['sm_code'] == 'PNLG') && $product['product_title_en'] == '' && $product_title_en == '') {
                $err[] = "{$product['product_sku']} {$orderRow['sm_code']} 英文品名不能为空";
            }
            if ($orderRow['sm_code'] == 'BH-USPS'||$orderRow['sm_code'] == 'BH-SFEP' || $orderRow['sm_code'] == 'BH-DPD' || $orderRow['sm_code'] == 'SF-RUPT' || $orderRow['sm_code'] == 'SF-RUPR' || $orderRow['sm_code'] == 'PNLN' || $orderRow['sm_code'] == 'PNLG' && $product_title_en == '') {
                if (!empty($product['product_title_en'])) {
                    $keyData = array('顺丰国际电商专递'=>array('BH-DPD'),'顺丰国际小包挂号'=>array('PNLG','SF-RUPR'),'顺丰国际小包挂号（美国）'=>array('BH-USPS','BH-SFEP'),'顺丰国际小包平邮'=>array('PNLN','SF-RUPT'));
                    $keyMinGan = '';
                    foreach ($keyData as $key => $value) {
                        if(in_array($orderRow['sm_code'], $value)){
                            $keyMinGan = $key;
                            break;
                        }
                    }
                    $filePath = APPLICATION_PATH . '/../data/file/mingan.xls';
                    $fileData = Common_Upload::readEXCEL($filePath);
                    $res      = 0;
                    if($keyMinGan){
                        foreach ($fileData as $k => $v) {
                            if ($k == 0) {
                                continue;
                            }
                            if($v[0]==$keyMinGan){
                                $str = strpos(strtolower($v['product_title_en']), strtolower($v[1]));
                                if (is_numeric($str)) {
                                    $res = 1;
                                    break;
                                }
                            }
                        }
                        if ($res) {
                            $err[] = "英文申报品名根据服务商要求，申报品名包含[".$v[1]."]禁止运输，请选择其他运输方式！";
                        }
                    }
                }
            }
            //检查产品重量尺寸 环球客户
            /*if( in_array($orderRow['customer_code'],array('E0693','E0174')) && in_array( $orderRow['sm_code'], array('HKDHL','BH-HKDHL')) ) {
                $pieces = isset( $orderRow['piecesDetail'] ) ? $orderRow['piecesDetail'] : array();
                if( false === $this->checkPieces( $pieces ) ) {
                    $error[] = 'piecesDetail数据异常';
                }
            }*/
        }
        if ($orderRow['sm_code'] == 'HKPG') {
            $purpose_totalDeclareHK = Service_Currency::converByCode("USD", "HKD", $total_purpose_declare);
            if ($purpose_totalDeclareHK > 3000) {
                $err[] = "HKPG总目的海关申报价值大于3000HKD";
            }
        }
        if ($orderRow['sm_code'] == "SZY-EUB" || $orderRow['sm_code'] == "WG-EUB") {
            if ($total_purpose_declare > 30 && $orderRow['oab_country_id'] == "82") {
                $err[] = "SZY-EUB、WG-EUB到法国的目的海关申报单价不能超过30美元";
            }
        }
        if ($orderRow['sm_code'] == "PNLN") {
            $purpose_totalDeclareEUR = Service_Currency::converByCode("USD", "EUR", $total_purpose_declare);
            if ($purpose_totalDeclareEUR > 22) {
                $err[] = "PNLN总目的海关申报价值不能超过22欧元";
            }
        }
        if ($orderRow['sm_code'] == 'HKDHL' || $orderRow['sm_code'] == 'BH-HKDHL' || $orderRow['sm_code'] == '4PX-HKDHL'){
            if($orderRow['is_fba']==1 && $orderRow['is_fba_tax']==0){
                $err[] = "当运输方式为HKDHL、BH-HKDHL、4PX-HKDHL时，若其是否FBA为是，则目的地关税自动对应为预付。";
            }
        }
		if (($orderRow['sm_code'] == 'ALBP-P' || $orderRow['sm_code'] == 'BH-BPP')&&in_array($orderRow['oab_country_id'],array('14','22','36','64','65','66','75','81','82','89','92','107','113','115','131','137','138','147','168','192','195','199','216','217','221','229','252'))){
            $purpose_totalDeclareEUR = Service_Currency::converByCode("USD", "EUR", $total_purpose_declare);
            if ($purpose_totalDeclareEUR > 22) {
                $err[] = "总目的海关申报价值大于22EUR";
            }
        }
        if(in_array($orderRow['sm_code'],array('BH-3HPA','BH-3H','BH-UKECSLTYD','BH-UKECSLTRM','BH-CORREOS','BH-19EURDPDDE','BH-DAC','BH-SL018','BH-IESLTANPOST'))){
            if($total_purpose_declare>165){
                $err[] = "渠道[".$orderRow['sm_code']."]货物申报价值不能大于165美金。";
            }
        }
        if(in_array($orderRow['sm_code'],array('ALBP-EU','BH-BPEU'))){
            if ($total_purpose_declare > 22) {
                $err[] = "总目的海关申报价值大于22USD";
            }
        }
        if( $orderRow['sm_code'] == 'DHL-TH' && $withBatteryQuantity > 2 ){
            $err[] = "当运输方式为DHL-TH时，带电产品总数不能超过2。";
        }
        if (count($productHscode) > 20) {
            $err[] = "海关系统不接收超过20个海关编码的订单";
        }
        $this->_parcel = $parcelArr;
        return $err;
    }

    public function validateCountryShippingMethod($countryId = null, $shippingMethod = null)
    {
        $err = array();
        if (empty($countryId) || empty($shippingMethod)) {
            if (empty($countryId)) {
                $err[] = Ec_Lang::getInstance()->getTranslate('RecipientCountryRequired'); //'收件人国家必填';
            }
            if (empty($shippingMethod)) {
                $err[] = Ec_Lang::getInstance()->getTranslate('ShippingMethodRequired'); //'运输方式必填';
            }
        } else {
            $country = Common_DataCache::getCountry($countryId);
            if (empty($country)) {
                $err[] = Ec_Lang::getInstance()->getTranslate('CountriesDoNotExist'); //'国家不存在';
            }

            $shippingMethods = Common_DataCache::getShippingMethod();
            $smCodes         = array();
            foreach ($shippingMethods as $sm) {
                $smCodes[] = $sm['sm_code'];
            }
            if (!in_array($shippingMethod, $smCodes)) {
                $err[] = Ec_Lang::getInstance()->getTranslate('ShippingMethodDoNotExist'); //'运输方式不存在';
            }
            $con = array(
                'sm_code'    => $shippingMethod,
                'country_id' => $countryId,
            );

            $countryMapRows = Service_SmCountryMap::getByCondition($con);

            if (empty($countryMapRows)) {
                $err[] = 'country -->' . $country['country_code'] . Ec_Lang::getInstance()->getTranslate('DoesNotSupportTheShippingMethod') . '-->' . $shippingMethod;
            }
        }
        return $err;
    }

    /**
     * @todo 检查是否偏远城市
     * @author solar
     * @param $country_id
     * @param $city_name
     * @param $postcode
     * @return boolean
     */
    public function isRemoteCity($country_id, $city_name, $postcode)
    {
        $aCity = Service_City::getByWhere(array('country_id' => $country_id, 'city_name' => strtoupper($city_name)));
        if (!empty($aCity)) {
            if ($aCity['is_remote'] == 1) {
                return true;
            } else {
                $condition = array(
                    'country_id'  => $country_id,
                    'postcode_no' => $postcode,
                    'is_remote'   => '1',
                );
                $counts = Service_Postcode::getByCondition($condition, 'count(*)');
                if ($counts > 0) {
                    return true;
                } else {
                    $condition = array(
                        'country_id'        => $country_id,
                        'postcode_no_start' => $postcode,
                        'postcode_no_end'   => $postcode,
                        'is_remote'         => '1',
                    );
                    $counts = Service_Postcode::getByCondition($condition, 'count(*)');
                    if ($counts > 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /*订单的建立*/
    public function createOrderTransaction($row)
    {
        //$this->initPieceDetail();

        $row['action'] = 'add';
        $result        = array("ask" => 0, "message" => Ec_Lang::getInstance()->getTranslate('CreateOrdersFailed')); //"创建订单失败"
        //$error         = $this->validateProduct($row['order_product'], $row);
        if ($row['order_type'] == 3) {
            $row['shipping_method'] = 'SELFPICKUP';
        }
        /*
        //订单模式 0:备货模式 1:集货模式
        if($row['order_mode_type']=='1'){
        if($row['change_order']!='1'&&$row['change_order']!='0'){
        $error[] = Ec_Lang::getInstance()->getTranslate('WhetherChangeSingle').Ec_Lang::getInstance()->getTranslate('require');
        }
        //假如是集货模式  如果选了 是否的情况  服务商单号就必填
        if($row['change_order']=='0' && $row['ref_tracking_number']==''){
        $error[] = "服务商单号必填";
        }else{
        if($row['ref_tracking_number']!=''&&$row['sm_code']!=''){
        //验证同一个运输方式的服务商单号的唯一性
        $refTrackCondition = array(
        'sm_code'=>$row['sm_code'],
        'ref_tracking_number'=>$row['ref_tracking_number']
        );
        $numberRefTrack = Service_Orders::getByCondition($refTrackCondition,'count(*)');
        if($numberRefTrack>0){
        $error[] = '该运输方式的服务商单号重复';
        }
        }
        }
        //不换单，运输方式只能是Other
        if($row['change_order']=='0' && $row['sm_code']!='Other') {
        $error[] = '不换单运输方式只能是Other';
        } else if($row['change_order']=='1' && $row['sm_code']=='Other') {
        $error[] = '要换单运输方式不能是Other';
        }
        }
         */
        //$error1 = $this->validateInput($row);
        //if (!empty($error1['error'])) {$error = array_merge($error, $error1['error']);}

        if ($row['order_mode_type'] == '0') {
            /* if($row['change_order']=='1'){
            $error[] = Ec_Lang::getInstance()->getTranslate('DeliveryModeCanNotChangeSingle');
            } */
            //备货模式一定换单 使用自有渠道 不是自有运输方式
            $row['change_order'] = '1';
        }
	 //派送通知服务、保障服务
        if(($row['sm_code'] == "BH-DHL-HKDELIVERY")){
            if((($row['dispatch_notice'] === '') || ($row['guarantee'] === ''))){
                $error = '运输方式为BH-DHL-HKDELIVERY时，派送通知服务、保障服务选项为必填';
            }
        }else{
            $row['dispatch_notice'] = $row['guarantee'] = '0';
        }
        $validateObj = new Service_OrderDataValidate();
        if( !$validateObj->validate( $row ) ) {
            $error = $validateObj->getError();
        } else {
            $this->_parcel = $validateObj->getParcel();
        }
        $row = $validateObj->getOrder();
        if (!empty($error)) {
            $result['error'] = $error;
            $result['order_code'] = isset($error1['order_code'])?$error1['order_code']:"";
            return $result;
        }
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        $session     = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {

            $customer   = Service_Customer::getByField($row['customer_id'], 'customer_id');
            $ordersCode = Common_GetNumbers::getCode('order', $customer['customer_code'], 'SO');
            $time       = date("Y-m-d H:i:s");

            $parcel = $this->_parcel;
            //             print_r($parcel);exit;
            $currency              = Service_Currency::getByField($customer['customer_currency'], 'currency_code', "*");
            $parcel_quantity       = $parcel['parcel_quantity'];
            $parcel_contents       = $parcel['parcel_contents'];
            $parcel_declared_value = $parcel['parcel_declared_value'];
            $plateform = isset($row['platform']) ? $row['platform'] : "0";
            if( Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $customer['customer_code'] ) ) {
                $plateform = 2;
            }
            $orderRow = array(
                'order_code'            => $ordersCode,
                'customer_id'           => $row['customer_id'],
                'customer_code'         => $customer['customer_code'],
                'warehouse_id'          => $row['warehouse_id'],
                'order_type'            => $row['order_type'],
                'sm_code'               => $row['sm_code'],
                'parcel_declared_value' => round($parcel_declared_value / $currency['currency_rate'], 2),
                'shipping_fee_estimate' => '0', //暂时还没明确怎么计算
                'currency_code'         => $customer['customer_currency'],
                'parcel_contents'       => $parcel_contents,
                'parcel_quantity'       => $parcel_quantity,
                'order_status'          => '1',
                'reference_no'          => $row['reference_no'],
                'currency_code'         => $row['currency_code'],
                'charge'                => $row['charge'],
                'add_time'              => $time,
                'update_time'           => $time,
                'remark'                => $row['remark'],
                'delivery_address'      => $row['delivery_address'],
                'platform'              => $plateform,
                'trade_mode'            => isset($row['trade_mode']) ? $row['trade_mode'] : "",
                'is_fba' => isset($row['is_fba']) ? $row['is_fba'] : '0',
                'is_fba_tax' => isset($row['is_fba_tax']) ? $row['is_fba_tax'] : '0',
                'is_pod' => isset($row['is_pod']) ? $row['is_pod'] : '0',
		'insurance' => isset($row['insurance']) && $row['insurance'] == 1 ? 1 : 0,
                'insurance_rate' => isset($row['insurance_rate']) && $row['insurance'] == 1 ? $row['insurance_rate'] : 1,
                'insurance_code' => isset($row['insurance_code']) && $row['insurance'] == 1 ? $row['insurance_code'] : '',
                'dispatch_notice'=>$row['dispatch_notice'],
                'guarantee'      =>$row['guarantee']
            );
            $orderRow['order_pick_type'] = '0';
            $orderProducts               = $row['order_product'];
            if (count($orderProducts) >= 2) {
                $orderRow['order_pick_type'] = '2';
            } else {
                if (isset($orderProducts[0]['qty']) && $orderProducts[0]['qty'] > 1) {
                    $orderRow['order_pick_type'] = '1';
                }
            }
            if ($row['order_mode_type'] == '1') {
                $orderRow['order_mode_type']     = '1';
                $orderRow['change_order']        = $row['change_order'];
                $orderRow['ref_tracking_number'] = $row['ref_tracking_number'];
            } else {
                $orderRow['order_mode_type']     = '0';
                $orderRow['change_order']        = '1'; //备货模式一定换单
                $orderRow['ref_tracking_number'] = ''; //服务商单号为客户填写
            }
            if ($orderRow['sm_code'] == "WG-EUB-EBAY") {
                $orderRow['ref_tracking_number'] = isset($row['ref_tracking_number']) ? $row['ref_tracking_number'] : "";
            }

            //如果是偏远城市或者地区，增加提示信息
            $orderRow['is_remote_city'] = 0;
            $isRemoteCity               = false;
            $checkRemote = array('WWDHLP','WWDHLU','HKDHL','HTTX-HKDHL','BH-HKDHL','CNDHL','4PX-HKDHL','DHL-TH','DGM-US','DHL-BH03');
            if ( in_array( $row['sm_code'], $checkRemote ) ) {
                $isRemoteCity = $this->isRemoteCity($row['oab_country_id'], $row['oab_city'], $row['oab_postcode']);
                if ($isRemoteCity === true) {
                    $orderRow['is_remote_city'] = 1;
                }
                if($row['sm_code'] == 'CNDHL'){
                    $orderRow['is_remote_city'] = 0;
                }

            } else {
                $isRemoteCity = Service_Remote::checkRemote($row['oab_country_id'], $row['oab_city'], $row['oab_postcode'], $orderRow['sm_code'], $row['warehouse_id']);
                if ($isRemoteCity === true) {
                    $orderRow['is_remote_city'] = 1;
                }

            }
            $order_id = Service_Orders::add($orderRow);

            $row['order_id'] = $order_id;
            $row['order_code'] = $ordersCode;

            if (!$order_id) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorCreateOrderFails'));
            }

            $w = Service_Warehouse::getByField($orderRow['warehouse_id'], 'warehouse_id', '*');
            if ($orderRow['order_mode_type'] == '0') {
                $sotDescription = '备货订单新建成功,草稿状态';
                $warehouseName  = $w['warehouse_desc'];
            } else {
                $sotDescription = '集货订单新建成功,草稿状态';
                $warehouseName  = "客户仓库";
            }
            $shipOrderTracking = array(
                'order_code'          => $ordersCode,
                'sot_location'        => $warehouseName,
                'sot_add_time'        => $time,
                'warehouse_id'        => $orderRow['warehouse_id'],
                'sot_description'     => $sotDescription,
                'sot_type'            => '0',
                'sot_time_offset'     => '',
                'tracking_number'     => $ordersCode,
                'ref_tracking_number' => '',
                'status_desc'         => '草稿',
                'user_id'             => -1 * $sessionData['id'],
            );
            Service_ShipOrderTracking::add($shipOrderTracking);

            //print_r($row);
            /*$addressRow = array(
            'orders_code'=>$ordersCode,
            'oa_consignee_first_name'=>$row['consignee_first_name'],
            'oa_consignee_last_name'=>$row['consignee_last_name'],
            'oa_consignee_company'=>$row['consignee_company'],
            'oa_consignee_country_id'=>$row['consignee_country_id'],
            'oa_consignee_zip'=>$row['consignee_zip'],
            'oa_consignee_region'=>$row['consignee_region'],
            'oa_consignee_city'=>$row['consignee_city'],
            'oa_consignee_address1'=>$row['consignee_address1'],
            'oa_consignee_address2'=>$row['consignee_address2'],
            'oa_consignee_address3'=>$row['consignee_address3'],
            'oa_consignee_phone'=>$row['consignee_phone'],
            'oa_consignee_email'=>$row['consignee_email'],
            'oa_modify_time'=>$time,
            );*/
            //收件人
            $addressBookRow = array(
                'order_id'            => $order_id,
                'order_code'          => $ordersCode,
                'oab_firstname'       => $row['oab_firstname'],
                'oab_lastname'        => $row['oab_lastname'],
                'oab_company'         => $row['oab_company'] ? $row['oab_company'] : $row['oab_firstname'],
                'oab_country_id'      => $row['oab_country_id'],
                'oab_postcode'        => $row['oab_postcode'],
                'oab_state'           => $row['oab_state'],
                'oab_city'            => $row['oab_city'],
                'oab_street_address1' => $row['oab_street_address1'],
                'oab_street_address2' => $row['oab_street_address2'],
                'oab_phone'           => $row['oab_phone'],
                'oab_cell_phone'      => $row['oab_phone'],
                'oab_email'           => $row['oab_email'],
                'oab_type'            => '0',
            );

            if (!Service_OrderAddressBook::add($addressBookRow)) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorOrdersAddressWriteFailure') . "...-->" . $ordersCode);
            }
            /*if($row['sm_code']=='HKDHL'){
            $addressSender = $row['addressSender'];
            //$stateinfo = Service_Region::getByField($addressSender['oab_state_id']);
            //$cityinfo = Service_Region::getByField($addressSender['oab_city_id']);
            //发件人信息
            $addressBookRow = array(
            'order_id'=>$order_id,
            'order_code'=>$ordersCode,
            'oab_firstname'=>$addressSender['oab_firstname'],
            'oab_lastname'=>$addressSender['oab_lastname'],
            'oab_company'=>$addressSender['oab_company'],
            'oab_postcode'=>$addressSender['oab_postcode'],
            'oab_country_id'=>'49',
            'oab_state_id'=>'0',
            'oab_state'=>$addressSender['oab_state'],
            'oab_city_id'=>'0',
            'oab_city'=>$addressSender['oab_city'],
            'oab_street_address1'=>$addressSender['oab_street_address1'],
            'oab_street_address2'=>$addressSender['oab_street_address2'],
            'oab_phone'=>$addressSender['oab_phone'],
            'oab_cell_phone'=>$addressSender['oab_phone'],
            'oab_email'=>$addressSender['oab_email'],
            'oab_type'=>'1',
            );
            if(!Service_OrderAddressBook::add($addressBookRow)){
            throw new Exception("发件人信息出错....-->".$ordersCode);
            }
            }*/
            $totaldeclare = 0;
            foreach ($row['order_product'] as $k=>$v) {
                $productId     = $v['product_id'];
                $qty           = trim($v['qty']);

                $row['order_product'][$k]['qty'] = $qty;

                $declare_price = 0;
                $haveDeclare   = false;
                if (isset($v['declare_price'])) {
                    $declare_price = trim($v['declare_price']);
                    $haveDeclare   = true;
                }
                $product_title_en = $v['product_title_en'];

                $purpose_declared_value = $v['op_declared_value'];

                $product = Service_Product::getByField($productId, 'product_id');

                /* $orderProductRow = array(
                'orders_code' => $ordersCode,
                'product_id' => $productId,
                'op_quantity' => $qty,
                'attribute' => empty($v['attribute']) ? "" : $v['attribute'],
                'product_barcode' => $product['product_barcode'],
                'op_unit_price' => ! empty($v['op_unit_price']) ? $v['op_unit_price'] : $product['product_declared_value'],

                'op_weight' => ! empty($v['weight']) ? $v['weight'] : $product['product_weight'],
                'product_title' => ! empty($v['product_title']) ? $v['product_title'] : $product['product_title'],
                'product_title_cn' => ! empty($v['product_title_cn']) ? $v['product_title_cn'] : $product['product_title_cn'],

                'hs_code' => empty($row['hs_code']) ? "" : $v['hs_code'],
                'op_ref_tnx' => empty($v['op_ref_tnx']) ? "" : $v['op_ref_tnx'],
                'op_ref_item_id' => empty($v['op_ref_item_id']) ? "" : $v['op_ref_item_id'],
                'op_ref_buyer_id' => empty($v['op_ref_buyer_id']) ? "" : $v['op_ref_buyer_id'],
                'op_ref_paydate' => empty($v['op_ref_paydate']) ? "" : $v['op_ref_paydate'],

                'op_last_update' => $time,
                ); */
                if (!$haveDeclare) {
                    //没有设置declare 就用订单的declare_value
                    $declare_price = $product['product_declared_value'];
                }
                if (empty($product_title_en)) {
                    //没传递就用产品的的
                    $product_title_en = $product['product_title_en'];
                }
                $orderProductRow = array(
                    'order_id'                  => $order_id,
                    'order_code'                => $ordersCode,
                    'product_id'                => $productId,
                    'product_barcode'           => $product['product_barcode'],
                    'product_title_en'          => $product_title_en,
                    'op_quantity'               => $qty,
                    'op_declared_value'         => $declare_price,
                    'op_purpose_declared_value' => $purpose_declared_value,
                    'op_category'               => $product['pc_id'],
                    'op_add_time'               => $time,
                );

                $totaldeclare += $purpose_declared_value * $qty;
                $op_id = Service_OrderProduct::add($orderProductRow);
                if (!$op_id) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorOrdersAddressWriteFailure') . "....-->" . $ordersCode, '50000');
                }

                $row['order_product'][$k]['op_id'] = $op_id;
                $row['order_product'][$k]['product_id'] = $product['product_id'];
                $row['order_product'][$k]['product_title'] = $product['product_title'];
                $row['order_product'][$k]['product_title_en'] = $product_title_en;
                $row['order_product'][$k]['product_sales_value'] = $product['product_sales_value'];
                $row['order_product'][$k]['product_declared_value'] = $product['product_declared_value'];
                $row['order_product'][$k]['hs_code'] = $product['hs_code'];

                if ($orderRow['sm_code'] == "WG-EUB-EBAY") {
                    $ebayOrderDetail = array(
                        'op_id'                     => $op_id,
                        'order_code'                => $ordersCode,
                        'ebay_item_id'              => $v['ebay_item_id'],
                        'ebay_transaction_id'       => $v['ebay_transaction_id'],
                        'ebay_buyer_id'             => $v['ebay_buyer_id'],
                        'ebay_item_title'           => '',
                        'ebay_email'                => '',
                        'sold_qty'                  => $qty,
                        'posted_qty'                => $qty,
                        'order_sales_record_number' => '',
                        //'order_id',
                        'ebay_site_id'              => '',
                        'received_amount'           => '',
                        'payment_date'              => '',
                        'sold_price'                => '',
                        'sold_date'                 => '',
                        'currency_code'             => '',
                        'ebay_message'              => '',
                        'paypal_email'              => '',
                        'paypal_message'            => '',
                        'note'                      => '',
                    );
                    Service_EbayOrderDetail::add($ebayOrderDetail);
                }

            }

            /*if($row['order_type']==3||$row['order_type']==4){
                $orderShipping = array(
                    'order_code'=>$ordersCode,
                    'notify_tel'=>$row['shippingInfo']['notifyTel'],
                    'notify_contact'=>$row['shippingInfo']['notifyContact'],
                    'notify_addr'=>$row['shippingInfo']['notifyAddr'],
                    'discharge_port'=>$row['shippingInfo']['dischargePort'],
                    'destination'=>$row['shippingInfo']['destination'],
                    'service_model'=>$row['shippingInfo']['serviceModel'],
                    'delivery_terms'=>$row['shippingInfo']['deliveryTerms'],
                    'hs_code'=>$row['shippingInfo']['hsCode'],
                    'is_dgd'=>$row['shippingInfo']['isDGD'],
                    'hs_description'=>$row['shippingInfo']['hsDescription'],
                    'pkg_total_amt'=>$row['shippingInfo']['pkgTotalAmt'],
                    'pkg_total_vol'=>$row['shippingInfo']['pkgTotalVol'],
                    'pkg_gw'=>$row['shippingInfo']['pkgGW'],
                    'pkg_vw'=>$row['shippingInfo']['pkgVW'],
                    'is_battery'=>$row['shippingInfo']['isBattery'],
                    'is_battery_rmk'=>$row['shippingInfo']['isBatteryRmk'],
                    'insured_account'=>$row['shippingInfo']['insuredAccount'],
                );
                Service_OrderShipping::add($orderShipping);
                if(!empty($row['shippingInfo']['package'])){
                    $prodetail = array();
                    $pradetail=$row['shippingInfo']['package'];
                    if(!empty($pradetail) && is_array($pradetail['0'])){

                    }else{
                        $pradetail = array($pradetail);
                    }
                    foreach($pradetail as $key=>$value){
                        $packageRow = array(
                            'order_code'=>$ordersCode,
                            'amt'=>$value['amt'],
                            'pkg_type'=>$value['pkgType'],
                            'pkg_length'=>$value['length'],
                            'pkg_width'=>$value['width'],
                            'pkg_height'=>$value['height'],
                        );
                        Service_Package::add($packageRow);
                    }
                }
            }*/
            if ($orderRow['sm_code'] == 'DGF-CARGO'){
                $orderShipping = array(
                    'order_code'=>$ordersCode,
                    'notify_tel'=>$row['shippingInfo']['notifyTel'],
                    'notify_contact'=>$row['shippingInfo']['notifyContact'],
                    'notify_addr'=>$row['shippingInfo']['notifyAddr'],
                    'discharge_port'=>$row['shippingInfo']['dischargePort'],
                    'destination'=>$row['shippingInfo']['destination'],
                    'service_model'=>$row['shippingInfo']['serviceModel'],
                    'delivery_terms'=>$row['shippingInfo']['deliveryTerms'],
                    //'hs_code'=>$row['shippingInfo']['hsCode'],
                    'is_dgd'=>$row['shippingInfo']['isDGD'],
                    'hs_description'=>$row['shippingInfo']['hsDescription'],
                    //'pkg_total_amt'=>$row['shippingInfo']['pkgTotalAmt'],
                    //'pkg_total_vol'=>$row['shippingInfo']['pkgTotalVol'],
                    //'pkg_gw'=>$row['shippingInfo']['pkgGW'],
                    //'pkg_vw'=>$row['shippingInfo']['pkgVW'],
                    'is_battery'=>$row['shippingInfo']['isBattery'],
                    'is_battery_rmk'=>$row['shippingInfo']['isBatteryRmk'],
                    'insured_account'=>$row['shippingInfo']['insuredAccount'],
                );
                Service_OrderShipping::add($orderShipping);
                /*if(!empty($row['shippingInfo']['package'])){
                    $prodetail = array();
                    $pradetail=$row['shippingInfo']['package'];
                    if(!empty($pradetail) && is_array($pradetail['0'])){

                    }else{
                        $pradetail = array($pradetail);
                    }
                    foreach($pradetail as $key=>$value){
                        $packageRow = array(
                            'order_code'=>$ordersCode,
                            'amt'=>$value['amt'],
                            'pkg_type'=>$value['pkgType'],
                            'pkg_length'=>$value['length'],
                            'pkg_width'=>$value['width'],
                            'pkg_height'=>$value['height'],
                        );
                        Service_Package::add($packageRow);
                    }
                }*/
            }
            if ($orderRow['sm_code'] == 'HKPG') {
                $totaldeclareHK = Service_Currency::converByCode("USD", "HKD", $totaldeclare);
                if ($totaldeclareHK > 3000) {
                    throw new Exception("HKPG总目的海关申报价值大于3000HKD");
                }
            }

            $order = Service_Orders::getByField($ordersCode, 'order_code');

            $orderOperateType = Service_OrderOperationType::getByField('add', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $order_id,
                    'order_code'   => $ordersCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }

            $oot = array(
                'order_id'     => $order_id,
                'order_code'   => $ordersCode,
                'confirm_time' => date("Y-m-d H:i:s"),
                //'creater_id'=>$sessionData['id']
            );
            $oot['creater_id'] = isset($sessionData['id']) ? $sessionData['id'] : $orderRow['customer_id'];
            Service_OrderOperationTime::add($oot);

            $logRow = array(
                'order_id'          => $order_id,
                'order_code'        => $ordersCode,
                'ol_type'           => '1',
                'order_status_from' => $order['order_status'],
                'order_status_to'   => $order['order_status'],
                'ol_add_time'       => $time,
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($logRow);
            if($orderRow['reference_no']!=""){
                // 添加预警
                Service_Precaution::insert(array(
                    'precaution_value' => $orderRow['reference_no'],
                ));
            }
            //$this->writeOrderLog($logRow);
            $message = Ec_Lang::getInstance()->getTranslate('CreateOrder') . " [{$ordersCode}]" . Ec_Lang::getInstance()->getTranslate('success');
            if ($isRemoteCity === true) {
                $message .= '<br>订单属于偏远地区，如需修改，请在草稿状态下进行编辑修改';
            }
            if (($orderRow['sm_code'] =='HKDHL'||$orderRow['sm_code']=="CNDHL"||$orderRow['sm_code']=="WWDHLP"||$orderRow['sm_code']=="WWDHLU") && $totaldeclare>120) {
                $message .= '<br>该订单目的海关申报价大于120USD，将产生超值报关费';
            }
             //高风险地区附加费
            $cityArr=array("阿富汗","布隆迪","伊拉克","利比亚","马里","尼日尔","南苏丹","叙利亚","也门");
            //受限制地区附加费
            $cityArr1=array("中非共和国","象牙海岸","刚果民主共和国","厄立特里亚","伊拉克","伊朗","朝鲜","利比亚","利比里亚","索马里","苏丹","叙利亚","也门");
            if ($orderRow['sm_code'] == 'HKDHL'||$orderRow['sm_code'] == 'BH-HKDHL'||$orderRow['sm_code'] == 'CNDHL'||$orderRow['sm_code']=="WWDHLP"||$orderRow['sm_code']=="WWDHLU") {
                $country=Service_Country::getByField($row['oab_country_id'],'country_id');
                if (in_array($country['country_name'],$cityArr)){
                    $message .= '<br><font style="color:red;">订单号为'.$ordersCode.'需支付高风险地区附加费</font>';
                }
                if (in_array($country['country_name'],$cityArr1)){
                    $message .= '<br><font style="color:red;">订单号为'.$ordersCode.'需支付受限制地区附加费</font>';
                }
            }


            $result = array("ask" => 1, "message" => $message, 'ordersCode' => $ordersCode);
            $messageTip='';
            $invoceContry=Service_ShippingMethodConfig::getInvoiceContry();
            if (in_array($orderRow['sm_code'],array('HKDHL','BH-HKDHL','CNDHL','WWDHLP','WWDHLU'))&&in_array($row['oab_country_id'],$invoceContry)) {
                if($orderRow['sm_code']=="BH-HKDHL"&&($row['oab_country_id']=="132"||$row['oab_country_id']=="128")){
                   $messageTip= '<br><span style="color:red">订单'.$ordersCode.'需提供正本发票,可在系统中的业务管理模块下载</span>';
                }elseif($row['oab_country_id']!='251'){
                   $messageTip= '<br><span style="color:red">该订单需提供正本发票</span>';
                }else{
                    if($totaldeclare>  Service_ShippingMethodConfig::$purPusDecalar){
                       $messageTip= '<br><span style="color:red">该订单需提供正本发票</span>';
                    }
                }
            }
            if ($orderRow['sm_code'] =='BH-DPD') {
                $totaldeclareEUR = Service_Currency::converByCode("USD", "EUR", $totaldeclare);
                if($totaldeclareEUR >= 50){
                    $messageTip .= '<br><span style="color:red;">订单号为'.$ordersCode.'有机会被征收关税</span>';
                }
            }

            if (in_array($orderRow['sm_code'], array('4PX-LYT_GH', '4PX-EU_PACKET')) && $totaldeclare >= 20) {
                $messageTip .= '<br><span style="color:red;">订单号为'.$ordersCode.'包裹申报价值大于等于15英镑(20美金)，无论当地是否实际产生税金，均需提前支付20%的关税</span>';
            }
            if(($orderRow['sm_code'] === 'CJ-DGMP'|| $orderRow['sm_code'] === 'CJ-DGMG') && $orderRow['order_type'] == '0'){
                $search = array(" ","　","\n","\r","\t");
                $oab_street_address1 = str_replace($search,"",$row['oab_street_address1']);
                $oab_street_address2 = str_replace($search,"",$row['oab_street_address2']);
                $is_contain = false;
                if(strstr(strtoupper($oab_street_address1),'POSTOFFICE')){
                    $is_contain = true;
                }
                if(strstr(strtoupper($oab_street_address2),'POSTOFFICE')){
                    $is_contain = true;
                }
                if(strstr(strtoupper($oab_street_address1),'POSTBOX')){
                    $is_contain = true;
                }
                if(strstr(strtoupper($oab_street_address2),'POSTBOX')){
                    $is_contain = true;
                }
                if($is_contain === true){
                    $messageTip .= '<br><span style="color:red;">订单号为'.$ordersCode.'地址内包含POST OFFICE/POST BOX，派送不会另行通知</span>';
                }
            }

            $this->addShipOrder($row);

            $message .=$messageTip;
            $result = array("ask" => 1, "message" => $message, 'ordersCode' => $ordersCode,'messageTip'=>$messageTip);
            $db->commit();
            //$db->rollback();
        } catch (Exception $e) {
            $db->rollback();
            $result = array("ask" => 0, "message" => $e->getMessage(), 'errorCode' => $e->getCode());
        }
        //发邮件通知
        $params = array(
            'subject'     => $row['customer_id'] . ' create order ' . $ordersCode,
            'customer_id' => $row['customer_id'],
            'body'        => 'create orders ' . $ordersCode,
        );
        //Common_Service_EmailProccess::autoSendMail($params);
        return $result;
    }

    /*订单的修改*/
    public function updateOrderTransaction($row, $ordersCode, $customerId = '')
    {
        $this->initPieceDetail();

        $result = array("ask" => 0, "message" => Ec_Lang::getInstance()->getTranslate('UpdateOrderFailed'));
        $order  = Service_Orders::getByField($ordersCode, 'order_code');
        //exit('ccc');
        if (empty($order)) {
            $result['message']   = Ec_Lang::getInstance()->getTranslate('OrderCodeDoesNotExist') . "-->{$ordersCode}";
            $result['errorCode'] = '10055';
            return $result;
        }
        if ($order['customer_id'] != $customerId) {
//非本人不能更新
            $result['message']   = Ec_Lang::getInstance()->getTranslate('FailedUpdateOrderAuthorityNotEnough'); //"更新订单失败,权限不够";
            $result['errorCode'] = '10080';
            return $result;
        }
        //草稿状态能更新，其他状态不可更新
        if ($order['order_status'] != 1) {
            $result['message']   = Ec_Lang::getInstance()->getTranslate('OrderStatusDoesNot') . "-->{$ordersCode}";
            $result['errorCode'] = '10071';
            return $result;
        }
        /*$error             = $this->validateProduct($row['order_product'], $row);
        $row['order_code'] = $ordersCode;
        $error1            = $this->validateInput($row);
        $error             = array_merge($error, $error1['error']);*/
        //不换单，运输方式只能是Other
        /*if($row['change_order']=='0' && $row['sm_code']!='Other') {
        $error[] = '不换单运输方式只能是Other';
        } else if($row['change_order']=='1' && $row['sm_code']=='Other') {
        $error[] = '要换单运输方式不能是Other';
        }*/
        if ($row['order_type'] == 3) {
            $row['sm_code'] = 'SELFPICKUP';
        }
        $validateObj = new Service_OrderDataValidate();
        if( !$validateObj->validate( $row ) ) {
            $error = $validateObj->getError();
        } else {
            $this->_parcel = $validateObj->getParcel();
        }
        $row = $validateObj->getOrder();
	//派送通知服务、保障服务
        if(($row['sm_code'] == "BH-DHL-HKDELIVERY")){
            if((($row['dispatch_notice'] == '') || ($row['guarantee'] == ''))){
                $error = '运输方式为BH-DHL-HKDELIVERY时，派送通知服务、保障服务选项为必填';
            }
        }else{
            $row['dispatch_notice'] = $row['guarantee'] = '0';
        }
        //var_dump($row); exit();

        if (!empty($error)) {
            $result['error'] = $error;
            $result['order_code'] = isset($error1['order_code'])?$error1['order_code']:"";
            return $result;
        }

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $time = date("Y-m-d H:i:s");

            $parcel                = $this->_parcel;
            $parcel_quantity       = $parcel['parcel_quantity'];
            $parcel_contents       = $parcel['parcel_contents'];
            $parcel_declared_value = $parcel['parcel_declared_value'];

            $orderRow = array(
                'warehouse_id'          => $row['warehouse_id'],
                'order_type'            => $row['order_type'],
                'sm_code'               => $row['sm_code'],
                'parcel_declared_value' => $parcel_declared_value,
                'shipping_fee_estimate' => '0', //暂时还没明确怎么计算
                'parcel_contents'       => $parcel_contents,
                'parcel_quantity'       => $parcel_quantity,
                'update_time'           => $time,
                'reference_no'          => $row['reference_no'],
                'currency_code'         => $row['currency_code'],
                'ref_tracking_number'   => $row['ref_tracking_number'],
                'charge'                => $row['charge'],
                'remark'                => $row['remark'],
                'delivery_address'      => $row['delivery_address'],
                'is_fba' => isset($row['is_fba']) ? $row['is_fba'] : '0',
                'is_fba_tax' => isset($row['is_fba_tax']) ? $row['is_fba_tax'] : '0',
                'is_pod' => isset($row['is_pod']) ? $row['is_pod'] : '0',
		'insurance' => isset($row['insurance']) && $row['insurance'] == 1 ? 1 : 0,
                'insurance_rate' => isset($row['insurance_rate']) && $row['insurance'] == 1 ? $row['insurance_rate'] : 1,
                'insurance_code' => isset($row['insurance_code']) && $row['insurance'] == 1 ? $row['insurance_code'] : '',
                'dispatch_notice'=>$row['dispatch_notice'],
                'guarantee'      =>$row['guarantee']
            );

            $orderRow['order_pick_type'] = '0';
            $orderProducts               = $row['order_product'];
            if (count($orderProducts) >= 2) {
                $orderRow['order_pick_type'] = '2';
            } else {
                if (isset($orderProducts[0]['qty']) && $orderProducts[0]['qty'] > 1) {
                    $orderRow['order_pick_type'] = '1';
                }
            }
            if ($row['change_order'] == '1') {
                //为否
                $orderRow['change_order'] = '1';
            } else {
                $orderRow['change_order'] = '0';
            }
            if ($row['order_mode_type'] == '1') {
                $orderRow['ref_tracking_number'] = $row['ref_tracking_number'];
            } else {
                $orderRow['ref_tracking_number'] = '';
                $orderRow['change_order']        = '1'; //备货一定不是客户自由渠道
            }
            $orderRow['is_remote_city'] = 0;
            $isRemoteCity               = false;
            $checkRemote = array('WWDHLP','WWDHLU','HKDHL','HTTX-HKDHL','BH-HKDHL','CNDHL','4PX-HKDHL','DHL-TH','DGM-US','DHL-BH03');
            if ( in_array( $row['sm_code'], $checkRemote ) ) {
                $isRemoteCity = $this->isRemoteCity($row['oab_country_id'], $row['oab_city'], $row['oab_postcode']);
                if ($isRemoteCity === true) {
                    $orderRow['is_remote_city'] = 1;
                }
                if($row['sm_code'] == 'CNDHL'){
                    $orderRow['is_remote_city'] = 0;
                }

            } else {
                $isRemoteCity = Service_Remote::checkRemote($row['oab_country_id'], $row['oab_city'], $row['oab_postcode'], $orderRow['sm_code'], $orderRow['warehouse_id']);
                if ($isRemoteCity === true) {
                    $orderRow['is_remote_city'] = 1;
                }

            }
            // print_r($orderRow);exit;
            if (!Service_Orders::update($orderRow, $ordersCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorFailedUpdateOrder'));
            }

            $row['order_id'] = $order['order_id'];
            $row['order_code'] = $ordersCode;

            Service_OrderAddressBook::delete($ordersCode, 'order_code');

            //$addressSender = $row['addressSender'];
            //$stateinfo = Service_Region::getByField($addressSender['oab_state_id']);
            //$cityinfo = Service_Region::getByField($addressSender['oab_city_id']);
            $addressBookRow = array(
                'order_id'            => $order['order_id'],
                'order_code'          => $ordersCode,
                'oab_firstname'       => $row['oab_firstname'],
                'oab_lastname'        => $row['oab_lastname'],
                'oab_company'         => $row['oab_company'] ? $row['oab_company'] : $row['oab_firstname'],
                'oab_country_id'      => $row['oab_country_id'],
                'oab_postcode'        => $row['oab_postcode'],
                'oab_state'           => $row['oab_state'],
                'oab_city'            => $row['oab_city'],
                'oab_street_address1' => $row['oab_street_address1'],
                'oab_street_address2' => $row['oab_street_address2'],
                'oab_phone'           => $row['oab_phone'],
                'oab_cell_phone'      => $row['oab_phone'],
                'oab_email'           => $row['oab_email'],
                'oab_type'            => '0',
            );
            if (!Service_OrderAddressBook::add($addressBookRow)) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorOrdersAddressWriteFailure') . "...-->" . $ordersCode);
            }
            /* if (! Service_OrderAddressBook::update($addressBookRow, $ordersCode, 'order_code')) {
            throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorFailedUpdateOrder'),'50000');
            } */
            /* if($row['sm_code']=='HKDHL'){
            $addressSender = $row['addressSender'];
            //$stateinfo = Service_Region::getByField($addressSender['oab_state_id']);
            //$cityinfo = Service_Region::getByField($addressSender['oab_city_id']);
            //发件人信息
            $addressBookRow = array(
            'order_id'=>$order['order_id'],
            'order_code'=>$ordersCode,
            'oab_firstname'=>$addressSender['oab_firstname'],
            'oab_lastname'=>$addressSender['oab_lastname'],
            'oab_company'=>$addressSender['oab_company'],
            'oab_postcode'=>$addressSender['oab_postcode'],
            'oab_country_id'=>'49',
            'oab_state_id'=>'0',
            'oab_state'=>$addressSender['oab_state'],
            'oab_city_id'=>'0',
            'oab_city'=>$addressSender['oab_city'],
            'oab_street_address1'=>$addressSender['oab_street_address1'],
            'oab_street_address2'=>$addressSender['oab_street_address2'],
            'oab_phone'=>$addressSender['oab_phone'],
            'oab_cell_phone'=>$addressSender['oab_phone'],
            'oab_email'=>$addressSender['oab_email'],
            'oab_type'=>'1',
            );
            if(!Service_OrderAddressBook::add($addressBookRow)){
            throw new Exception("发件人信息出错....-->".$ordersCode);
            }
            } */
            Service_OrderProduct::delete($ordersCode, 'order_code');
            Service_EbayOrderDetail::delete($ordersCode, "order_code");

            $purpose_totalDeclare = 0;
            foreach ($row['order_product'] as $k=>$v) {
                $productId = $v['product_id'];
                $qty       = trim($v['qty']);

                $declare_price = 0;
                $haveDeclare   = false;
                if (isset($v['declare_price']) && $v['declare_price'] > 0) {
                    $declare_price = trim($v['declare_price']);
                    $haveDeclare   = true;
                }
                $product_title_en = $v['product_title_en'];

                $product = Service_Product::getByField($productId, 'product_id');
                if (empty($product_title_en)) {
                    //没传递就用产品的的
                    $product_title_en = $product['product_title_en'];
                }
                if (!$haveDeclare) {
                    //没有设置declare 就用订单的declare_value
                    $declare_price = $product['product_declared_value'];
                }
                $purpose_declared_value = trim($v['op_declared_value']);
                $orderProductRow        = array(
                    'order_id'                  => $order['order_id'],
                    'order_code'                => $order['order_code'],
                    'product_id'                => $productId,
                    'product_barcode'           => $product['product_barcode'],
                    'product_title_en'          => $product_title_en,
                    'op_quantity'               => $qty,
                    'op_declared_value'         => $declare_price,
                    'op_purpose_declared_value' => $purpose_declared_value,
                    'op_category'               => $product['pc_id'],
                    'op_add_time'               => $time,
                    'op_update_time'            => $time,
                );
                $op_id = Service_OrderProduct::add($orderProductRow);
                if (!$op_id) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorOrderProductWriteFailure') . " ....-->" . $ordersCode, '50000');
                }
                $purpose_totalDeclare += $purpose_declared_value * $qty;

                $row['order_product'][$k]['op_id'] = $op_id;
                $row['order_product'][$k]['product_id'] = $product['product_id'];
                $row['order_product'][$k]['product_title'] = $product['product_title'];
                $row['order_product'][$k]['product_title_en'] = $product_title_en;
                $row['order_product'][$k]['product_sales_value'] = $product['product_sales_value'];
                $row['order_product'][$k]['product_declared_value'] = $product['product_declared_value'];
                $row['order_product'][$k]['hs_code'] = $product['hs_code'];

                if ($orderRow['sm_code'] == "WG-EUB-EBAY") {
                    $ebayOrderDetail = array(
                        'op_id'                     => $op_id,
                        'order_code'                => $ordersCode,
                        'ebay_item_id'              => $v['ebay_item_id'],
                        'ebay_transaction_id'       => $v['ebay_transaction_id'],
                        'ebay_buyer_id'             => $v['ebay_buyer_id'],
                        'ebay_item_title'           => '',
                        'ebay_email'                => '',
                        'sold_qty'                  => $qty,
                        'posted_qty'                => $qty,
                        'order_sales_record_number' => '',
                        //'order_id',
                        'ebay_site_id'              => '',
                        'received_amount'           => '',
                        'payment_date'              => '',
                        'sold_price'                => '',
                        'sold_date'                 => '',
                        'currency_code'             => '',
                        'ebay_message'              => '',
                        'paypal_email'              => '',
                        'paypal_message'            => '',
                        'note'                      => '',
                    );
                    Service_EbayOrderDetail::add($ebayOrderDetail);
                }

            }

            $this->addShipOrder($row);

            if ($row['sm_code'] == 'HKPG') {
                $purpose_totalDeclareHK = Service_Currency::converByCode("USD", "HKD", $purpose_totalDeclare);
                if ($purpose_totalDeclareHK > 3000) {
                    throw new Exception("HKPG总目的海关申报价值大于3000HKD");
                }
            }

            $remark = "Order Contents Update";

            $logRow = array(
                'order_id'          => $order['order_id'],
                'order_code'        => $ordersCode,
                'ol_type'           => '1',
                'order_status_from' => $order['order_status'],
                'order_status_to'   => $order['order_status'],
                'ol_add_time'       => $time,
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($logRow);
            if($orderRow['reference_no']!=""){
                $predata = Service_Precaution::getByField( $order['reference_no'],'precaution_value');
                if(empty($predata)){
                    Service_Precaution::insert(array(
                        'precaution_value' => $orderRow['reference_no'],
                    ));
                }else{
                    // 更新预警信息
                    Service_Precaution::update(array(
                        'precaution_value' => $orderRow['reference_no'],
                    ), $order['reference_no'], 'precaution_value');
                }
            }else{
                Service_Precaution::delete($order['reference_no'], 'precaution_value');
            }

            $message = Ec_Lang::getInstance()->getTranslate('update') . " [{$ordersCode}] " . Ec_Lang::getInstance()->getTranslate('success');
            if ($isRemoteCity === true) {
                $message .= '<br>订单属于偏远地区，如需修改，请在草稿状态下进行编辑修改';
            }
            if (($orderRow['sm_code'] =='HKDHL'||$orderRow['sm_code'] =='CNDHL'||$orderRow['sm_code'] =='WWDHLU'||$orderRow['sm_code'] =='WWDHLP') && $purpose_totalDeclare>120) {
                $message .= '<br>该订单目的海关申报价大于120USD，将产生超值报关费';
            }
            if (in_array($orderRow['sm_code'], array('4PX-LYT_GH', '4PX-EU_PACKET')) && $purpose_totalDeclare >= 20) {
                $message .= '<br/><span style="color: red;">该包裹申报价值大于等于15英镑(20美金)，无论当地是否实际产生税金，均需提前支付20%的关税</span>';
            }
            if ($orderRow['sm_code'] =='BH-DPD') {
                $totaldeclareEUR = Service_Currency::converByCode("USD", "EUR", $purpose_totalDeclare);
                if($totaldeclareEUR >= 50){
                    $message .= '<br><font style="color:red;">订单号为'.$ordersCode.'有机会被征收关税</font>';
                }
            }

            if(($orderRow['sm_code'] === 'CJ-DGMP'|| $orderRow['sm_code'] === 'CJ-DGMG') && $orderRow['order_type'] == '0'){
                $search = array(" ","　","\n","\r","\t");
                $oab_street_address1 = str_replace($search,"",$row['oab_street_address1']);
                $oab_street_address2 = str_replace($search,"",$row['oab_street_address2']);
                $is_contain = false;
                if(strstr(strtoupper($oab_street_address1),'POSTOFFICE')){
                    $is_contain = true;
                }
                if(strstr(strtoupper($oab_street_address2),'POSTOFFICE')){
                    $is_contain = true;
                }
                if(strstr(strtoupper($oab_street_address1),'POSTBOX')){
                    $is_contain = true;
                }
                if(strstr(strtoupper($oab_street_address2),'POSTBOX')){
                    $is_contain = true;
                }
                if($is_contain === true){
                    $message .= '<br><span style="color:red;">订单号为['.$ordersCode.']地址内包含POST OFFICE/POST BOX，派送不会另行通知</span>';
                }
            }

            //高风险地区附加费
            $cityArr=array("阿富汗","布隆迪","伊拉克","利比亚","马里","尼日尔","南苏丹","叙利亚","也门");
            //受限制地区附加费
            $cityArr1=array("中非共和国","象牙海岸","刚果民主共和国","厄立特里亚","伊拉克","伊朗","朝鲜","利比亚","利比里亚","索马里","苏丹","叙利亚","也门");
            if ($orderRow['sm_code'] == 'HKDHL'||$orderRow['sm_code'] == 'BH-HKDHL'||$orderRow['sm_code'] == 'CNDHL'||$orderRow['sm_code'] == 'WWDHLP'||$orderRow['sm_code'] == 'WWDHLU') {
                $country=Service_Country::getByField($row['oab_country_id'],'country_id');
                if (in_array($country['country_name'],$cityArr)){
                    $message .= '<br><font style="color:red;">订单号为'.$ordersCode.'需支付高风险地区附加费</font>';
                }
                if (in_array($country['country_name'],$cityArr1)){
                    $message .= '<br><font style="color:red;">订单号为'.$ordersCode.'需支付受限制地区附加费</font>';
                }
            }
            $invoceContry=Service_ShippingMethodConfig::getInvoiceContry();
              if (in_array($orderRow['sm_code'],array('HKDHL','BH-HKDHL','CNDHL','WWDHLP','WWDHLU'))&&in_array($row['oab_country_id'],$invoceContry)) {
                if($orderRow['sm_code']=="BH-HKDHL"&&($row['oab_country_id']=="132"||$row['oab_country_id']=="128")){
                    $message.= '<br><span style="color:red">订单'.$ordersCode.'需提供正本发票,可在系统中的业务管理模块下载</span>';
                }elseif($row['oab_country_id']!='251'){
                    $message .= '<br><span style="color:red" >该订单需提供正本发票</span>';
                }else{
                    if($purpose_totalDeclare>Service_ShippingMethodConfig::$purPusDecalar){
                        $message .= '<br><span style="color:red" >该订单需提供正本发票</span>';
                    }
                }
            }
            //处理order_shipping
            $orderShipping = Service_OrderShipping::getByField( $ordersCode, 'order_code' );
            if( $orderRow['sm_code'] == 'DGF-CARGO' ) {
                if( $orderShipping ) {
                    $old = array(
                        'notify_tel' => $orderShipping['notify_tel'],
                        'notify_contact' => $orderShipping['notify_contact'],
                        'notify_addr' => $orderShipping['notify_addr'],
                        'destination' => $orderShipping['destination'],
                        'is_dgd' => $orderShipping['is_dgd'],
                        'hs_description' => $orderShipping['hs_description'],
                        'insured_account' => $orderShipping['insured_account'],
                    );
                    $new = array(
                        'notify_tel'=>$row['shippingInfo']['notifyTel'],
                        'notify_contact'=>$row['shippingInfo']['notifyContact'],
                        'notify_addr'=>$row['shippingInfo']['notifyAddr'],
                        'destination'=>$row['shippingInfo']['destination'],
                        'is_dgd'=>$row['shippingInfo']['isDGD'],
                        'hs_description'=>$row['shippingInfo']['hsDescription'],
                        'insured_account'=>$row['shippingInfo']['insuredAccount'],
                    );
                    $update = array_diff_assoc( $new, $old );
                    if( $update ) {
                        $uResult = Service_OrderShipping::update( $update, $orderShipping['os_id'], 'os_id' );
                        if( !$uResult) {
                            throw new Exception('更新物流信息失败');
                        }
                    }
                } else {
                    $orderShipping = array(
                        'order_code'=>$ordersCode,
                        'notify_tel'=>$row['shippingInfo']['notifyTel'],
                        'notify_contact'=>$row['shippingInfo']['notifyContact'],
                        'notify_addr'=>$row['shippingInfo']['notifyAddr'],
                        'destination'=>$row['shippingInfo']['destination'],
                        'is_dgd'=>$row['shippingInfo']['isDGD'],
                        'hs_description'=>$row['shippingInfo']['hsDescription'],
                        'insured_account'=>$row['shippingInfo']['insuredAccount'],
                    );
                    $aResult = Service_OrderShipping::add($orderShipping);
                    if( !$aResult) {
                        throw new Exception('更新物流信息失败');
                    }
                }
            } else {
                if( $orderShipping ) {
                    $dResult = Service_OrderShipping::delete( $orderShipping['os_id'], 'os_id' );
                    if( !$dResult )
                        throw new Exception('更新物流信息失败');
                }
            }
            $result = array(
                "ask"        => 1,
                "message"    => $message,
                'ordersCode' => $ordersCode,
            );
            $db->commit();
            //$db->rollback();
        } catch (Exception $e) {
            $db->rollback();
            $result = array("ask" => 0, "message" => $e->getMessage(), 'errorCode' => $e->getCode());
        }
        return $result;
    }

    //格式化
    private static function formatRow($v)
    {
        $productArr = array();
        foreach ($v as $key => $subV) {
            if (preg_match('/(.*)\[([0-9]+)\].*/', $key, $m)) {
                if ($m[1] == 'sku') {
                    $productArr[$m[2]]['sku'] = $subV;
                }
                if ($m[1] == 'qty') {
                    $productArr[$m[2]]['qty'] = $subV;
                }
                unset($v[$key]);
            }
            if ($key == 'shipping_method') {
                $v[$key] = preg_replace('/([0-9a-zA-Z]+)\s+.*/', '\\1', $subV);
            }

            if ($key == 'consignee_country_id') {
                $subV = preg_replace('/([0-9a-zA-Z]+)\s+.*/', '\\1', $subV);
                //                     echo $subV;exit;
                if ($country = Merchant_Service_Country::getByField($subV, 'country_code')) {
                    $v[$key] = $country['country_id'];
                } else {
                    $v[$key] = 0;
                }
            }
            if ($key == 'warehouse_id') {
                if ($warehouse = Merchant_Service_Warehouse::getByField($subV, 'warehouse_name')) {
                    $v[$key] = $warehouse['warehouse_id'];
                } else {
                    $v[$key] = 0;
                }
            }
        }
        $tmp = array();
        foreach ($productArr as $v1) {
            if (empty($v1['sku'])) {
//sku空
                continue;
            }
            $tmp[$v1['sku']] = $v1['qty'];
        }
        $productArr = $tmp; //重新赋值

        $v['order_product'] = $productArr;

        return $v;
    }

    public static function upload($file, $customerId)
    {

        $fileContentArr = self::readUploadFile($file['name'], $file['tmp_name']);
        // print_r($fileContentArr);exit;
        $results = array();
        foreach ($fileContentArr as $v) {
            $v = self::formatRow($v); //格式化

            $orderProduct = array();
            $error        = array();
            foreach ($v['order_product'] as $sku => $qty) {
                $product = Merchant_Service_Product::getByCondition(array('product_sku' => $sku, 'customer_id' => $customerId));

                if (empty($product)) {
                    $error[] = "SKU:[" . $sku . "] Not Exists";
                    if (!preg_match('/^[0-9]+$/', trim($qty))) {
                        $error[] = "SKU:[" . $sku . "] Qty nust be integer!";
                    }
                    continue;
                }
                //$orderProduct[$product[0]['product_id']] = $qty;
                $orderProduct[] = array(
                    'product_id' => $product[0]['product_id'],
                    'qty'        => $qty,
                );

            }

            //print_r($v);exit;
            if (empty($error)) {
                $row = array(
                    'customer_id'          => $customerId,
                    'warehouse_id'         => $v['warehouse_id'],
                    'shipping_method'      => $v['shipping_method'],
                    'customer_order_code'  => $v['customer_order_code'],
                    'remark'               => '',
                    'order_type'           => '0',

                    /* //以下没有传值
                    'parcel_declared_value'=>'',
                    'parcel_contents'=>'',
                    'parcel_quantity'=>'',
                    'orders_status'=>'',
                    'problem_status'=>'',
                    'underreview_status'=>'',
                    'add_time'=>'',
                    'last_modified_time'=>'',
                     */
                    'consignee_first_name' => $v['consignee_first_name'],
                    'consignee_last_name'  => $v['consignee_last_name'],
                    'consignee_company'    => $v['consignee_company'],
                    'consignee_country_id' => $v['consignee_country_id'],
                    'consignee_zip'        => $v['consignee_zip'],
                    'consignee_region'     => $v['consignee_region'],
                    'consignee_city'       => $v['consignee_city'],
                    'consignee_address1'   => $v['consignee_address1'],
                    'consignee_address2'   => $v['consignee_address2'],
                    'consignee_address3'   => $v['consignee_address3'],
                    'consignee_phone'      => $v['consignee_phone'],
                    'consignee_email'      => $v['consignee_email'],

                    'order_product'        => $orderProduct,
                );

                //print_r($row);exit;
                $process = new Merchant_Service_OrderProcess();
                $result  = $process->createOrderTransaction($row);
                if ($result['ask'] == 0) {
//错误数据处理

                    $row['order_product'] = $v['order_product'];
                    $row['msg']           = $result['message'];
                    $row['errs']          = array();
                    if (isset($result['error'])) {
                        $row['errs'] = $result['error'];
                    }
                    $results[] = $row;
                }
            } else {
                $v['msg']  = "Create Order Fail";
                $v['errs'] = $error;
                $results[] = $v;
            }

        }
//         print_r($results);exit;
        return $results;
    }

    public static function batchAdd($orderArr, $customerId)
    {

        $results = array();

        $process = new Merchant_Service_OrderProcess();
        foreach ($orderArr as $row) {

            $validArr = self::validateProductSku($row['order_product'], $customerId);

            $result = array('ask' => '0');
            if ($validArr['ask'] == 1) {
                $bak                  = $row['order_product'];
                $row['order_product'] = $validArr['order_product'];
                //print_r($row);exit;
                $result = $process->createOrderTransaction($row, $customerId);
                if ($result['ask'] == 0) {
//错误数据处理
                    $row['order_product'] = $bak;

                    $row['msg']  = $result['message'];
                    $row['errs'] = array();
                    if (isset($result['error'])) {
                        $row['errs'] = $result['error'];
                    }
                    $results[] = $row;
                }
            } else {
                $err         = $validArr['err'];
                $row['msg']  = "Order Create Fail.";
                $row['errs'] = $err;
                $results[]   = $row;
            }
        }

        return $results;
    }

    private static function validateProductSku($order_product, $customerId)
    {
        $err        = array();
        $productArr = array();
        foreach ($order_product as $product_sku => $qty) {
            $con     = array('product_sku' => $product_sku, 'customer_id' => $customerId);
            $product = Merchant_Service_Product::getByCondition($con);
            if (empty($product)) {
//忽略不存在的产品
                $err[] = 'Product_sku:' . $product_sku . ' Not Exists.Pls make sure it is right.';
            } else {
                $product      = $product[0];
                $productArr[] = array(
                    'product_id' => $product['product_id'],
                    'qty'        => intval($qty),
                );
            }
            if (intval($qty) == 0) {
                $err[] = "Product_sku:[{$product_sku}] Quantity can't be null and must be integer";
            }

        }
        if ($err) {
            return array('ask' => 0, 'err' => $err);
        } else {
            return array('ask' => 1, 'order_product' => $productArr);
        }
    }

    /**
     * 读取上传文件
     * @param string $fileName
     * @return array
     */
    private static function readUploadFile($fileName, $filePath)
    {
        $columnMap = array(
            'ReferenceNo'     => 'customer_order_code',
            'Shipping Method' => 'shipping_method',
            'Country'         => 'consignee_country_id',
            'First Name'      => 'consignee_first_name',
            'Last Name'       => 'consignee_last_name',
            'Address1'        => 'consignee_address1',
            'Address2'        => 'consignee_address2',
            'Address3'        => 'consignee_address3',
            'City'            => 'consignee_city',
            'State/Provice'   => 'consignee_region',
            'Postalcode'      => 'consignee_zip',
            'Email'           => 'consignee_email',
            'Company'         => 'consignee_company',
            'PhoneNo'         => 'consignee_phone',
            'WarehouseCode'   => 'warehouse_id',
            'SKU #1'          => 'sku[1]',
            'Qty #1'          => 'qty[1]',
            'SKU #2'          => 'sku[2]',
            'Qty #2'          => 'qty[2]',
            'SKU #3'          => 'sku[3]',
            'Qty #3'          => 'qty[3]',
            'SKU #4'          => 'sku[4]',
            'Qty #4'          => 'qty[4]',
            'SKU #5'          => 'sku[5]',
            'Qty #5'          => 'qty[5]',
        );
        $pathinfo = pathinfo($fileName);
        $fileData = array();

        if ($pathinfo["extension"] == "xls") {
            $fileData = Default_Service_Upload::readEXCEL($filePath);
        } else if ($pathinfo["extension"] == "csv") {
            $fileData = Default_Service_Upload::readCSV($filePath);
        }
        $result = array();
        if ($fileData) {
            foreach ($fileData[0] as $key => $value) {
                if (isset($columnMap[$value])) {
                    $fileData[0][$key] = $columnMap[$value];
                }
            }
            foreach ($fileData as $key => $value) {
                //将第一行value转成其他行的key
                if ($key == 0) {
                    continue;
                }
                foreach ($value as $vKey => $vValue) {
                    if ($fileData[0][$vKey] == "") {
                        continue;
                    }

                    $result[$key][$fileData[0][$vKey]] = $vValue;
                }
            }
        }

        return $result;
    }

    /*
     * 加入自动任务
     * @return bool
     */
    private function dataToWarehouse()
    {
        if ($this->_order['warehouse_id'] != '2') {
            $warehouseConfig = Zend_Registry::get('warehouse');
            if ($warehouseConfig['Sino']['active']) {
                $wmsApi = new Common_Service_WmsAPI();
                $return = $wmsApi->createOrder($this->_order['orders_code']);
                if (isset($return['out']['ask']) && $return['out']['ask'] != 'Success') {
                    $arr = array();
                    if (!Default_Service_Common::isSoapArray($return['out']['error'])) {
                        $temp                     = $return['out']['error'];
                        $return['out']['error']   = array();
                        $return['out']['error'][] = $temp;
                    }
                    foreach ($return['out']['error'] as $err) {
                        $arr[] = "50000 " . $err['errorMessage'];
                    }
                    throw new Exception(serialize($arr), '110');
                }
            }

//             throw new Exception(print_r($return,true));
            return true;
        }
        $addArr = array(
            'c_type'     => 0,
            'c_app_type' => 0,
            'c_code'     => $this->_order['orders_code'],
        );
        if (!Merchant_Service_Crontab::add($addArr)) {
            throw new Exception("Internal error!Submit Order Fail..", '50000');
            return false;
        }

    }

    /**
     * @author william-fan
     * @todo 用于确认订单
     */
    public static function confirm($orderCode = '', $customerId)
    {
        $result     = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('ConfirmFailure'), 'error' => array());
        $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
        $error      = array();
        //print_r($receiving);exit;
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid'); //'订单无效';
        } else {
            if ($ordersInfo['order_status'] != '1') {
                $error[] = Ec_Lang::getInstance()->getTranslate('OrderStatusNotInDraft'); //'订单状态不为草稿';
            }
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        //不检查库存了 在 提交订单的的时候检查
        /* if($ordersInfo['order_mode_type']=='0'){
        $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderCode),"*");
        $shortage = false;
        foreach($orderProduct as $k=>$v){
        $productInventory = Service_ProductInventory::getByField($v['product_id'],'product_id',"*");
        if($v['op_quantity']>$productInventory['pi_sellable']){
        $result['message'] = $v['product_barcode'].Ec_Lang::getInstance()->getTranslate('InventoryShortage');
        $shortage = true;
        break;
        }
        }
        if($shortage){
        return $result;
        }
        } */
        $session     = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $orderRow = array(
                'order_status' => '2',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Orders::update($orderRow, $orderCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed')); //"订单状态更改失败"
            }

            $SMRow = Service_ShippingMethod::getByField($ordersInfo['sm_code'], "sm_code", "*");
            if (!in_array($ordersInfo['sm_code'], array("SZY-EUB", 'WG-EUB', "UKTL", "SZY-ETK", 'BH-USPS','BH-SFEP',
                'BH-DPD','SF-RUPR','SF-RUPT','Rumall-RU-EP','Rumall-RU-G','4PX-LYT_GH','4PX-EU_PACKET','4PX-RU_POST-LINK_RMAIL','4PX-HKDHL','PNLN','PNLG','4PX-YX','4PX-SG_ordinary_mail+','CJ-DGMG','LYT-SMTGH-X','BH-AZAT-G','DGM-US','BH-POST-NL','BH-BEAT','BH-NLAT'
                ))) {
                if ($SMRow['sm_class_code'] == "CRP" && $ordersInfo['order_mode_type'] == "1" && $ordersInfo['ref_tracking_number'] == ""
                        ||(($ordersInfo['sm_code']=='4PX-Singapo_SPack_IMAIR' || $ordersInfo['sm_code']=='4PX-OZXBTH')&& $ordersInfo['ref_tracking_number'] == ""
                         )) {
                    $condition = array(
                        'sm_code'      => $ordersInfo['sm_code'],
                        'warehouse_id' => $ordersInfo['warehouse_id'],
                        'stn_status'   => '0',
                    );
                    if ($ordersInfo['sm_code']=='CJ-DGMG') {
                        $oab=Service_OrderAddressBook::getByField($ordersInfo['order_code'],'order_code');
                        if (!empty($oab)) {
                            if ($oab['oab_country_id']=='253') {
                                $condition['stn_code_arr']=array('LX56145012DE','LX56148012DE');
                            }
                        }
                    }
                    $STNList = Service_ServiceTrackingNumber::getByConditionLock($condition, "*", 1, 1, "stn_id asc");
                    if (empty($STNList)) {
                        throw new Exception("没有可以分配的预存单号1!");
                    }
                    $ServiceTrackingNumber = array(
                        'order_code'      => $orderCode,
                        'stn_status'      => '1',
                        'stn_update_time' => date("Y-m-d H:i:s"),
                    );

                    //$trackingNumber=Service_ServiceTrackingNumber::getTrackingNumber($ordersInfo['sm_code'], $STNList[0]['stn_code']);
                    $refTrackingNumber = array(
                        'ref_tracking_number' => $STNList[0]['stn_code'],
                    );
                    Service_ServiceTrackingNumber::update($ServiceTrackingNumber, $STNList[0]['stn_id'], 'stn_id');
                    Service_Orders::update($refTrackingNumber, $orderCode, 'order_code');
                }
            }

            $customerRow = Service_Customer::getByField($customerId);

            $orderOperateType = Service_OrderOperationType::getByField('confirm', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $ordersInfo['order_id'],
                    'order_code'   => $orderCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }

            $orderOperationTime = Service_OrderOperationTime::getByField($ordersInfo['order_id'], 'order_id', "*");
            if (!empty($orderOperationTime)) {
                $oot = array(
                    'confirm_time'    => date("Y-m-d H:i:s"),
                    'confirm_user_id' => -1 * $sessionData['id'],
                );
                Service_OrderOperationTime::update($oot, $orderOperationTime['oot_id'], "oot_id");
            } else {
                $oot = array(
                    'order_id'        => $ordersInfo['order_id'],
                    'order_code'      => $orderCode,
                    'confirm_time'    => date("Y-m-d H:i:s"),
                    'confirm_user_id' => -1 * $sessionData['id'],
                );
                Service_OrderOperationTime::add($oot);
            }

            $orderLog = array(
                'order_id'          => $ordersInfo['order_id'],
                'order_code'        => $orderCode,
                'ol_type'           => '1',
                'order_status_from' => '1',
                'order_status_to'   => '2',
                'ol_add_time'       => date('Y-m-d H:i:s', time()),
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($orderLog);

            /* $ftProcess = new Service_FtpMessageProcess();
            $fml_id = $ftProcess->addSendMessage($ASNCode);
            $ftProcess->ftpSendMessage($fml_id); */

            $w = Service_Warehouse::getByField($ordersInfo['warehouse_id'], 'warehouse_id', '*');
            if ($ordersInfo['order_mode_type'] == "0") {
                $sotDescription = '备货订单确认成功,待提交';
                $warehouseName  = $w['warehouse_desc'];
            } else {
                $sotDescription = "集货订单确认成功,待提交";
                $warehouseName  = "客户仓库";
            }
            $shipOrderTracking = array(
                'order_code'          => $orderCode,
                'sot_location'        => $warehouseName,
                'sot_add_time'        => date("Y-m-d H:i:s"),
                'warehouse_id'        => $ordersInfo['warehouse_id'],
                'sot_description'     => $sotDescription,
                'sot_type'            => '0',
                'sot_time_offset'     => '',
                'tracking_number'     => $orderCode,
                'ref_tracking_number' => '',
                'status_desc'         => '确认',
                'user_id'             => -1 * $sessionData['id'],
            );
            Service_ShipOrderTracking::add($shipOrderTracking);

            $balanceProcess = new Service_CustomerBalanceProcess();
            $feeResult      = $balanceProcess->freezeFeeCheck($orderCode, $customerId);
            if ($feeResult !== true) {
                throw new Exception($feeResult);
            }
            $result['ask']     = '1';
            $result['message'] = Ec_Lang::getInstance()->getTranslate('OrderConfirmationSuccess'); //'订单确认成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();

            $exceptionExplain   = "草稿->确认异常:" . $e->getMessage();
            $exceptionCondition = array(
                'et_code'    => 'orderConfirm',
                'e_title'    => '订单确认',
                'e_refer_no' => $orderCode,
                'e_explain'  => $exceptionExplain,
            );
            $exist = Service_Exception::getByCondition($exceptionCondition, 'count(*)');
            if (!$exist) {
                $exceptionCondition['e_add_time']    = date("Y-m-d H:i:s");
                $exceptionCondition['e_update_time'] = date("Y-m-d H:i:s");
                Service_Exception::add($exceptionCondition);
            }

            return $result;
        }
        //print_r($result);exit;
        return $result;
    }
    /**
     * @author william-fan
     * @todo 用于提交订单
     */
    public static function submit($orderCode = '', $customerId, $batchNumber = '')
    {
        $result      = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('SubmissionFailed'), 'error' => array());
        $ordersInfo  = Service_Orders::getByField($orderCode, 'order_code');
        $error       = array();
        $batchNumber = ('' !== $batchNumber) ? '<span style="display:none !important;">' . $batchNumber . '</span>' : '';
        //print_r($receiving);exit;
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid');
        } else {
            if ($ordersInfo['order_status'] != '2' && $ordersInfo['order_status'] != '3') {
                $error[]           = Ec_Lang::getInstance()->getTranslate('OrderstatusIsNotRecognizedOrAbnormalState');
                $result['message'] = Ec_Lang::getInstance()->getTranslate('SubmitFailOrderStatusError'); //'确认失败订单状态不为确认状态';
            }
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        //提交客户冻结检测
        $customerInfo = Service_Customer::getByField($ordersInfo['customer_code'], 'customer_code', array('is_frozen', 'frozen_reason'));
        if($customerInfo['is_frozen']){
            $error[]           = '订单['.$ordersInfo['order_code'].'],客户['.$ordersInfo['customer_code'].']已冻结，冻结原因：'.$customerInfo['frozen_reason'];
            $result['message'] = '订单['.$ordersInfo['order_code'].'],客户['.$ordersInfo['customer_code'].']已冻结，冻结原因：'.$customerInfo['frozen_reason'];
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        $session     = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();

            // 解决订单从提交状态到异常状态的问题。能解决？由时间检验，暂时就这么做。
            $ordersInfo = Service_Orders::getByField($orderCode, 'order_code'); // 事务开启，重新提取订单信息
            if (!in_array((int) $ordersInfo['order_status'], array(2, 3), true)) {
                // 重新判断订单状态，只有确认2、异常3才能提交
                throw new Exception(Ec_Lang::getInstance()->getTranslate('SubmitFailOrderStatusError'));
            }

            $orderStatus = '4';
            $ycString    = ''; //异常的字符串
            $orderRow    = array(
                'order_status' => '4',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );

            $customerRow = Service_Customer::getByField($customerId);
            if ($ordersInfo['order_mode_type'] == '0') {
                //备货模式下的订单要检查库存

                //查找订单下面的产品
                $conOrderProduct = array(
                    'order_code' => $orderCode,
                );
                $orderProducts = Service_OrderProduct::getByCondition($conOrderProduct, "*", 0, 1, '', "for update");
                if (!empty($orderProducts)) {
                    $totalValue=0;
                    foreach ($orderProducts as $keyop => $valueop) {
                        $totalValue+=$valueop['op_purpose_declared_value']*$valueop['op_quantity'];
                        $conInventory = array(
                            'customer_id'  => $customerId,
                            'product_id'   => $valueop['product_id'],
                            'warehouse_id' => $ordersInfo['warehouse_id'],
                        );
                        $productInventory = Service_ProductInventory::getByCondition($conInventory, "*", 0, 1, '', "for update");
                        if (!empty($productInventory)) {
                            $inventory = $productInventory[0];
                            if ($inventory['pi_sellable'] - $valueop['op_quantity'] < 0) {
                                //throw new Exception(";
                                $errorInventory[] = "{$valueop['product_barcode']}" . Ec_Lang::getInstance()->getTranslate('AvailableStockIsNegativeCanNotSubmitOrders');
                            }
                            //修改product_inventory 记录
                            $productInventoryRow = array(
                                'pi_sellable'    => $inventory['pi_sellable'] - $valueop['op_quantity'],
                                'pi_reserved'    => $inventory['pi_reserved'] + $valueop['op_quantity'],
                                'pi_update_time' => date('Y-m-d H:i:s', time()),
                            );
                            Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
                            $productInventoryLogRow = array(
                                'product_id'      => $valueop['product_id'],
                                'product_barcode' => $valueop['product_barcode'],
                                'warehouse_id'    => $ordersInfo['warehouse_id'],
                                'user_id'         => '-1',
                                'pil_sellable'    => $inventory['pi_sellable'] - $valueop['op_quantity'],
                                'pil_reserved'    => $inventory['pi_reserved'] + $valueop['op_quantity'],
                                'pil_onway'       => $inventory['pi_onway'],
                                'pil_pending'     => $inventory['pi_pending'],
                                'pil_unsellable'  => $inventory['pi_unsellable'],
                                'pil_shipped'     => $inventory['pi_shipped'],
                                'pil_ip'          => Common_Common::getIP(),
                                'pil_add_time'    => date('Y-m-d H:i:s', time()),
                                'pil_note'        => '订单确认提交',
                                'from_it_code'    => 'Confirm',
                                'to_it_code'      => 'Submitted',
                                'reference_code'  => $valueop['order_code'],
                                'pil_quantity'    => $valueop['op_quantity'],
                            );
                            Service_ProductInventoryLog::add($productInventoryLogRow);
                        } else {
                            $errorInventory[] = "{$valueop['product_barcode']}" . '无库存';
                        }
                    }
                    //print_r($errorInventory);
                    if (isset($errorInventory) && !empty($errorInventory)) {
                        $orderStatus = '3'; //订单到异常状态
                        $ycString .= implode('<br/>', $errorInventory);
                        throw new Exception($ycString, '110');
                    }
                }

                $orderLog = array(
                    'order_id'          => $ordersInfo['order_id'],
                    'order_code'        => $orderCode,
                    'ol_type'           => '1',
                    'order_status_from' => $ordersInfo['order_status'],
                    'order_status_to'   => $orderStatus,
                    'ol_add_time'       => date('Y-m-d H:i:s', time()),
                    'user_id'           => '-1',
                    'account_id'        => Service_Login::getUserId(),
                    'ol_ip'             => Common_Common::getIP(),
                    'ol_comments'       => $batchNumber,
                );
                Service_OrderLog::add($orderLog);

                $orderOperateType = Service_OrderOperationType::getByField('submit', 'oot_code'); //提交订单操作
                if (!empty($orderOperateType)) {
                    $orderOperationNodeRow = array(
                        'order_id'     => $ordersInfo['order_id'],
                        'order_code'   => $orderCode,
                        'oot_code'     => $orderOperateType['oot_code'],
                        'oon_note'     => '',
                        'oon_add_time' => date('Y-m-d H:i:s', time()),
                        'user_id'      => '-1',
                    );
                    Service_OrderOperationNode::add($orderOperationNodeRow);
                }

                $opt = Service_OrderOperationTime::getByField($ordersInfo['order_id'], 'order_id', "*");
                if (!empty($opt)) {
                    $orderOperationTime = array(
                        'order_code'     => $orderCode,
                        'submit_time'    => date("Y-m-d H:i:s"),
                        'submit_user_id' => -1 * $sessionData['id'],
                    );
                    Service_OrderOperationTime::update($orderOperationTime, $opt['oot_id'], "oot_id");
                } else {
                    $orderOperationTime = array(
                        'order_id'          => $ordersInfo['order_id'],
                        'order_code'        => $orderCode,
                        'cutoff_time'       => '',
                        'submit_time'       => date("Y-m-d H:i:s"),
                        'process_time'      => '',
                        'pack_time'         => '',
                        'ship_time'         => '',
                        'import_time'       => '',
                        'delivered_time'    => '',
                        'sync_time'         => '',
                        'update_time'       => '',
                        'process_user_id'   => '',
                        'pack_user_id'      => '',
                        'import_user_id'    => '',
                        'ship_user_id'      => '',
                        'delivered_user_id' => '',
                        'cutoff_user_id'    => '',
                        'submit_user_id'    => -1 * $sessionData['id'],
                    );
                    Service_OrderOperationTime::add($orderOperationTime);
                }

                $w                 = Service_Warehouse::getByField($ordersInfo['warehouse_id'], 'warehouse_id', '*');
                $shipOrderTracking = array(
                    'order_code'          => $orderCode,
                    'sot_location'        => $w['warehouse_desc'],
                    'sot_add_time'        => date("Y-m-d H:i:s"),
                    'warehouse_id'        => $ordersInfo['warehouse_id'],
                    'sot_description'     => '备货订单提交成功,待仓库系统确认',
                    'sot_type'            => '0',
                    'sot_time_offset'     => '',
                    'tracking_number'     => $orderCode,
                    'ref_tracking_number' => '',
                    'status_desc'         => '已提交',
                    'user_id'             => -1 * $sessionData['id'],
                );
                Service_ShipOrderTracking::add($shipOrderTracking);

                $balanceProcess = new Service_CustomerBalanceProcess();
                //环球直接扣费
                if( Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $customerRow['customer_code'] ) ) {
                    $feeResult      = $balanceProcess->deductFee( $orderCode );
                    //var_dump($feeResult);exit;
                    if ($feeResult !== true) {
                        $orderStatus = '3';
                        $error = implode( ',', $balanceProcess->getError() );
                        $ycString .= $error;
                        throw new Exception($error, '111');
                    }
                } else {
                    $feeResult      = $balanceProcess->freezeFee($orderCode, $customerId);
                    if ($feeResult !== true) {
                        $orderStatus = '3';
                        $ycString .= $feeResult;
                        throw new Exception($feeResult, '111');
                    }
                }
            }
            $orderRow['order_status'] = $orderStatus;
            if (!Service_Orders::update($orderRow, $orderCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed'));
            }
            $result['ask'] = '1';
            if ($orderStatus == '4') {
                $result['message'] = Ec_Lang::getInstance()->getTranslate('OrdersSubmittedSuccessfully'); //'订单提交成功';
            } else {
                $result['ask']     = '0';
                $result['message'] = '订单移至提交失败,订单移至异常:' . '<br/>' . $ycString; //'订单提交成功';
            }
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            if ($e->getCode() == '110' || $e->getCode() == '111') {
                $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
                $orderRow   = array(
                    'order_status' => '3',
                    'update_time'  => date('Y-m-d H:i:s', time()),
                );
                Service_Orders::update($orderRow, $orderCode, 'order_code');
                $orderLog = array(
                    'order_id'          => $ordersInfo['order_id'],
                    'order_code'        => $orderCode,
                    'ol_type'           => '1',
                    'order_status_from' => $ordersInfo['order_status'],
                    'order_status_to'   => '3',
                    'ol_add_time'       => date('Y-m-d H:i:s', time()),
                    'user_id'           => '-1',
                    'account_id'        => Service_Login::getUserId(),
                    'ol_ip'             => Common_Common::getIP(),
                    'ol_comments'       => $ycString . $batchNumber,
                );
                Service_OrderLog::add($orderLog);
            }
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();

            $exceptionExplain   = "确认->提交异常:" . $e->getMessage();
            $exceptionCondition = array(
                'et_code'    => 'orderSubmit',
                'e_title'    => '订单提交',
                'e_refer_no' => $orderCode,
                'e_explain'  => $exceptionExplain,
            );
            $exist = Service_Exception::getByCondition($exceptionCondition, 'count(*)');
            if (!$exist) {
                $exceptionCondition['e_add_time']    = date("Y-m-d H:i:s");
                $exceptionCondition['e_update_time'] = date("Y-m-d H:i:s");
                Service_Exception::add($exceptionCondition);
            }

            return $result;
        }
        //print_r($result);exit;
        return $result;
    }
    /**
     * @author william-fan
     * @todo 移至草稿状态
     */
    public static function draftTranslate($orderCode = '', $customerId)
    {
        $result     = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('FailedToDraft'), 'error' => array());
        $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
        $error      = array();
        //print_r($receiving);exit;
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid'); //'订单无效';
        } else {
            if ($ordersInfo['order_status'] != '2') {
                $error[]           = Ec_Lang::getInstance()->getTranslate('OrderStatusIsNotRecognizedInTheState'); //'订单状态不为确认状态';
                $result['message'] = Ec_Lang::getInstance()->getTranslate('FailedToDraft') . Ec_Lang::getInstance()->getTranslate('OrderStatusIsNotRecognizedInTheState'); //'移至草稿失败订单状态不为确认状态';
            }
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $orderRow = array(
                'order_status' => '1',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Orders::update($orderRow, $orderCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed'));
            }
            $customerRow = Service_Customer::getByField($customerId);
            //查找订单下面的产品
            $conOrderProduct = array(
                'order_code' => $orderCode,
            );
            $orderProducts = Service_OrderProduct::getByCondition($conOrderProduct);
            /* if(!empty($orderProducts)){
            foreach($orderProducts as $keyop=>$valueop){
            $conInventory = array(
            'customer_id'=>$customerId,
            'product_id'=>$valueop['product_id'],
            'warehouse_id'=>$ordersInfo['warehouse_id']
            );
            $productInventory = Service_ProductInventory::getByCondition($conInventory);
            if(!empty($productInventory)){
            $inventory = $productInventory[0];
            if($inventory['pi_reserved']-$valueop['op_quantity']<0){
            //throw new Exception(";
            $errorInventory[]="{$valueop['product_barcode']}可用库存为负,不能提交订单";
            }
            //修改product_inventory 记录
            $productInventoryRow = array(
            'pi_sellable'=>$inventory['pi_sellable']+$valueop['op_quantity'],
            'pi_reserved'=>$inventory['pi_reserved']-$valueop['op_quantity'],
            'pi_update_time'=>date('Y-m-d H:i:s',time()),
            );
            Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
            $productInventoryLogRow = array(
            'product_id'=>$valueop['product_id'],
            'product_barcode'=>$valueop['product_barcode'],
            'warehouse_id'=>$ordersInfo['warehouse_id'],
            'user_id'=>'-1',
            'pil_sellable'=>$inventory['pi_sellable']-$valueop['op_quantity'],
            'pil_reserved'=>$inventory['pi_reserved']+$valueop['op_quantity'],
            'pil_ip'=>Common_Common::getIP(),
            );
            Service_ProductInventoryLog::add($productInventoryLogRow);
            }
            if(isset($errorInventory) && !empty($errorInventory)){
            throw new Exception(implode('<br/>',$errorInventory));
            }
            }

            } */

            $orderLog = array(
                'order_id'          => $ordersInfo['order_id'],
                'order_code'        => $orderCode,
                'ol_type'           => '1',
                'order_status_from' => '2',
                'order_status_to'   => '1',
                'ol_add_time'       => date('Y-m-d H:i:s', time()),
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($orderLog);

            $orderOperateType = Service_OrderOperationType::getByField('draft', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $ordersInfo['order_id'],
                    'order_code'   => $orderCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }

            //冻结金额
            /* $balanceProcess = new Service_CustomerBalanceProcess();
            $feeResult =  $balanceProcess->freezeFee($orderCode, $customerId);
            if($feeResult !== true) throw new Exception($feeResult); */

            $result['ask']     = '1';
            $result['message'] = Ec_Lang::getInstance()->getTranslate('SuccessToDraft'); //'订单提交成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }

    /**
     * @author colin
     * @todo 从异常到草稿状态
     */
    public static function draftFromAbnormal($orderCode = '', $customerId)
    {
        $result     = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('FailedToDraft'), 'error' => array());
        $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
        $error      = array();
        //print_r($receiving);exit;
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid'); //'订单无效';
        } else {
            if ($ordersInfo['order_status'] != '3') {
                $error[]           = Ec_Lang::getInstance()->getTranslate('OrderStatusIsNotAbnormal'); //'订单状态不为异常状态';
                $result['message'] = Ec_Lang::getInstance()->getTranslate('FailedToDraft') . Ec_Lang::getInstance()->getTranslate('OrderStatusIsNotAbnormal'); //'移至草稿失败订单状态不为确认状态';
            }
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $orderRow = array(
                'order_status' => '1',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Orders::update($orderRow, $orderCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed'));
            }
            $customerRow = Service_Customer::getByField($customerId);
            //查找订单下面的产品
            $conOrderProduct = array(
                'order_code' => $orderCode,
            );
            $orderProducts = Service_OrderProduct::getByCondition($conOrderProduct);

            $orderLog = array(
                'order_id'          => $ordersInfo['order_id'],
                'order_code'        => $orderCode,
                'ol_type'           => '1',
                'order_status_from' => '3',
                'order_status_to'   => '1',
                'ol_add_time'       => date('Y-m-d H:i:s', time()),
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($orderLog);

            $orderOperateType = Service_OrderOperationType::getByField('draft', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $ordersInfo['order_id'],
                    'order_code'   => $orderCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => 'from abnormal',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }

            //冻结金额
            /* $balanceProcess = new Service_CustomerBalanceProcess();
            $feeResult =  $balanceProcess->freezeFee($orderCode, $customerId);
            if($feeResult !== true) throw new Exception($feeResult); */

            $result['ask']     = '1';
            $result['message'] = Ec_Lang::getInstance()->getTranslate('SuccessToDraft'); //'订单提交成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }

    /**
     * @author william-fan
     * @todo 用于删除订单
     */
    public static function deleteTranslate($orderCode = '', $customerId)
    {
        $result     = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('FailedToDeleteOrders'), 'error' => array());
        $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
        $error      = array();
        //print_r($receiving);exit;
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid'); //'订单无效';
        } else {
            if ($ordersInfo['order_status'] != '1') {
                $error[]           = Ec_Lang::getInstance()->getTranslate('OrderStatusNotInDraft'); //'订单状态不为草稿状态';
                $result['message'] = Ec_Lang::getInstance()->getTranslate('FailedToDeleteOrders') . Ec_Lang::getInstance()->getTranslate('OrderStatusNotInDraft'); //'删除订单失败订单状态不为草稿状态';
            }
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $orderRow = array(
                'order_status' => '0',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Orders::update($orderRow, $orderCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed')); //"订单状态更改失败"
            }
            $customerRow = Service_Customer::getByField($customerId);
            //查找订单下面的产品
            $conOrderProduct = array(
                'order_code' => $orderCode,
            );

            $orderLog = array(
                'order_id'          => $ordersInfo['order_id'],
                'order_code'        => $orderCode,
                'ol_type'           => '1',
                'order_status_from' => '1',
                'order_status_to'   => '0',
                'ol_add_time'       => date('Y-m-d H:i:s', time()),
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($orderLog);

            $orderOperateType = Service_OrderOperationType::getByField('delete', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $ordersInfo['order_id'],
                    'order_code'   => $orderCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }
            Service_Precaution::delete($ordersInfo['reference_no'], 'precaution_value');

            $result['ask']     = '1';
            $result['message'] = Ec_Lang::getInstance()->getTranslate('OrdersDeletedSuccessfully'); //'订单删除成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }
    /**
     * @author wiliam-fan
     * @todo 用于恢复删除的订单
     */
    public static function recoveryTranslate($orderCode = '', $customerId)
    {
        $result     = array('ask' => 0, 'message' => "恢复订单失败", 'error' => array());
        $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
        $error      = array();
        //print_r($receiving);exit;
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid'); //'订单无效';
        } else {
            if ($ordersInfo['order_status'] != '0') {
                $error[]           = "订单不为删除状态"; //'订单状态不为删除状态';
                $result['message'] = "恢复订单失败,订单不为删除状态"; //'恢复订单失败,订单不为删除状态';
            }
            if ($ordersInfo['intercept_status'] == "3") {
                $error[]           = "已拦截完成的订单不能再恢复";
                $result['message'] = "已拦截完成的订单不能再恢复";
            }
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();

            // 判断服务商单号是否已存在
            $trackingNumber = trim($ordersInfo['ref_tracking_number']);
            if ('' !== $trackingNumber) {
                $trackingNumberCount = Service_Orders::getByCondition(array(
                    'ref_tracking_number'        => $trackingNumber,
                    'except_order_status_delete' => true,
                ), 'count(*)');
                $serviceTracking = Service_ServiceTrackingNumber::getByField($trackingNumber, 'stn_code');

                if ($trackingNumberCount > 0 || (!empty($serviceTracking) && $serviceTracking['order_code'] !== $ordersInfo['order_code'])) {
                    throw new Exception('恢复订单失败，服务商单号已经存在');
                }
            }

            $orderRow = array(
                'order_status' => '1',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Orders::update($orderRow, $orderCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed')); //"订单状态更改失败"
            }
            $customerRow = Service_Customer::getByField($customerId);
            //查找订单下面的产品
            $conOrderProduct = array(
                'order_code' => $orderCode,
            );

            $orderLog = array(
                'order_id'          => $ordersInfo['order_id'],
                'order_code'        => $orderCode,
                'ol_type'           => '1',
                'order_status_from' => '0',
                'order_status_to'   => '1',
                'ol_add_time'       => date('Y-m-d H:i:s', time()),
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($orderLog);

            $orderOperateType = Service_OrderOperationType::getByField('recovery', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $ordersInfo['order_id'],
                    'order_code'   => $orderCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }
            $predata = Service_Precaution::getByField( $ordersInfo['reference_no'],'precaution_value');
            if(empty($predata)&&$ordersInfo['reference_no']!=""){
                Service_Precaution::insert(array(
                    'precaution_value' => $ordersInfo['reference_no'],
                ));
            }

            $result['ask']     = '1';
            $result['message'] = "订单恢复成功"; //'订单删除成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }
    /**
     * 状态统计
     * @author solar
     * @param int $customer_id
     * @param int $$mode_type
     */
    public static function statStatus($customer_id, $mode_type, $warehouse_id = 0)
    {
        $result = array();
        if ($mode_type == 1) {
            $statusText = self::getjiOrderStatus();
            unset($statusText['0'], $statusText['5,6,7'], $statusText['8,9,10,11,12'], $statusText['13']);
        } else {
            $statusText = self::getOrderStatus();
            unset($statusText['0'], $statusText['8,9,10,11,12'], $statusText['13']);
        }
        //$statusText = $mode_type==1 ? self::getjiOrderStatus() : self::getOrderStatus();
        $list     = Service_Orders::stat($customer_id, $mode_type, $warehouse_id);
        $statData = array();
        foreach ($list as $row) {
            //$result[$row['order_status']]['num'] = $row['num'];
            $statData[$row['order_status']] = $row['num'];
        }
        foreach ($statusText as $key => $text) {
            if (!is_numeric($key)) {
                $result[$key]['num'] = 0;
                $aStatus             = explode(',', $key);
                foreach ($aStatus as $status) {
                    if (isset($result[$status])) {
                        //$result[$key]['num'] += $result[$status]['num'];
                        //unset($result[$status]);
                        $result[$key]['num'] += $statData[$status];
                    }
                }
            } else if (isset($statData[$key])) {
                $result[$key]['num'] = $statData[$key];
            } else {
                $result[$key]['num'] = 0;
            }
            $result[$key]['text'] = $text;
        }
        //print_r($result);
        ksort($result);
        $result = array_values($result);
        return $result;
    }
    /**
     * 根据订单的编码计算产品的重量
     * @author colinyang
     * @param String $orderCode
     * //@param int $mode_type
     */
    public static function calucateOrderTotalWeight($orderCode)
    {
        $result        = array('totalWeight' => 0, 'totalValue' => 0);
        $orderProducts = Service_OrderProduct::getByCondition(array('order_code' => $orderCode));
        if (empty($orderProducts)) {return 0;}

        foreach ($orderProducts as $p) {
            $prd                = Service_Product::getByField($p['product_id'], "product_id", "*");
            $p['product_sku']   = $prd['product_sku'];
            $p['product_type']  = $prd['product_type'];
            $p['currency_code'] = 'RMB';
            if ($prd['currency_code']) {$p['currency_code'] = $prd['currency_code'];}
            $currency_array     = Service_Currency::getByField($p['currency_code'], 'currency_code', "*");
            $p['currency_rate'] = 1;
            if ($currency_array) {$p['currency_rate'] = $currency_array['currency_rate'];}
            $p['totalWeight'] = 0;
            $p['totalValue']  = 0;

            if ($p['product_type'] == 0) {
                $result['totalWeight'] += $prd['product_weight'] * $p['op_quantity'];
                $result['totalValue'] += ($prd['product_declared_value'] * $p['op_quantity']);
            }

            if ($p['product_type'] == 1) {
                $product_combine_arr = Service_ProductCombineRelation::getByCondition(array('product_id' => $prd['product_id']));
                if ($product_combine_arr && is_array($product_combine_arr)) {
                    foreach ($product_combine_arr as $row) {
                        $prdson = Service_Product::getByField($row['pcr_product_id'], "product_id", "*");
                        if (empty($prdson)) {continue;}
                        $result['totalWeight'] += $prdson['product_weight'] * $row['pcr_quantity'] * $p['op_quantity'];
                        $result['totalValue'] += $prdson['product_declared_value'] * $row['pcr_quantity'] * $p['op_quantity'];
                    } //    foreach($product_combine_arr

                }
            }
            $result['totalValue'] = $p['totalValue'] * $p['currency_rate'];

        }

        return $result;
    } //end function

    /*计算订单的申报价值
    $orderProductRows的数据对应order_product表的数据
    $is_return_total==1的时候返回总值而不返回一行行的记录
     */
    public static function getDeclaredValue($order_code, $is_return_total = 0)
    {
        $total         = 0;
        $orderProducts = Service_OrderProduct::getByCondition(array('order_code' => $order_code), "*");
        if (!$orderProducts) {return;}
        foreach ($orderProducts as $p) {
            $prd              = Service_Product::getByField($p['product_id'], "product_id", "*");
            $p['product_sku'] = $prd['product_sku'];
            //  $p['category_name'] = $categories[$prd['pc_id']]['pc_name'];
            $p['product_type']  = $prd['product_type'];
            $p['currency_code'] = 'RMB';
            if ($prd['currency_code']) {
                $currency_array = Service_Currency::getByField($prd['currency_code'], 'currency_code', "*");
            } else {
                $currency_array = Service_Currency::getByField('RMB', 'currency_code', "*");
            }
            //if($prd['currency_code']){$p['currency_code'] = $prd['currency_code'];}
            //$currency_array = Service_Currency::getByField($p['currency_code'],'currency_code',"*");
            $p['currency_rate'] = 1;
            if ($currency_array) {$p['currency_rate'] = $currency_array['currency_rate'];}
            $p['totalWeight'] = 0;
            $p['totalValue']  = 0;

            if ($p['product_type'] == 0 || $p['product_type'] == '1') {
                $p['totalWeight'] = $prd['product_weight'] * $p['op_quantity'];
                $p['totalValue']  = ($p['op_declared_value'] * $p['op_quantity']);
            }
            /*
            if($p['product_type']==1){
            $product_combine_arr = Service_ProductCombineRelation::getByCondition(array('product_id'=>$prd['product_id']));
            if($product_combine_arr && is_array($product_combine_arr)){
            foreach($product_combine_arr as $row){
            $prdson = Service_Product::getByField($row['pcr_product_id'],"product_id","*");
            if(empty($prdson)){continue;}
            if($prdson['currency_code']){
            $currency = Service_Currency::getByField($prdson['currency_code'],"currency_code","*");
            }else{
            $currency = Service_Currency::getByField('RMB',"currency_code","*");
            }
            $p['totalWeight']+= $prdson['product_weight']*$row['pcr_quantity']*$p['op_quantity'];
            $p['totalValue']+= $p['op_declared_value']*$p['op_quantity']*$currency['currency_rate'];
            }

            }
            }
             */

            //$p['totalValue'] = round($p['totalValue']*$p['currency_rate'],2);
            $total += $p['totalValue'];
            $products[] = $p;
        }
        if ($is_return_total == '1') {return $total;}
        return $products;

    } //function end

    /*colin 计算总申报价值*/
    public static function getDeclaredValue2($order_code)
    {
        $total         = 0;
        $orderProducts = Service_OrderProduct::getByCondition(array('order_code' => $order_code), "*");
        if (!$orderProducts) {return;}
        foreach ($orderProducts as $p) {
            $prd = Service_Product::getByField($p['product_id'], "product_id", "*");
            if (empty($prd) || $prd['product_type'] == '1') {continue;}
            $total += $p['op_declared_value'] * $p['op_quantity'];

        }
        return $total;
    } //function end

    /*colin 计算海关申报总价*/
    public static function getHSTotalPrice($order_code)
    {
        $total         = 0;
        $orderProducts = Service_OrderProduct::getByCondition(array('order_code' => $order_code), "*");
        if (!$orderProducts) {return;}
        foreach ($orderProducts as $p) {
            $prd = Service_Product::getByField($p['product_id'], "product_id", "*");
            if (empty($prd) || $prd['product_type'] == '1') {continue;}
            $total += $p['op_purpose_declared_value'] * $p['op_quantity'];

        }
        return $total;
    } //function end

    public static function interceptTranslate($data, $customerId)
    {
        $result     = array('ask' => 0, 'message' => '拦截失败', 'error' => array(), 'reference_no' => '');
        $orderCode  = $data['order_code'];
        $ordersInfo = Service_Orders::getByField($orderCode, 'order_code');
        $error      = array();
        if (empty($ordersInfo)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('OrdersInvalid'); //'订单无效';
        }
        if (empty($customerId)) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('CustomerError'); //'客户错误';
            return $result;
        }
        if (trim($data['intercept_reason']) == '') {
            $result['message'] = '拦截原因不能为空';
            return $result;
        }
        if ($ordersInfo['intercept_status'] != '0') {
            $result['message'] = '该订单已拦截,不能再次拦截';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($ordersInfo['customer_id'] != $customerId) {
            $result['message'] = Ec_Lang::getInstance()->getTranslate('TheInconsistentOrdersAndCustomers'); //'该订单和客户不一致';
            return $result;
        }
        $DB = Common_Common::getAdapter();
        $DB->beginTransaction();
        try {
            if ($ordersInfo['order_mode_type'] == '0') {
                switch ($ordersInfo['order_status']) {
                    case "4":
                        self::tijiaoIntercept($ordersInfo, $data, $customerId);
                        break;
                    case "5":
                    case "6":
                    case "7":
                        self::otherIntercept($ordersInfo, $data, $customerId);
                        break;
                    default:
                        throw new Exception('订单不是已提交状态,不能拦截');
                }
            } else {
                throw new Exception('订单模式不对');
            }
            if ($ordersInfo['order_status'] == '4') {
                $message = "订单号:{$ordersInfo['order_code']}拦截成功，已移至删除状态";
            } else {
                $message = "订单号:{$ordersInfo['order_code']}拦截申请被确认成功，待仓库确认";
            }
            $result['ask']     = '1';
            $result['message'] = $message; //'订单拦截成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        //print_r($result);exit;
        return $result;
    }

    public static function tijiaoIntercept($orderInfo, $data, $customerId)
    {
        $orderRow = array(
            'order_status'     => '0',
            'intercept_status' => '3',
            'intercept_reason' => $data['intercept_reason'],
            'update_time'      => date('Y-m-d H:i:s', time()),
        );
        Service_Orders::update($orderRow, $orderInfo['order_id']);
        $OR = Service_Orders::getByField($orderInfo['order_code'],'order_code',"*");
        Service_Precaution::delete($OR['reference_no'],"precaution_value");
        $session     = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        $orderLog    = array(
            'order_id'          => $orderInfo['order_id'],
            'order_code'        => $orderInfo['order_code'],
            'ol_type'           => '0',
            'order_status_from' => $orderInfo['order_status'],
            'order_status_to'   => 0,
            'ol_add_time'       => date('Y-m-d H:i:s', time()),
            'user_id'           => '-1',
            'account_id'        => Service_Login::getUserId(),
            'ol_ip'             => Common_Common::getIP(),
            'ol_comments'       => "订单拦截,拦截原因:{$data['intercept_reason']}",
        );
        Service_OrderLog::add($orderLog);

        $nodeArr = array(
            'order_id'     => $orderInfo['order_id'],
            'order_code'   => $orderInfo['order_code'],
            'oon_add_time' => date('Y-m-d H:i:s'),
            'oon_note'     => $data['intercept_reason'],
            'user_id'      => '-1',
        );
        Service_OrderOperationNode::add($nodeArr);

        $opt = array(
            'cutoff_time'    => date("Y-m-d H:i:s"),
            'cutoff_user_id' => -1 * $sessionData['id'],
        );
        Service_OrderOperationTime::update($opt, $orderInfo['order_code'], 'order_code');

        $conOrderProduct = array(
            'order_code' => $orderInfo['order_code'],
        );

        if ($orderInfo['order_mode_type'] == '0') {
            //备货模式的订单退库存
            $orderProducts = Service_OrderProduct::getByCondition($conOrderProduct);
            if (!empty($orderProducts)) {
                foreach ($orderProducts as $keyop => $valueop) {
                    $conInventory = array(
                        'customer_id'  => $customerId,
                        'product_id'   => $valueop['product_id'],
                        'warehouse_id' => $orderInfo['warehouse_id'],
                    );
                    $productInventory = Service_ProductInventory::getByCondition($conInventory);
                    $p                = Service_Product::getByField($valueop['product_id'], 'product_id', "*");
                    if (!empty($productInventory)) {
                        $inventory = $productInventory[0];
                        if ($inventory['pi_sellable'] - $valueop['op_quantity'] < 0) {
                            //throw new Exception(";
                            $errorInventory[] = "{$p['product_sku']}" . Ec_Lang::getInstance()->getTranslate('AvailableStockIsNegativeCanNotSubmitOrders');
                        }
                        //修改product_inventory 记录
                        $productInventoryRow = array(
                            'pi_sellable'    => $inventory['pi_sellable'] + $valueop['op_quantity'],
                            'pi_reserved'    => $inventory['pi_reserved'] - $valueop['op_quantity'],
                            'pi_update_time' => date('Y-m-d H:i:s', time()),
                        );
                        Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
                        $productInventoryLogRow = array(
                            'product_id'      => $valueop['product_id'],
                            'product_barcode' => $valueop['product_barcode'],
                            'warehouse_id'    => $orderInfo['warehouse_id'],
                            'user_id'         => '-1',
                            'pil_sellable'    => $inventory['pi_sellable'] + $valueop['op_quantity'],
                            'pil_reserved'    => $inventory['pi_reserved'] - $valueop['op_quantity'],
                            'pil_onway'       => $inventory['pi_sellable'] + $valueop['op_quantity'],
                            'pil_pending'     => $inventory['pi_pending'],
                            'pil_unsellable'  => $inventory['pi_unsellable'],
                            'pil_shipped'     => $inventory['pi_shipped'],
                            'pil_quantity'    => $valueop['op_quantity'],
                            'pil_ip'          => Common_Common::getIP(),
                            'pil_note'        => '订单截单,退库存',
                            'pil_add_time'    => date('Y-m-d H:i:s', time()),
                            'reference_code'  => $valueop['order_code'],
                            'from_it_code'    => 'Submitted',
                            'to_it_code'      => 'delete',
                        );
                        Service_ProductInventoryLog::add($productInventoryLogRow);
                    } else {
                        $errorInventory[] = "{$p['product_sku']}" . '无库存';
                    }
                }
            }
            //截单解冻金额
            $balanceProcess = new Service_CustomerBalanceProcess();
            //环球的客户是直接扣费的
            if( Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $orderInfo['customer_code'] ) ) {
                $feeResult      = $balanceProcess->returnFee( $orderInfo['order_code'] );
                if ($feeResult !== true) {
                    throw new Exception( implode( ',', $balanceProcess->getError() ) );
                }
            } else {
                $feeResult      = $balanceProcess->unfreezeFee($orderInfo['order_code'], $customerId);
                if ($feeResult !== true) {
                    throw new Exception($feeResult);
                }
            }
        }
    }

    /**
     * @todo 用于5:已打印;6:已下架;7:已打包 的拦截
     */
    public static function otherIntercept($orderInfo, $data, $customerId)
    {
        $orderRow = array(
            'intercept_status' => '1',
            'intercept_reason' => $data['intercept_reason'],
            'update_time'      => date('Y-m-d H:i:s', time()),
        );
        Service_Orders::update($orderRow, $orderInfo['order_id']);
        Service_Precaution::delete($orderInfo['reference_no'],"precaution_value");
        $session     = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        $orderLog    = array(
            'order_id'          => $orderInfo['order_id'],
            'order_code'        => $orderInfo['order_code'],
            'ol_type'           => '0',
            'order_status_from' => $orderInfo['order_status'],
            'order_status_to'   => $orderInfo['order_status'],
            'ol_add_time'       => date('Y-m-d H:i:s', time()),
            'user_id'           => '-1',
            'account_id'        => Service_Login::getUserId(),
            'ol_ip'             => Common_Common::getIP(),
            'ol_comments'       => "订单拦截,拦截原因:{$data['intercept_reason']}",
        );
        Service_OrderLog::add($orderLog);

        $nodeArr = array(
            'order_id'     => $orderInfo['order_id'],
            'order_code'   => $orderInfo['order_code'],
            'oon_add_time' => date('Y-m-d H:i:s'),
            'oon_note'     => $data['intercept_reason'],
            'user_id'      => '-1',
        );
        Service_OrderOperationNode::add($nodeArr);

        $opt = array(
            'cutoff_time'    => date("Y-m-d H:i:s"),
            'cutoff_user_id' => -1 * $sessionData['id'],
        );
        Service_OrderOperationTime::update($opt, $orderInfo['order_code'], 'order_code');
    }

    public function createOrderToStatus24($row)
    {
        $row['action'] = 'add';
        $result        = array("ask" => 0, "message" => Ec_Lang::getInstance()->getTranslate('CreateOrdersFailed'), "ordersCode" => ''); //"创建订单失败"
        //$error         = $this->validateProduct($row['order_product'], $row);

        if ($row['order_type'] == 3) {
            $row['shipping_method'] = 'SELFPICKUP';
        }

        /*$error1 = $this->validateInput($row);
        if (!empty($error1['error'])) {$error = array_merge($error, $error1['error']);}*/

        if ($row['order_mode_type'] == '0') {
            $row['change_order'] = '1';
        }
        $validateObj = new Service_OrderDataValidate();
        if( !$validateObj->validate( $row ) ) {
            $error = $validateObj->getError();
        } else {
            $this->_parcel = $validateObj->getParcel();
        }
        $row = $validateObj->getOrder();
	//派送通知服务、保障服务
        if(($row['sm_code'] == "BH-DHL-HKDELIVERY")){
            if((($row['dispatch_notice'] == '') || ($row['guarantee'] == ''))){
                $error = '运输方式为BH-DHL-HKDELIVERY时，派送通知服务、保障服务选项为必填';
            }
        }else{
            $row['dispatch_notice'] = $row['guarantee'] = '0';
        }

        if (!empty($error)) {
            $result['error'] = $error;
            $result['order_code'] = isset($error1['order_code'])?$error1['order_code']:"";
            return $result;
        }
        $lessInvSku = array();
        $db         = Common_Common::getAdapter();
        $db->beginTransaction();
        $session     = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {

            $customer   = Service_Customer::getByField($row['customer_id'], 'customer_id');
            //验证冻结
            if( isset($customer['is_frozen']) && $customer['is_frozen'] == 1 ){
                throw new Exception('客户['.$customer['customer_code'].']已冻结，冻结原因：'.$customer['frozen_reason']);
            }
            $ordersCode = Common_GetNumbers::getCode('order', $customer['customer_code'], 'SO');
            $time       = date("Y-m-d H:i:s");

            $parcel = $this->_parcel;

            $currency              = Service_Currency::getByField($customer['customer_currency'], 'currency_code', "*");
            $parcel_quantity       = $parcel['parcel_quantity'];
            $parcel_contents       = $parcel['parcel_contents'];
            $parcel_declared_value = $parcel['parcel_declared_value'];
            $plateform = isset($row['platform']) ? $row['platform'] : "0";
            if( Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $customer['customer_code'] ) ) {
                $plateform = 2;
            }
            $orderRow = array(
                'order_code'            => $ordersCode,
                'customer_id'           => $row['customer_id'],
                'customer_code'         => $customer['customer_code'],
                'warehouse_id'          => $row['warehouse_id'],
                'order_type'            => $row['order_type'],
                'sm_code'               => $row['sm_code'],
                'parcel_declared_value' => round($parcel_declared_value / $currency['currency_rate'], 2),
                'shipping_fee_estimate' => '0', //暂时还没明确怎么计算
                'currency_code'         => $customer['customer_currency'],
                'parcel_contents'       => $parcel_contents,
                'parcel_quantity'       => $parcel_quantity,
                'order_status'          => '1',
                'reference_no'          => $row['reference_no'],
                'currency_code'         => $row['currency_code'],
                'charge'                => $row['charge'],
                'add_time'              => $time,
                'update_time'           => $time,
                'remark'                => $row['remark'],
                'delivery_address'      => $row['delivery_address'],
                'platform'              => $plateform,
                'trade_mode'            => isset($row['trade_mode']) ? $row['trade_mode'] : "",
                'is_pod' => isset($row['is_pod']) ? $row['is_pod'] : '0',
	        'insurance' => isset($row['insurance']) && $row['insurance'] == 1 ? 1 : 0,
                'insurance_rate' => isset($row['insurance_rate']) && $row['insurance'] == 1 ? $row['insurance_rate'] : 1,
                'insurance_code' => isset($row['insurance_code']) && $row['insurance'] == 1 ? $row['insurance_code'] : '',
            );
            $orderRow['order_pick_type'] = '0';
            $orderProducts               = $row['order_product'];
            if (count($orderProducts) >= 2) {
                $orderRow['order_pick_type'] = '2';
            } else {
                if (isset($orderProducts[0]['qty']) && $orderProducts[0]['qty'] > 1) {
                    $orderRow['order_pick_type'] = '1';
                }
            }
            if ($row['order_mode_type'] == '1') {
                $orderRow['order_mode_type']     = '1';
                $orderRow['change_order']        = $row['change_order'];
                $orderRow['ref_tracking_number'] = $row['ref_tracking_number'];
            } else {
                $orderRow['order_mode_type']     = '0';
                $orderRow['change_order']        = '1'; //备货模式一定换单
                $orderRow['ref_tracking_number'] = ''; //服务商单号为客户填写
            }
            if ($orderRow['sm_code'] == "WG-EUB-EBAY") {
                $orderRow['ref_tracking_number'] = isset($row['ref_tracking_number']) ? $row['ref_tracking_number'] : "";
            }

            //如果是偏远城市或者地区，增加提示信息
            $orderRow['is_remote_city'] = 0;
            $isRemoteCity               = false;
            $needCheckRemote = array('WWDHLU','WWDHLP','HKDHL','HTTX-HKDHL','BH-HKDHL','CNDHL','DHL-TH','DGM-US','DHL-BH03');
            if ( in_array( $row['sm_code'], $needCheckRemote ) ) {
                $isRemoteCity = $this->isRemoteCity($row['oab_country_id'], $row['oab_city'], $row['oab_postcode']);
                if ($isRemoteCity === true) {
                    $orderRow['is_remote_city'] = 1;
                }
                if($row['sm_code'] == 'CNDHL'){
                    $orderRow['is_remote_city'] = 0;
                }

            }else {
                $isRemoteCity = Service_Remote::checkRemote($row['oab_country_id'], $row['oab_city'], $row['oab_postcode'], $orderRow['sm_code'], $row['warehouse_id']);
                if ($isRemoteCity === true) {
                    $orderRow['is_remote_city'] = 1;
                }

            }
            $order_id = Service_Orders::add($orderRow);
            if (!$order_id) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorCreateOrderFails'));
            }

            $w = Service_Warehouse::getByField($orderRow['warehouse_id'], 'warehouse_id', '*');
            if ($orderRow['order_mode_type'] == '0') {
                $sotDescription = '备货订单新建成功,草稿状态';
                $warehouseName  = $w['warehouse_desc'];
            } else {
                $sotDescription = '集货订单新建成功,草稿状态';
                $warehouseName  = "客户仓库";
            }
            $shipOrderTracking = array(
                'order_code'          => $ordersCode,
                'sot_location'        => $warehouseName,
                'sot_add_time'        => $time,
                'warehouse_id'        => $orderRow['warehouse_id'],
                'sot_description'     => $sotDescription,
                'sot_type'            => '0',
                'sot_time_offset'     => '',
                'tracking_number'     => $ordersCode,
                'ref_tracking_number' => '',
                'status_desc'         => '草稿',
                'user_id'             => -1 * $sessionData['id'],
            );
            Service_ShipOrderTracking::add($shipOrderTracking);

            //收件人
            $addressBookRow = array(
                'order_id'            => $order_id,
                'order_code'          => $ordersCode,
                'oab_firstname'       => $row['oab_firstname'],
                'oab_lastname'        => $row['oab_lastname'],
                'oab_company'         => $row['oab_company'] ? $row['oab_company'] : $row['oab_firstname'],
                'oab_country_id'      => $row['oab_country_id'],
                'oab_postcode'        => $row['oab_postcode'],
                'oab_state'           => $row['oab_state'],
                'oab_city'            => $row['oab_city'],
                'oab_street_address1' => $row['oab_street_address1'],
                'oab_street_address2' => $row['oab_street_address2'],
                'oab_phone'           => $row['oab_phone'],
                'oab_cell_phone'      => $row['oab_phone'],
                'oab_email'           => $row['oab_email'],
                'oab_type'            => '0',
            );

            if (!Service_OrderAddressBook::add($addressBookRow)) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorOrdersAddressWriteFailure') . "...-->" . $ordersCode);
            }

            $totaldeclare = 0;
            foreach ($row['order_product'] as $v) {
                $productId     = $v['product_id'];
                $qty           = trim($v['qty']);
                $declare_price = 0;
                $haveDeclare   = false;
                if (isset($v['declare_price'])) {
                    $declare_price = trim($v['declare_price']);
                    $haveDeclare   = true;
                }
                $product_title_en = $v['product_title_en'];

                $purpose_declared_value = $v['op_declared_value'];

                $product = Service_Product::getByField($productId, 'product_id');

                if (!$haveDeclare) {
                    //没有设置declare 就用订单的declare_value
                    $declare_price = $product['product_declared_value'];
                }
                if (empty($product_title_en)) {
                    //没传递就用产品的的
                    $product_title_en = $product['product_title_en'];
                }
                $orderProductRow = array(
                    'order_id'                  => $order_id,
                    'order_code'                => $ordersCode,
                    'product_id'                => $productId,
                    'product_barcode'           => $product['product_barcode'],
                    'product_title_en'          => $product_title_en,
                    'op_quantity'               => $qty,
                    'op_declared_value'         => $declare_price,
                    'op_purpose_declared_value' => $purpose_declared_value,
                    'op_category'               => $product['pc_id'],
                    'op_add_time'               => $time,
                );

                $totaldeclare += $purpose_declared_value * $qty;
                $op_id = Service_OrderProduct::add($orderProductRow);
                if (!$op_id) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('InternalErrorOrdersAddressWriteFailure') . "....-->" . $ordersCode, '50000');
                }
                if ($orderRow['sm_code'] == "WG-EUB-EBAY") {
                    $ebayOrderDetail = array(
                        'op_id'                     => $op_id,
                        'order_code'                => $ordersCode,
                        'ebay_item_id'              => $v['ebay_item_id'],
                        'ebay_transaction_id'       => $v['ebay_transaction_id'],
                        'ebay_buyer_id'             => $v['ebay_buyer_id'],
                        'ebay_item_title'           => '',
                        'ebay_email'                => '',
                        'sold_qty'                  => $qty,
                        'posted_qty'                => $qty,
                        'order_sales_record_number' => '',
                        //'order_id',
                        'ebay_site_id'              => '',
                        'received_amount'           => '',
                        'payment_date'              => '',
                        'sold_price'                => '',
                        'sold_date'                 => '',
                        'currency_code'             => '',
                        'ebay_message'              => '',
                        'paypal_email'              => '',
                        'paypal_message'            => '',
                        'note'                      => '',
                    );
                    Service_EbayOrderDetail::add($ebayOrderDetail);
                }

            }
            if ($orderRow['sm_code'] == 'HKPG') {
                $totaldeclareHK = Service_Currency::converByCode("USD", "HKD", $totaldeclare);
                if ($totaldeclareHK > 3000) {
                    throw new Exception("HKPG总目的海关申报价值大于3000HKD");
                }
            }

            $orderOperateType = Service_OrderOperationType::getByField('add', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $order_id,
                    'order_code'   => $ordersCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }

            $oot = array(
                'order_id'     => $order_id,
                'order_code'   => $ordersCode,
                'confirm_time' => date("Y-m-d H:i:s"),
                //'creater_id'=>$sessionData['id']
            );
            $oot['creater_id'] = isset($sessionData['id']) ? $sessionData['id'] : $orderRow['customer_id'];
            Service_OrderOperationTime::add($oot);

            $logRow = array(
                'order_id'          => $order_id,
                'order_code'        => $ordersCode,
                'ol_type'           => '1',
                'order_status_from' => $row['order_status'],
                'order_status_to'   => $row['order_status'],
                'ol_add_time'       => $time,
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($logRow);
            if($orderRow['reference_no']!=""){
                // 添加预警
                Service_Precaution::insert(array(
                    'precaution_value' => $orderRow['reference_no'],
                ));
            }
            //$this->writeOrderLog($logRow);
            $message = Ec_Lang::getInstance()->getTranslate('CreateOrder') . " [{$ordersCode}]" . Ec_Lang::getInstance()->getTranslate('success');
            if ($isRemoteCity === true) {
                $message .= '<br>订单属于偏远地区，如需修改，请在草稿状态下进行编辑修改';
            }
              $invoceContry=Service_ShippingMethodConfig::getInvoiceContry();
            if (in_array($orderRow['sm_code'],array('HKDHL','BH-HKDHL','CNDHL','WWDHLP','WWDHLU'))&&in_array($row['oab_country_id'],$invoceContry)) {
                if($row['oab_country_id']!='251'){
                    $message .= '<br><span style="color:red">该订单需提供正本发票</span>';
                }else{
                    if($totaldeclare>Service_ShippingMethodConfig::$purPusDecalar){
                        $message .= '<br><span style="color:red">该订单需提供正本发票</span>';
                    }
                }
            }
            $updateOrderRow = array(
                'order_status' => '2',
                'update_time'  => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Orders::update($updateOrderRow, $ordersCode, 'order_code')) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed')); //"订单状态更改失败"
            }

            $SMRow = Service_ShippingMethod::getByField($row['sm_code'], "sm_code", "*");
            if (!in_array($row['sm_code'], array("SZY-EUB", 'WG-EUB', "UKTL", "SZY-ETK", 'BH-USPS','BH-SFEP',
                'BH-DPD','SF-RUPR','SF-RUPT','Rumall-RU-EP','Rumall-RU-G','4PX-LYT_GH','4PX-EU_PACKET','4PX-RU_POST-LINK_RMAIL','4PX-HKDHL','PNLN','PNLG','4PX-YX','4PX-SG_ordinary_mail+','LYT-SMTGH-X','BH-BEAT','BH-NLAT'))) {
                if ($SMRow['sm_class_code'] == "CRP" && $orderRow['order_mode_type'] == "1" && $orderRow['ref_tracking_number'] == ""||(($orderRow['sm_code']=='4PX-Singapo_SPack_IMAIR' || $orderRow['sm_code']=='4PX-OZXBTH') && $orderRow['ref_tracking_number'] == ""
                         )) {
                    $condition = array(
                        'sm_code'      => $orderRow['sm_code'],
                        'warehouse_id' => $orderRow['warehouse_id'],
                        'stn_status'   => '0',
                    );
                    $STNList = Service_ServiceTrackingNumber::getByCondition($condition, "*", 1, 1, "stn_id asc");
                    if (empty($STNList)) {
                        throw new Exception("没有可以分配的预存单号!");
                    }
                    $ServiceTrackingNumber = array(
                        'order_code'      => $ordersCode,
                        'stn_status'      => '1',
                        'stn_update_time' => date("Y-m-d H:i:s"),
                    );

                    $refTrackingNumber = array(
                        'ref_tracking_number' => $STNList[0]['stn_code'],
                    );
                    Service_ServiceTrackingNumber::update($ServiceTrackingNumber, $STNList[0]['stn_id'], 'stn_id');
                    Service_Orders::update($refTrackingNumber, $ordersCode, 'order_code');
                }
            }

            //$customerRow = Service_Customer::getByField($orderRow['customer_id']);

            $orderOperateType = Service_OrderOperationType::getByField('confirm', 'oot_code'); //提交订单操作
            if (!empty($orderOperateType)) {
                $orderOperationNodeRow = array(
                    'order_id'     => $order_id,
                    'order_code'   => $ordersCode,
                    'oot_code'     => $orderOperateType['oot_code'],
                    'oon_note'     => '',
                    'oon_add_time' => date('Y-m-d H:i:s', time()),
                    'user_id'      => '-1',
                );
                Service_OrderOperationNode::add($orderOperationNodeRow);
            }

            $orderOperationTime = Service_OrderOperationTime::getByField($order_id, 'order_id', "*");
            if (!empty($orderOperationTime)) {
                $oot = array(
                    'confirm_time'    => date("Y-m-d H:i:s"),
                    'confirm_user_id' => -1 * $sessionData['id'],
                );
                Service_OrderOperationTime::update($oot, $orderOperationTime['oot_id'], "oot_id");
            } else {
                $oot = array(
                    'order_id'        => $order_id,
                    'order_code'      => $ordersCode,
                    'confirm_time'    => date("Y-m-d H:i:s"),
                    'confirm_user_id' => -1 * $sessionData['id'],
                );
                Service_OrderOperationTime::add($oot);
            }

            $orderLog = array(
                'order_id'          => $order_id,
                'order_code'        => $ordersCode,
                'ol_type'           => '1',
                'order_status_from' => '1',
                'order_status_to'   => '2',
                'ol_add_time'       => date('Y-m-d H:i:s', time()),
                'user_id'           => '-1',
                'account_id'        => Service_Login::getUserId(),
                'ol_ip'             => Common_Common::getIP(),
            );
            Service_OrderLog::add($orderLog);

            $w = Service_Warehouse::getByField($orderRow['warehouse_id'], 'warehouse_id', '*');
            if ($orderRow['order_mode_type'] == "0") {
                $sotDescription = '备货订单确认成功,待提交';
                $warehouseName  = $w['warehouse_desc'];
            } else {
                $sotDescription = "集货订单确认成功,待提交";
                $warehouseName  = "客户仓库";
            }
            $shipOrderTracking = array(
                'order_code'          => $ordersCode,
                'sot_location'        => $warehouseName,
                'sot_add_time'        => date("Y-m-d H:i:s"),
                'warehouse_id'        => $orderRow['warehouse_id'],
                'sot_description'     => $sotDescription,
                'sot_type'            => '0',
                'sot_time_offset'     => '',
                'tracking_number'     => $ordersCode,
                'ref_tracking_number' => '',
                'status_desc'         => '确认',
                'user_id'             => -1 * $sessionData['id'],
            );
            Service_ShipOrderTracking::add($shipOrderTracking);

            //DHL空运处理
            if ($orderRow['sm_code'] == 'DGF-CARGO'){
                $orderShipping = array(
                    'order_code'=>$ordersCode,
                    'notify_tel'=>isset($row['shippingInfo']['notifyTel'])?$row['shippingInfo']['notifyTel']:'',
                    'notify_contact'=>isset($row['shippingInfo']['notifyContact'])?$row['shippingInfo']['notifyContact']:'',
                    'notify_addr'=>isset($row['shippingInfo']['notifyAddr'])?$row['shippingInfo']['notifyAddr']:'',
                    //'discharge_port'=>$row['shippingInfo']['dischargePort'],
                    'destination'=>isset($row['shippingInfo']['destination'])?$row['shippingInfo']['destination']:'',
                    'service_model'=>isset($row['shippingInfo']['serviceModel'])?$row['shippingInfo']['serviceModel']:'',
                    'delivery_terms'=>isset($row['shippingInfo']['deliveryTerms'])?$row['shippingInfo']['deliveryTerms']:'',
                    //'hs_code'=>$row['shippingInfo']['hsCode'],
                    'is_dgd'=>isset($row['shippingInfo']['isDGD'])?$row['shippingInfo']['isDGD']:'0',
                    'hs_description'=>isset($row['shippingInfo']['hsDescription'])?$row['shippingInfo']['hsDescription']:'',
                    //'pkg_total_amt'=>$row['shippingInfo']['pkgTotalAmt'],
                    //'pkg_total_vol'=>$row['shippingInfo']['pkgTotalVol'],
                    //'pkg_gw'=>$row['shippingInfo']['pkgGW'],
                    //'pkg_vw'=>$row['shippingInfo']['pkgVW'],
                    'is_battery'=>isset($row['shippingInfo']['isBattery'])?$row['shippingInfo']['isBattery']:'0',
                    'is_battery_rmk'=>isset($row['shippingInfo']['isBatteryRmk'])?$row['shippingInfo']['isBatteryRmk']:'',
                    'insured_account'=>isset($row['shippingInfo']['insuredAccount'])?$row['shippingInfo']['insuredAccount']:'',
                );
                file_put_contents(APPLICATION_PATH.'/../data/log/'.'ServiceForOrder2.txt',var_export($row,true),FILE_APPEND);
                Service_OrderShipping::add($orderShipping);
                /*if(!empty($row['shippingInfo']['package'])){
                    $prodetail = array();
                    $pradetail=$row['shippingInfo']['package'];
                    if(!empty($pradetail) && is_array($pradetail['0'])){

                    }else{
                        $pradetail = array($pradetail);
                    }
                    foreach($pradetail as $key=>$value){
                        $packageRow = array(
                            'order_code'=>$ordersCode,
                            'amt'=>$value['amt'],
                            'pkg_type'=>$value['pkgType'],
                            'pkg_length'=>$value['length'],
                            'pkg_width'=>$value['width'],
                            'pkg_height'=>$value['height'],
                        );
                        Service_Package::add($packageRow);
                    }
                }*/
            }



            //冻结金额
            $balanceProcess = new Service_CustomerBalanceProcess();
            $feeResult      = $balanceProcess->freezeFeeCheck($ordersCode, $orderRow['customer_id']);
            if ($feeResult !== true) {
                throw new Exception($feeResult);
            }

            if ($row['order_status'] == "4") {
                //$orderStatus = '4';
                $ycString        = ''; //异常的字符串
                $updateOrderRow4 = array(
                    'order_status' => '4',
                    'update_time'  => date('Y-m-d H:i:s', time()),
                );

                //$customerRow = Service_Customer::getByField($customerId);
                if ($orderRow['order_mode_type'] == '0') {
                    //备货模式下的订单要检查库存

                    //查找订单下面的产品
                    $conOrderProduct = array(
                        'order_code' => $ordersCode,
                    );
                    $orderProducts = Service_OrderProduct::getByCondition($conOrderProduct, "*", 0, 1, '', "for update");
                    if (!empty($orderProducts)) {
                        $totalValue=0;
                        foreach ($orderProducts as $keyop => $valueop) {
                            $totalValue+=$valueop['op_purpose_declared_value']*$valueop['op_quantity'];
                            $conInventory = array(
                                'customer_id'  => $orderRow['customer_id'],
                                'product_id'   => $valueop['product_id'],
                                'warehouse_id' => $orderRow['warehouse_id'],
                            );
                            $productInventory = Service_ProductInventory::getByCondition($conInventory, "*", 0, 1, '', "for update");
                            $productRow       = Service_Product::getByField($valueop['product_id'], "product_id", "*");
                            if (!empty($productInventory)) {
                                $inventory = $productInventory[0];
                                if ($inventory['pi_sellable'] - $valueop['op_quantity'] < 0) {
                                    //throw new Exception(";
                                    $errorInventory[] = "{$valueop['product_barcode']}" . Ec_Lang::getInstance()->getTranslate('AvailableStockIsNegativeCanNotSubmitOrders');
                                    $lessInvSku[]     = $productRow['product_sku'];
                                }
                                //修改product_inventory 记录
                                $productInventoryRow = array(
                                    'pi_sellable'    => $inventory['pi_sellable'] - $valueop['op_quantity'],
                                    'pi_reserved'    => $inventory['pi_reserved'] + $valueop['op_quantity'],
                                    'pi_update_time' => date('Y-m-d H:i:s', time()),
                                );
                                Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
                                $productInventoryLogRow = array(
                                    'product_id'      => $valueop['product_id'],
                                    'product_barcode' => $valueop['product_barcode'],
                                    'warehouse_id'    => $orderRow['warehouse_id'],
                                    'user_id'         => '-1',
                                    'pil_sellable'    => $inventory['pi_sellable'] - $valueop['op_quantity'],
                                    'pil_reserved'    => $inventory['pi_reserved'] + $valueop['op_quantity'],
                                    'pil_onway'       => $inventory['pi_onway'],
                                    'pil_pending'     => $inventory['pi_pending'],
                                    'pil_unsellable'  => $inventory['pi_unsellable'],
                                    'pil_shipped'     => $inventory['pi_shipped'],
                                    'pil_ip'          => Common_Common::getIP(),
                                    'pil_add_time'    => date('Y-m-d H:i:s', time()),
                                    'pil_note'        => '订单确认提交',
                                    'from_it_code'    => 'Confirm',
                                    'to_it_code'      => 'Submitted',
                                    'reference_code'  => $valueop['order_code'],
                                    'pil_quantity'    => $valueop['op_quantity'],
                                );
                                Service_ProductInventoryLog::add($productInventoryLogRow);
                            } else {
                                $lessInvSku[]     = $productRow['product_sku'];
                                $errorInventory[] = "{$valueop['product_barcode']}" . '无库存';
                            }
                        }
                        //print_r($errorInventory);
                        if (isset($errorInventory) && !empty($errorInventory)) {
                            //$orderStatus = '3'; //订单到异常状态
                            $ycString .= implode('<br/>', $errorInventory);
                            throw new Exception($ycString, '110');
                        }
                    }

                    $orderLog = array(
                        'order_id'          => $order_id,
                        'order_code'        => $ordersCode,
                        'ol_type'           => '1',
                        'order_status_from' => 2,
                        'order_status_to'   => 4,
                        'ol_add_time'       => date('Y-m-d H:i:s', time()),
                        'user_id'           => '-1',
                        'account_id'        => Service_Login::getUserId(),
                        'ol_ip'             => Common_Common::getIP(),
                        //'ol_comments'=>$batchNumber,
                    );
                    Service_OrderLog::add($orderLog);

                    $orderOperateType = Service_OrderOperationType::getByField('submit', 'oot_code'); //提交订单操作
                    if (!empty($orderOperateType)) {
                        $orderOperationNodeRow = array(
                            'order_id'     => $order_id,
                            'order_code'   => $ordersCode,
                            'oot_code'     => $orderOperateType['oot_code'],
                            'oon_note'     => '',
                            'oon_add_time' => date('Y-m-d H:i:s', time()),
                            'user_id'      => '-1',
                        );
                        Service_OrderOperationNode::add($orderOperationNodeRow);
                    }

                    $opt = Service_OrderOperationTime::getByField($order_id, 'order_id', "*");
                    if (!empty($opt)) {
                        $orderOperationTime = array(
                            'order_code'     => $ordersCode,
                            'submit_time'    => date("Y-m-d H:i:s"),
                            'submit_user_id' => -1 * $sessionData['id'],
                        );
                        Service_OrderOperationTime::update($orderOperationTime, $opt['oot_id'], "oot_id");
                    } else {
                        $orderOperationTime = array(
                            'order_id'          => $order_id,
                            'order_code'        => $ordersCode,
                            'cutoff_time'       => '',
                            'submit_time'       => date("Y-m-d H:i:s"),
                            'process_time'      => '',
                            'pack_time'         => '',
                            'ship_time'         => '',
                            'import_time'       => '',
                            'delivered_time'    => '',
                            'sync_time'         => '',
                            'update_time'       => '',
                            'process_user_id'   => '',
                            'pack_user_id'      => '',
                            'import_user_id'    => '',
                            'ship_user_id'      => '',
                            'delivered_user_id' => '',
                            'cutoff_user_id'    => '',
                            'submit_user_id'    => -1 * $sessionData['id'],
                        );
                        Service_OrderOperationTime::add($orderOperationTime);
                    }

                    $w                 = Service_Warehouse::getByField($orderRow['warehouse_id'], 'warehouse_id', '*');
                    $shipOrderTracking = array(
                        'order_code'          => $ordersCode,
                        'sot_location'        => $w['warehouse_desc'],
                        'sot_add_time'        => date("Y-m-d H:i:s"),
                        'warehouse_id'        => $orderRow['warehouse_id'],
                        'sot_description'     => '备货订单提交成功,待仓库系统确认',
                        'sot_type'            => '0',
                        'sot_time_offset'     => '',
                        'tracking_number'     => $ordersCode,
                        'ref_tracking_number' => '',
                        'status_desc'         => '已提交',
                        'user_id'             => -1 * $sessionData['id'],
                    );
                    Service_ShipOrderTracking::add($shipOrderTracking);
                  /*if ($ordersInfo['sm_code']=='HKDHL'&& $totalValue<=120) {
                    //不冻结
                    }else{*/
                    //冻结金额
                    //环球的客户是直接扣费的
                    if( Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner( $orderRow['customer_code'] ) ) {
                        $feeResult      = $balanceProcess->deductFee( $ordersCode );
                        if ($feeResult !== true) {
                            $error = implode( ',', $balanceProcess->getError() );
                            throw new Exception($error, '111');
                        }
                    } else {
                        $balanceProcess = new Service_CustomerBalanceProcess();
                        $feeResult      = $balanceProcess->freezeFee($ordersCode, $orderRow['customer_id']);
                        if ($feeResult !== true) {
                            throw new Exception($feeResult, '111');
                        }
                    }
                    //}
                }
                if (!Service_Orders::update($updateOrderRow4, $ordersCode, 'order_code')) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('OrderStatusChangeFailed'));
                }
            }
            $db->commit();
            $result['ask']        = 1;
            $result['lessInvSku'] = $lessInvSku;
            $result['message']    = $message;
            $result['ordersCode'] = $ordersCode;

        } catch (Exception $e) {
            $db->rollback();
            $result['lessInvSku'] = $lessInvSku;
            $result['ask']        = 0;
            $result['message']    = $e->getMessage();
        }
        return $result;
    }
    public static function getPrintNo(){
        $table= new Table_Orders();
        $condition=array(
             'application_code' =>'HJTW_SEQUESE',
        );
         $application = Service_Application::getByCondition($condition, '*');
         if(empty($application)){
             $addRow=array(
                 'application_code' =>'HJTW_SEQUESE',
                 'application_name'=>'TWPG与TWPP面单序列号',
                 'current_number'=>'0',
                 'rule'=>1,
                 'app_add_time'=>date('Y-m-d H:i:s'),
                 );

             Service_Application::add($addRow);
             $application[0]=$addRow;
         }
          $start=  $application[0]['current_number'];
          $loopNumber=1;
          $endLoop='2';//正式2
          $startMax=99;//正式99
          $dayMax=1500;//正式1500
          $twoweekMax=5000;//正式5000
        do{
            $printNo=  '100561-0016'.str_pad($start,'2','0',STR_PAD_LEFT);


            $printCondition=array(
                    'sm_code_in'=>array('TWPG','TWPP'),
                    'confirmDateFor'=>date('Y-m-d').' 00:00:00',
                    'confirmDateTo'=>date('Y-m-d').' 23:59:59',
                    'print_no'=>$printNo,
            );
            $count=  $table->getLeftJoinAllByCondition($printCondition,'count(*)');

            $twoWeekCountCondition=array(
                     'sm_code_in'=>array('TWPG','TWPP'),
                    'confirmDateFor'=>date('Y-m-d',  strtotime('-15 days',strtotime(date('Y-m-d')))).' 00:00:00',
                    'confirmDateTo'=>date('Y-m-d').' 23:59:59',
                    'print_no'=>$printNo,
            );
            $twoWeekCount=  $table->getLeftJoinAllByCondition($twoWeekCountCondition,'count(*)');

            if($count<$dayMax&&$twoWeekCount<$twoweekMax){
                $updateRow=array(
                    'current_number'=>$start,
                    'app_update_time'=>date('Y-m-d H:i:s'),
                );
                Service_Application::update($updateRow, $application[0]['application_id']);
                return $printNo;
            }
            if($start==$startMax){
                 $updateRow=array(
                    'current_number'=>0,
                     'app_update_time'=>date('Y-m-d H:i:s'),
                );
                Service_Application::update($updateRow, $application[0]['application_id']);
                $start=-1;//
                $loopNumber+=1;
            }
            $start++;
        }while($loopNumber<$endLoop);
       return '';


    }

    /* @todo:添加物流信息
     * @desc:处理分销平台客户 环球
     * @author；gilbert
     * @param array $orderRow 订单信息
     * @param array  包裹信息
     * @return none
     */
    protected function addShipOrder( $orderRow ) {
        $warehouse = Common_DataCache::getWarehouse(0,$orderRow['warehouse_id']);
        $orderRow['customer_code'] = isset($orderRow['customer_code'])?$orderRow['customer_code']:'';
        if( $warehouse['warehouse_code'] != 'SZ01' || !in_array($orderRow['customer_code'],array('E0693')) ||  !in_array( $orderRow['sm_code'], array('HKDHL','BH-HKDHL') ) )
            return;

        $shipMethods = Service_ShippingMethod::getByCondition( array('sm_code'=>$orderRow['sm_code'],'warehouse_id_arr'=>array(0,$orderRow['warehouse_id'])),'*',0,0,'warehouse_id desc');
        //判断数据是否存在
        $shipOrder = Service_ShipOrder::getByField( $orderRow['order_code'], 'order_code');
        $text = '添加物流信息失败';
        if( !$shipOrder ) {
                $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $orderRow['customer_code'], 'SP');
                $shipOrder = array(
                    'so_code' => $soCode,
                    'order_id' => $orderRow['order_id'],
                    'order_code' => $orderRow['order_code'],
                    'tracking_number' => '',//WMS有自动任务去获取
                    'warehouse_id' => $orderRow['warehouse_id'],
                    'pp_barcode' => '',
                    'sm_code' => $orderRow['sm_code'],
                    'so_status' => '0',
                    'so_weight' => 0,
                    'so_vol_weight' =>0,
                    'so_length' => '',
                    'so_width' => '',
                    'so_height' => '',
                    'so_declared_value' => '',
                    'so_shipping_fee' => '',
                    'currency_code' => '',
                    'so_add_time' => date('Y-m-d H:i:s'),
                    'so_update_time' => date('Y-m-d H:i:s'),
                    'file_path' => '',
                    'so_piece' => 0,
                );
                $soId = Service_ShipOrder::add($shipOrder);
                if( !$soId )
                    throw new Exception( $text.'1' );
        } else {
            $text = '更新物流信息失败';
            $soCode = $shipOrder['so_code'];
            $soId = $shipOrder['so_id'];
            //先删除旧的明细
            $dResult = Service_ShipOrderDetail::delete($orderRow['order_code'],'order_code');
            if( !$dResult )
                throw new Exception( $text );
        }

        $totalPieces = 0;
        $totalWeight = $totalVolWeight = 0;

        $totalPieces = count($orderRow['pieceDetail']);
        foreach( $orderRow['piecesDetail'] as $piece) {



            //$pieceDetail = $this->_pieceDetail[ $product['product_id'] ];
            //foreach( $pieceDetail as $piece) {

            $volWeight = sprintf('%0.2f', ($piece['length'] * $piece['width'] * $piece['height'] ) / $shipMethods[0]['sm_vol_rate']);
            //$opSubtotal = $product['qty'] * $product['product_sales_value'];

            $totalWeight += $piece['weight'];
            $totalVolWeight += $volWeight;

            $shipOrderDetailRow = array(
                'so_code' => $soCode,
                'so_id' => $soId,
                'order_id' => $orderRow['order_id'],
                'order_code' => $orderRow['order_code'],
                'sub_tracking_number' => '',
                //'op_id' => $product['op_id'],
                //'op_title' => $piece['opDescription'],
                'sod_length' => $piece['length'],
                'sod_width' => $piece['width'],
                'sod_height' => $piece['height'],
                'sod_weight' => $piece['weight'],
                'sod_vol_weight' => $volWeight,
                //'sod_quantity' => $product['qty'],
                'op_description' => $piece['opDescription'],
                'cn_description' => $piece['cnDescription'],
                //'hs_code' => "",
                //'op_unit_price' => "",
                //'op_subtotal' => "",
                //'op_origin' => '',
                //'op_declared_value' => "",
            );
            $id = Service_ShipOrderDetail::add($shipOrderDetailRow);
            if( !$id )
                throw new Exception( $text.'2' );
        }
        $update = array('so_piece'=>$totalPieces,'so_weight'=>$totalWeight,'so_vol_weight'=>$totalVolWeight);
        if( $shipOrder['so_piece'] != $update['so_piece'] || $shipOrder['so_weight'] != $update['so_weight'] || $shipOrder['so_vol_weight'] != $update['so_vol_weight']) {
            $result = Service_ShipOrder::update($update ,$soId,'so_id');
            if( !$result )
                throw new Exception( $text.'3');
        }
    }

    protected function checkPieces( $pieces ) {
        if( !is_array( $pieces ) || empty( $pieces ) )
            return false;

        foreach( $pieces as $piece ) {
            if( !isset( $piece['serialNumber'] ) || !is_scalar( $piece['serialNumber'] ) || $piece['serialNumber'] === '' )
                return false;
            if( !isset( $piece['weight'] ) || !is_numeric( $piece['weight'] ) || $piece['weight'] <= 0 )
                return false;
            if( !isset( $piece['length'] ) || !is_numeric( $piece['length'] ) || $piece['length'] <= 0 )
                return false;
            if( !isset( $piece['width'] ) || !is_numeric( $piece['width'] ) || $piece['width'] <= 0 )
                return false;
            if( !isset( $piece['height'] ) || !is_numeric( $piece['height'] ) || $piece['height']  <= 0 )
                return false;
            //$this->_pieceDetail[$productId][$piece['serialNumber']] = $piece;
        }

        //ksort($this->_pieceDetail[$productId]);

        return true;
    }
    /* @todo:是否允许带电池
     *
     */
    public static function allowTakeBattery( $smCode, $countryId, $batteryType, $others = array() ) {
        $allow = array( 'allow' => true, 'msg' => '' );
        //不能带电池的运输方式
        $shipMethodNoBattery = self::getUnBatterySm();
        //渠道4PX-Singapo_SPack_IMAIR/4PX-SG_ordinary_mail+在英国/德国/意大利/老挝/埃及限制带电池产品
        $shipMethodNoBIB = array('4PX-Singapo_SPack_IMAIR', '4PX-SG_ordinary_mail+', '4PX-OZXBTH');

        $thCountriesNotDeliveryWithBattery = array(16,64,91,119,126,129,157,234,256,468,164);//哲盟这些国家不能发带电产品
        $thStatesNotDeliveryWithBattery = array( 'USA'=> 'GEORGIA' );//哲盟这些洲不能发带电产品
        $thCitiesNotDeliveryWithBattery = array( 'France'=>'PARIS' );//哲盟这些城市不能发带电产品

        switch( $smCode ) {
            case 'SZY-ETK':
            case 'SZY-EMS':
            case 'CJ-DGMG':
            case 'CJ-DGMP':
			case 'DGM-US':
            case 'HKPP':
            case 'HJPG':
            case 'WG-EMS':
            case 'WG-EUB':
            case 'WG-EUB-EBAY':
                if(in_array($smCode, array('CJ-DGMG','CJ-DGMP','DGM-US'))){
                    $countryInfo = Service_Country::getByField($countryId);
                    if(in_array($countryId, array(14,61,65,66,81,89,107,113,168,182,192,195,217,221,230,252))|| (($smCode == 'DGM-US') && $countryId == '253')){
                        if($batteryType !=2){
                            $allow['allow'] = false;
                            $allow['msg']   = '国家'.$countryInfo['country_name'].'渠道为'. $smCode .'只能发内置电池产品';
                        }
                    }else{
                        $allow['allow'] = false;
                        $allow['msg'] = '国家'.$countryInfo['country_name'].'渠道为'. $smCode .'限制运输带电产品';
                    }
                }else{
                    $allow['allow'] = false;
                    $allow['msg'] = '渠道'. $smCode .'限制运输带电产品';
                }
                break;
            case 'SZY-EUB':
                if( !in_array( $countryId ,array( 253, 41 ) ) ) {
                    $allow['allow'] = false;
                    $allow['msg'] = '渠道'. $smCode .'限制运输带电产品';
                }
                break;
            case '4PX-Singapo_SPack_IMAIR':
            case '4PX-SG_ordinary_mail+':
                if ( in_array( $countryId, array(89,115,130,71,220,190) ) ) {
                    $allow['allow'] = false;
                    $allow['msg'] = "此国家不能走含有电池";
                }else if($countryId=252&&$batteryType != 2){
                    $allow['allow'] = false;
                    $allow['msg'] = "此国家带电池产品的电池类型只能内置电池";
                }
                break;
            case '4PX-OZXBTH':
                if ( in_array( $countryId, array(252, 89, 115, 130, 71 ) ) ) {
                    $allow['allow'] = false;
                    $allow['msg'] = "此国家不能走含有电池";
                }
                break;
            case 'HKDHL':
                $countryInfo = Service_Country::getByField($countryId);
                $noBattery = array('AI','AW','AZ','XB','BI','CV','CF','TD','KM','CU','DJ','EG','GQ','ER','FK','FO','GF','GM','GE','GL','GW','KZ','KP','KV','KG','LS','LR','LY','MR','YT','MS','MZ','XN','NE','QA','SH','ST','SC','SL','SO','XS','SS','XY','XE','SD','SR','SZ','SY','TJ','TZ','TN','TC','UG','UZ','VG','YE','ZW','FM','MP','AS','MM');
                if(in_array( $countryInfo['country_code'], $noBattery ) ){
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为HKDHL时，国家".$countryInfo['country_name']."不允许发带电产品";
                }else{
                    if ( $batteryType != 1 && $batteryType != 2) {
                        $allow['allow'] = false;
                        $allow['msg'] = "渠道为HKDHL时，带电池产品的电池类型只能是配置和内置电池";
                    }
                }
                break;
            case 'DHL-TH':
                if( $batteryType != 2 ){
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为DHL-TH时，带电池产品的电池类型只能是内置电池";
                }
                if( in_array( $countryId, $thCountriesNotDeliveryWithBattery ) ) {
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为DHL-TH时，此国家不能发带电产品";
                } else if ( in_array( @$others['state'], $thStatesNotDeliveryWithBattery ) ) {
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为DHL-TH时，此州/区域不能发带电产品";
                } else if( in_array( @$others['city'], $thCitiesNotDeliveryWithBattery ) ) {
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为DHL-TH时，此城市不能发带电产品";
                }
                break;
            case "BH-BEAT";
                if(!in_array($batteryType, array('2','0'))){
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为BH-BEAT时，带电池产品的电池类型只能是内置或不带电";
                }
                break;
            case "BH-NLAT";
                if(!in_array($batteryType, array('2','0','1'))){
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为BH-NLAT时，带电池产品的电池类型只能是内置电池或配套电池或不带电产品";
                }
                break;
            case 'BH-AZAT-G';
                if(!in_array($batteryType, array('1','2'))){
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为BH-AZAT-G时，带电池产品的电池类型只能是内置或配套电池";
                }
            break;
            case 'SWPT':
            case 'BH-MMP':
            case 'BH-MMP1':
                if( $batteryType != 2 ){
                    $allow['allow'] = false;
                    $allow['msg'] = "渠道为BH-MMP/BH-MMP1/SWPT时，带电池产品的电池类型只能是内置电池";
                }
            break;
            case 'BH-POST-NL':
                if(!in_array($batteryType, array('1','2'))){
                    $allow['allow'] = false;
                    $allow['msg']   = "渠道为BH-POST-NL时，带电池产品的电池类型只能是内置电池或配套电池";
                }else{
                   if($batteryType == '1'){
                       $countryInfo = Service_Country::getByField($countryId);
                       $allowCountryCode = array('AT','BE','CZ','IT','SK','IE','DK','FR','HU','LU','ES','NL','NO','PL','PT','CH');
                       if(!in_array( $countryInfo['country_code'], $allowCountryCode ) ){
                           $allow['allow'] = false;
                           $allow['msg'] = "渠道为BH-POST-NL时，国家".$countryInfo['country_name']."不允许发配套电池产品";
                       }
                   }
                }
            break;
            case 'BH-SFEP':
            case 'BH-NLPOST-TH':
            case 'BH-USPS':
            case 'LYT-SMTGH-X':
            case 'LYT-USET-X':
                if( $batteryType != 2 ){
                    $allow['allow'] = false;
                    $allow['msg'] = '渠道为'.$smCode.'时，带电池产品的电池类型只能是内置电池';
                }
                break;
            break;    
        }
        return $allow;
    }

}
