<?php

class Service_AsnProccess
{
    protected $_orderCode = null;
    protected $_products = null;
    protected $_customerId = null;
    protected $_customerInfo = null;
    protected $_warehouseId = null;
    protected $_error;
    protected $_pro;
    protected $_receiving = array();
    protected $_date = '';

    public static function getAsnStatus()
    {
        $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('PendingAudit');//'待审核';
        $status[4] = Ec_Lang::getInstance()->getTranslate('Audited');//'已审核';
        $status[5] = Ec_Lang::getInstance()->getTranslate('onway');//'在途';
        $status[6] = Ec_Lang::getInstance()->getTranslate('ReceiptOf');//'收货中';
        $status[7] = Ec_Lang::getInstance()->getTranslate('ReceiptComplete');//'收货完成';
        return $status;
    }

    public static $itemStatus = array(
        0 => 'Awaiting',
        1 => 'Receiving',
        2 => 'Finished',
    );

    public static $AsnType = array(
        0 => 'Normal',
        1 => 'By Po',
        2 => 'Refund',
        3 => 'Reject',
        4 => 'Return',
    );

    public static function getAsnType()
    {
        $status[0] = Ec_Lang::getInstance()->getTranslate('Standard');//'标准';
        //$status[1] = Ec_Lang::getInstance()->getTranslate('OrdersReturns');//'订单退货';
        //$status[2] = Ec_Lang::getInstance()->getTranslate('SpecifyTheProductBackPieces');//'指定产品退件';
        //$status[3] = Ec_Lang::getInstance()->getTranslate('Transit');//'中转';
        return $status;
    }

    public static $applicationType = array(
        1 => 'avrived',
        2 => 'receive',
        3 => 'putaway',
    );

    //异常状态
    public static $underreviewStatus = array(
        0 => 'Normal', //无
        1 => 'Abnormal',
    );


    public function __construct($pro = 'BHR')
    {
        $this->setCustomer();
        $this->_pro = $pro;
        $this->_date = date('Y-m-d H:i:s');
    }

    private function setCustomer($customerId = '')
    {
        $customerService = new Service_Customer();
        if (!isset($this->_customerId) && $customerId == '') {
            $customerInfo = $customerService->getLoginInfo();
            $customerRow = $customerInfo->customer;
        } elseif ($customerId != '') {
            $customerRow = $customerService->getByField($customerId);
        }
        $this->_customerId = $customerRow['customer_id'];
        $this->_customerInfo = $customerRow;
    }

    /**
     * @param $order ASN ,$item ASN产品 ,$customerId 客户ID
     * @return array('ask' => 0, 'msg' => '','Error'=>array(array('errorCode'=>'','errorMessage')), 'ASNCode' => '');
     * @author william-fan
     * @todo 创建一条新的 ASN 信息 事务处理 (备货模式)
     */
    public function createTransaction($data, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        //exit('ffsss');
        $data['customerId'] = $customerId;
        $error = self::validate($data, $customerId);

        //var_dump($error);
        //exit('cccnnn');
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        //exit('fff00sssf');
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();

            $date = date('Y-m-d H:i:s');
            if (isset($data['ref_code']) && $data['ref_code'] != '') {
                $r = self::checkReferenceNo(array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
                if (!empty($r)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'));
                }
            }
            if ($customerId) {
                $this->setCustomer($customerId);
            }
            if ($this->_customerInfo['customer_status'] != 2) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('AccountIsNotActivated'));
            }
            if ($warehouseId) {
                $this->_warehouseId = $warehouseId;
            }

            $ASNCode = self::createCode();
            $receiving['receiving_code'] = $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            $receiving['warehouse_id'] = $warehouseId;
            $receiving['customer_id'] = $customerId;
            $receiving['customer_code'] = $this->_customerInfo['customer_code'];
            $receiving['receiving_type'] = isset($data['receiving_type']) ? $data['receiving_type'] : '0';
            $receiving['receiving_status'] = '1';
            $receiving['receiving_add_time'] = $date;
            $receiving['is_delivery'] = $data['is_delivery'];
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving ['trade_mode'] = $data ['trade_mode'];
            $receiving ['trans_mode'] = $data ['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];
            //$receiving['netweight']			= $data['netweight'];

            /* if ($data ['haveconta'] == '1') {
				$receiving ['haveconta'] = '1';
				$receiving ['conta_id'] = $data ['conta_id'];
				$receiving ['conta_model'] = $data ['conta_model'];
				$receiving ['conta_wt'] = $data ['conta_wt'];
			} else {
				$receiving ['haveconta'] = '0';
				$receiving ['conta_id'] = '';
				$receiving ['conta_model'] = '';
				$receiving ['conta_wt'] = '0';
			} */
            $receiving ['haveconta'] = '0';
            $receiving ['conta_id'] = '';
            $receiving ['conta_model'] = '';
            $receiving ['conta_wt'] = '0';

            $receiving ['receiving_description'] = $data ['instructions'];
            $receiving['receive_model_type'] = '0';
            if (!isset ($receiving ['receiving_type']) || $receiving ['receiving_type'] === '') {
                throw new Exception (Ec_Lang::getInstance()->getTranslate('ASNTypeIsEmpty'));
            }
            /*
			 * $receiving['receiving_status'] =
			 * isset($data['receiving_status'])?$data['receiving_status']:'0';
			 * $receiving['receiving_description'] = $data['instructions'];
			 * $receiving['receiving_add_time'] 	= $date;
			 * $receiving['refercence_form_id']	= $data['refercence_form_id'];
			 * $receiving['ie_port']				= $data['ie_port'];
			 * $receiving['form_type']				= $data['form_type'];
			 * $receiving['traf_name']				= $data['traf_name'];
			 * $receiving['wrap_type']				= $data['wrap_type'];
			 * $receiving['pack_no']				= $data['pack_no'];
			 * $receiving['traf_mode']				= $data['traf_mode'];
			 * $receiving['trade_mode'] 			= $data['trade_mode'];
			 * $receiving['trans_mode']			= $data['trans_mode'];
			 * $receiving['conta_id']				= $data['conta_id'];
			 * $receiving['conta_model']			= $data['conta_model'];
			 * $receiving['conta_wt']				= $data['conta_wt'];
			 */

            if ($warehouseId === '') {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehouseIsEmpty'));
            }
            $warehouse = Common_DataCache::getWareHouse();
            if (!isset($warehouse[$warehouseId])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist'));
            }

            if (!isset($receiving['customer_id']) || $receiving['customer_id'] == '') {
                $receiving['customer_id'] = $this->_customerId;
            }

            $receiving_id = Service_Receiving::add($receiving);
            /* echo $receiving_id;
            $DB->rollBack();
            exit; */
            //receiving_detail

            $session = new Zend_Session_Namespace('customerAuth');
            $sessionData = $session->data;
            $customerCode = $sessionData['code'];

            $product_sku = $data['product_sku'];
            $sku = $data['sku'];
            $haveDeclare = false;
            if (isset($data['declared_value'])) {
                $haveDeclare = true;
                $declare = $data['declared_value'];
            }
            /*if(isset($data['is_new_goods_id'])){
                $haveNewGoodId=true;
                $isNewGoodsId =$data['is_new_goods_id'];
            }*/
            if (isset($data['hs_code'])) {
                $haveHsCode = true;
                $HsCode = $data['hs_code'];
            }
            if (isset($data['hs_goods_name'])) {
                $haveHsGoodsName = true;
                $HsGoodsName = $data['hs_goods_name'];
            }
            if (isset($data['g_model'])) {
                $haveGmodel = true;
                $Gmodel = $data['g_model'];
            }
            foreach ($product_sku as $k => $v) {
                $productList = Service_Product::getByCondition(array('product_sku' => $v, 'customer_code' => $this->_customerInfo['customer_code']), "*");
                //$product = Service_Product::getByField($v,'product_sku');
                $product = $productList[0];

                if ($haveDeclare) {
                    $declare_vale = $declare[$k];
                } else {
                    $declare_vale = $product['product_declared_value'];
                }
                $hs_code = "";
                if ($haveHsCode) {
                    $hs_code = $HsCode[$k];
                    if ($hs_code != $product['hs_code']) throw new Exception("sku[" . $v . "]的海关编码[" . $hs_code . "]与原海关编码[" . $product['hs_code'] . "]不一致!");
                }
                $hs_goods_name = "";
                if ($haveHsGoodsName) {
                    $hs_goods_name = $HsGoodsName[$k];
                }
                $g_model = "";
                if ($haveGmodel) {
                    $g_model = $Gmodel[$k];
                }
                $hemList = Service_HsElementMap::getByCondition(array('product_id' => $product['product_id']), 'hem_detail');
                $elements = array();
                foreach ($hemList as $hemRow) {
                    if ($hemRow['hem_detail'] != "")
                        $elements[] = $hemRow['hem_detail'];
                }
                $existGmodel = implode('|', $elements);
                $is_new_goods_id = 0;
                $goods_id = $product['goods_id'];
                if ($haveHsCode && $haveHsGoodsName && $haveGmodel) {
                    if (($hs_code != "" && $hs_code != $product['hs_code']) || ($hs_goods_name != "" && $hs_goods_name != $product['hs_goods_name']) || ($g_model != "" && $existGmodel != $g_model)) {
                        $con = array(
                            'product_id' => $k,
                            'hs_code' => $hs_code,
                            'hs_goods_name' => $hs_goods_name,
                            'g_model' => $g_model
                        );
                        $exGoods = Service_Goods::getByCondition($con, "*");
                        if (empty($exGoods)) {
                            $is_new_goods_id = 1;
                            $goods_id = Service_CustomerProcess::generateGoodsId($product['customer_id'], $product['has_invoice']);
                        } else {
                            $goods_id = $exGoods[0]['goods_id'];
                        }
                    }
                }
                $receivingDetail = array(
                    'receiving_id' => $receiving_id,
                    'receiving_code' => $ASNCode,
                    'rd_status' => '0',
                    'product_id' => $product['product_id'],
                    'product_barcode' => $product['product_barcode'],
                    'op_declared_value' => trim($declare_vale),
                    'rd_receiving_qty' => trim($sku[$k]),
                    'rd_add_time' => $date,
                    'rd_goods_id' => $goods_id,
                );
                if ($is_new_goods_id) {
                    $goodsRow = array(
                        'product_id' => $k,
                        'goods_id' => $goods_id,
                        'hs_code' => $hs_code,
                        'hs_goods_name' => $hs_goods_name,
                        'g_model' => $g_model
                    );
                    Service_Goods::add($goodsRow);
                }
                $receivingDetailArr[] = $receivingDetail;
                if (!Service_ReceivingDetail::add($receivingDetail)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
                }

            }

            $note = 'create';
            foreach ($receivingDetailArr as $val) {
                $productRow = Service_Product::getByField($val['product_id'], 'product_id', array('product_sku'));
                $note .= ' sku:' . $productRow['product_sku'] . ' quantity:' . $val['rd_receiving_qty'] . ' ';
            }
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'user_id' => '-1',
                'customer_code' => $this->_customerInfo['customer_code'],
                'rl_note' => $note,
                'rl_add_time' => $date,
                'rl_status_from' => '1',
                'rl_status_to' => '1',
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            $result['ask'] = '1';
            $result['msg'] = "收货订单[{$ASNCode}]创建成功."; //'ASN创建成功';
            $result['ASNCode'] = $ASNCode;
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    public function createPoAsn($data, $insertId, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        //exit('ffsss');
        $supllierSession = Service_Customer::getLoginInfo();
        $supllier = $supllierSession->data;
        $data['customerId'] = $customerId;
        $error = self::validatePoAsn($data, $customerId);
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        //exit('fff00sssf');
        try {
            $date = date('Y-m-d H:i:s');
            if (isset($data['ref_code']) && $data['ref_code'] != '') {
                $r = self::checkReferenceNo(array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
                if (!empty($r)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'));
                }
            }

            if (empty($customerId)) {
                throw new Exception('客户ID不能为空');
            } else {
                $this->setCustomer($customerId);
            }

            if ($this->_customerInfo['customer_status'] != 2) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('AccountIsNotActivated'));
            }
            if ($warehouseId) {
                $this->_warehouseId = $warehouseId;
            }
            $customerInfo = Service_Customer::getByField($customerId);
            $ASNCode = self::createCode();
            $receiving['receiving_code'] = $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            $receiving['warehouse_id'] = $warehouseId;
            $receiving['customer_id'] = $customerId;
            $receiving['customer_code'] = $customerInfo['customer_code'];
            $receiving['receiving_type'] = isset($data['receiving_type']) ? $data['receiving_type'] : '0';
            $receiving['receiving_status'] = '3';
            $receiving['receiving_add_time'] = $date;
            $receiving['is_delivery'] = $data['is_delivery'];
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving ['trade_mode'] = $data ['trade_mode'];
            $receiving ['trans_mode'] = $data ['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];
            //$receiving['netweight']			= $data['netweight'];

            /* if ($data ['haveconta'] == '1') {
				$receiving ['haveconta'] = '1';
				$receiving ['conta_id'] = $data ['conta_id'];
				$receiving ['conta_model'] = $data ['conta_model'];
				$receiving ['conta_wt'] = $data ['conta_wt'];
			} else {
				$receiving ['haveconta'] = '0';
				$receiving ['conta_id'] = '';
				$receiving ['conta_model'] = '';
				$receiving ['conta_wt'] = '0';
			} */
            $receiving ['haveconta'] = '0';
            $receiving ['conta_id'] = '';
            $receiving ['conta_model'] = '';
            $receiving ['conta_wt'] = '0';
            $receiving['supplier_id'] = $supllier['id'];
            $receiving ['receiving_description'] = $data ['instructions'];
            $receiving['receive_model_type'] = '0';
            if (!isset ($receiving ['receiving_type']) || $receiving ['receiving_type'] === '') {
                throw new Exception (Ec_Lang::getInstance()->getTranslate('ASNTypeIsEmpty'));
            }
            /*
			 * $receiving['receiving_status'] =
			 * isset($data['receiving_status'])?$data['receiving_status']:'0';
			 * $receiving['receiving_description'] = $data['instructions'];
			 * $receiving['receiving_add_time'] 	= $date;
			 * $receiving['refercence_form_id']	= $data['refercence_form_id'];
			 * $receiving['ie_port']				= $data['ie_port'];
			 * $receiving['form_type']				= $data['form_type'];
			 * $receiving['traf_name']				= $data['traf_name'];
			 * $receiving['wrap_type']				= $data['wrap_type'];
			 * $receiving['pack_no']				= $data['pack_no'];
			 * $receiving['traf_mode']				= $data['traf_mode'];
			 * $receiving['trade_mode'] 			= $data['trade_mode'];
			 * $receiving['trans_mode']			= $data['trans_mode'];
			 * $receiving['conta_id']				= $data['conta_id'];
			 * $receiving['conta_model']			= $data['conta_model'];
			 * $receiving['conta_wt']				= $data['conta_wt'];
			 */

            if ($warehouseId === '') {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehouseIsEmpty'));
            }
            $warehouse = Common_DataCache::getWareHouse();
            if (!isset($warehouse[$warehouseId])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist'));
            }
            $receiving_id = Service_Receiving::add($receiving);
            $product_sku = $data['product_sku'];
            $haveDeclare = false;
            if (isset($data['declared_value'])) {
                $haveDeclare = true;
                $declare = $data['declared_value'];
            }
            foreach ($product_sku as $k => $v) {
                $productList = Service_Product::getByCondition(array('product_sku' => $v, 'customer_code' => $customerInfo['customer_code']), "*");
                //$product = Service_Product::getByField($v,'product_sku');
                $product = $productList[0];

                if ($haveDeclare) {
                    $declare_vale = $declare[$k];
                } else {
                    $declare_vale = $product['product_declared_value'];
                }
                $receivingDetail = array(
                    'receiving_id' => $receiving_id,
                    'receiving_code' => $ASNCode,
                    'rd_status' => '0',
                    'product_id' => $product['product_id'],
                    'product_barcode' => $product['product_barcode'],
                    'op_declared_value' => $product['product_declared_value'],
                    'rd_receiving_qty' => $data['num'][$k],
                    'rd_add_time' => $date
                );
                $receivingDetailArr[] = $receivingDetail;
                if (!Service_ReceivingDetail::add($receivingDetail)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
                }

            }

            $note = 'create';
            foreach ($receivingDetailArr as $val) {
                $productRow = Service_Product::getByField($val['product_id'], 'product_id', array('product_sku'));
                $note .= ' sku:' . $productRow['product_sku'] . ' quantity:' . $val['rd_receiving_qty'] . ' ';
            }
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'user_id' => '-1',
                'customer_code' => $customerInfo['customer_code'],
                'rl_note' => $note,
                'rl_add_time' => $date,
                'rl_status_from' => '1',
                'rl_status_to' => '1',
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            if ($receiving['trade_mode'] == "9610" || $receiving['trade_mode'] == "1210") {

                $goodsIdArr = Service_ReceivingDetail::getGoodsId($receiving['receiving_code']);
                $sumNetWeight = Service_ReceivingDetail::sumNetWeight($receiving['receiving_code']);

                $goodsIdArr = array_chunk($goodsIdArr, 35);
                $subIndex = 1;
                $gross_wt = ($receiving['roughweight'] - $sumNetWeight) / count($goodsIdArr);
                foreach ($goodsIdArr as $gk => $gv) {
                    if ($subIndex < 10) {
                        $sub_receiving_code = $receiving['receiving_code'] . "-0" . $subIndex;
                    } else {
                        $sub_receiving_code = $receiving['receiving_code'] . "-" . $subIndex;
                    }
                    $subIndex++;
                    $receivingXml = array(
                        'receiving_code' => $receiving['receiving_code'],
                        'sub_receiving_code' => $sub_receiving_code,
                        'gross_wt' => '0',
                        'net_wt' => '0',
                        'pack_no' => '0',
                        'refercence_form_id' => '',
                        'rx_add_time' => date("Y-m-d H:i:s"),
                        'receiving_xml_status' => '3',
                    );
                    Service_ReceivingXml::add($receivingXml);
                    $RXdbObj = new Table_ReceivingXml();
                    $rxId = $RXdbObj->getAdapter()->lastInsertId();
                    $net_wt = 0;
                    $pack_no = 0;
                    $G_NO_index = 1;
                    foreach ($gv as $goods_id) {

                        $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id' => $goods_id, 'receiving_code' => $receiving['receiving_code']));

                        $productRow = Service_Product::getByField($productList[0]['product_id'], 'product_id', "*");
                        $currencyRow = Service_Currency::getByField($productRow['currency_code'], 'currency_code', "*");
                        $receivingXmlDetail = array(
                            'rx_id' => $rxId,
                            'from_id' => $receiving['receiving_code'],
                            'sub_receiving_code' => $sub_receiving_code,
                            'g_no' => $G_NO_index,
                            'goods_id' => $productList[0]['goods_id'],
                            'merger_g_no' => $G_NO_index,
                            'code_ts' => $productList[0]['hs_code'],
                            'g_name_cn' => $productList[0]['hs_goods_name'],
                            //'decl_price'=>"",
                            'curr' => $currencyRow['currency_hs_code'],
                            'qty_1' => 0,
                            'unit_1' => '',
                            'qty_2' => '',
                            'unit_2' => '',
                        );

                        $g_qty = 0;
                        $decl_total = 0;
                        $decl_price = 0;
                        foreach ($productList as $p) {
                            if ($receiving['receive_model_type'] == "1") {
                                $quantity = $p['op_quantity'];
                                $g_qty += $p['op_quantity'];
                            } else {
                                $quantity = $p['rd_receiving_qty'];
                                $g_qty += $p['rd_receiving_qty'];
                            }

                            $hemList = Service_HsElementMap::getByCondition(array('product_id' => $p['product_id']), 'hem_detail');
                            $elements = array();

                            foreach ($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                            $receivingXmlDetail['g_model'] = implode('|', $elements);
                            $hs_uom_map = Service_HsUomMap::getByField($p['product_id'], 'product_id', "*");
                            $quantitylaw1 = isset($hs_uom_map['hum_quantity_law']) ? $hs_uom_map['hum_quantity_law'] : '0';
                            $receivingXmlDetail['qty_1'] += $quantitylaw1 * $quantity;
                            $quantitylaw2 = isset($hs_uom_map['hum_quantity_second']) ? $hs_uom_map['hum_quantity_second'] : "0";
                            $receivingXmlDetail['qty_2'] += $quantitylaw2 * $quantity;
                            if (!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'], 'hu_id', "*");
                            $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law']) ? $hs_uom['pu_code_law'] : "";
                            $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second']) ? $hs_uom['pu_code_second'] : "";
                            $product = Service_Product::getByField($p['product_id'], "product_id", "*");
                            $decl_total += $product['product_declared_value'] * $quantity;
                            $receivingXmlDetail['g_unit'] = $product['pu_code'];

                        }
                        $pack_no += $g_qty;

                        $ntWeight = Service_ReceivingDetail::calNetWeightByCondition(array('goods_id' => $goods_id, 'receiving_code' => $receiving['receiving_code']));

                        $net_wt += $ntWeight;
                        $decl_price = sprintf("%.4f", $decl_total / $g_qty);
                        $receivingXmlDetail['decl_price'] = $decl_price;
                        $receivingXmlDetail['g_qty'] = $g_qty;
                        $receivingXmlDetail['decl_total'] = $decl_total;
                        Service_ReceivingXmlDetail::add($receivingXmlDetail);
                        $G_NO_index++;
                    }
                    $updateReceivingXml = array(
                        'gross_wt' => $net_wt + $gross_wt,
                        'net_wt' => $net_wt,
                        'pack_no' => $pack_no,
                    );
                    Service_ReceivingXml::update($updateReceivingXml, $sub_receiving_code, 'sub_receiving_code');

                    $aMessage['fmt_code'] = 'MRK';
                    $aMessage['fmt_type'] = 'BSG011';
                    $aMessage['refercence_no'] = $sub_receiving_code;
                    $aMessage['fml_status'] = 1;
                    $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                    Service_FtpMessageSendlist::add($aMessage);

                }
            }
            foreach ($insertId as $s => $poTrakcingId) {
                Service_PoOrderTracking::update(array('is_created_asn' => 1, 'receiving_id' => $receiving_id), $poTrakcingId);
            }
            if ($receiving['is_delivery'] == '1') {
                //提货的ASN要提货费
                //冻结提货费
                $objOtherCalculte = new Common_CalculateOtherFee();
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code' => $ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                $otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
                $otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];

                if ($otherfee_tihuo['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult = $balanceProcess->freezeASNFee($ASNCode, $customerInfo['customer_id'], $receiving);
                    if ($feeResult !== true) {
                        throw new Exception($feeResult);
                    }
                }
            }

            $law_weight = Service_ReceivingDetail::sumLawWeight($ASNCode);

            if ($law_weight > $receiving['roughweight']) {
                throw new Exception('法定单位为千克的SKU的总重量大于ASN毛重，请修改SKU的法定单位重量');
            }
            if ($customerInfo['customer_platform'] == "FX") {
                $ftpMessageSendlistRow = array(
                    'fmt_code' => 'ASNSH-TO-FX',
                    'fmt_type' => 'FXSYS',
                    'refercence_no' => $ASNCode,
                    'fml_status' => '1',
                    'fml_add_time' => date("Y-m-d H:i:s"),
                );
                Service_FtpMessageSendlist::add($ftpMessageSendlistRow);
                $ftpMessageSendlistRow = array(
                    'fmt_code' => 'ASNWCSH-TO-FX',
                    'fmt_type' => 'FXSYS',
                    'refercence_no' => $ASNCode,
                    'fml_status' => '1',
                    'fml_add_time' => date("Y-m-d H:i:s"),
                );
                Service_FtpMessageSendlist::add($ftpMessageSendlistRow);
            }
            $result['ask'] = '1';
            $result['msg'] = "收货订单[{$ASNCode}]创建成功."; //'ASN创建成功';
            $result['ASNCode'] = $ASNCode;
            //$DB->rollBack();
        } catch (Exception $e) {
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    /**
     * @author william-fan
     * @todo 创建集货货模式的ASN
     */
    public function createjihuoTransaction($data, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        //exit('ffsss');

        //exit('fff00sssf');
        $session = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $error = self::validate($data, $customerId);
            $errorOrder = self::validOrder($data);
            $errorAll = array_merge($error, $errorOrder['error']);
            if (!empty($errorAll)) {
                $result['error'] = $errorAll;
                $result['detail'] = $errorOrder['detail'];
                throw new Exception("错误");
                //return $result;
            }
            $date = date('Y-m-d H:i:s');

            if (isset($data['ref_code']) && $data['ref_code'] != '') {
                $r = self::checkReferenceNo(array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
                if (!empty($r)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'));
                }
            }
            if ($customerId) {
                $this->setCustomer($customerId);
            }
            if ($this->_customerInfo['customer_status'] != 2) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('AccountIsNotActivated'));
            }
            if ($warehouseId) {
                $this->_warehouseId = $warehouseId;
            }

            $ASNCode = self::createCode();
            $receiving['receiving_code'] = $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            $receiving['warehouse_id'] = $warehouseId;
            $receiving['customer_id'] = $customerId;
            $receiving['customer_code'] = $this->_customerInfo['customer_code'];
            $receiving['receiving_type'] = isset($data['receiving_type']) ? $data['receiving_type'] : '0';
            $receiving['receiving_status'] = '1';
            $receiving['receiving_add_time'] = $date;
            $receiving['receiving_update_time'] = date("Y-m-d H:i:s");
            $receiving['is_delivery'] = $data['is_delivery'];
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving ['trade_mode'] = $data ['trade_mode'];
            $receiving ['trans_mode'] = $data ['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];
            //$receiving['netweight']			= $data['netweight'];

            /* if ($data ['haveconta'] == '1') {
    			$receiving ['haveconta'] = '1';
    			$receiving ['conta_id'] = $data ['conta_id'];
    			$receiving ['conta_model'] = $data ['conta_model'];
    			$receiving ['conta_wt'] = $data ['conta_wt'];
    		} else {
    			$receiving ['haveconta'] = '0';
    			$receiving ['conta_id'] = '';
    			$receiving ['conta_model'] = '';
    			$receiving ['conta_wt'] = '0';
    		} */
            $receiving ['haveconta'] = '0';
            $receiving ['conta_id'] = '';
            $receiving ['conta_model'] = '';
            $receiving ['conta_wt'] = '0';

            $receiving['receive_model_type'] = '1';
            $receiving ['receiving_description'] = $data ['instructions'];

            if (!isset ($receiving ['receiving_type']) || $receiving ['receiving_type'] === '') {
                throw new Exception (Ec_Lang::getInstance()->getTranslate('ASNTypeIsEmpty'));
            }

            if ($warehouseId === '') {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehouseIsEmpty'));
            }
            $warehouse = Common_DataCache::getWareHouse();
            if (!isset($warehouse[$warehouseId])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist'));
            }

            if (!isset($receiving['customer_id']) || $receiving['customer_id'] == '') {
                $receiving['customer_id'] = $this->_customerId;
            }

            $receiving_id = Service_Receiving::add($receiving);
            /* echo $receiving_id;
    		 $DB->rollBack();
    		exit; */
            //receiving_detail
            //增加到receiving_order_detail表中 asn和订单关联表
            /*$rab = array(
                'receiving_id'=>$receiving_id,
                'receiving_code'=>$ASNCode,
                'onway_time'=>date("Y-m-d H:i:s")
            );
            Service_ReceivingAttribute::add($rab);*/

            $asnOrders = $data['asn_order'];
            //$sku =  $data['sku'];
            foreach ($asnOrders as $keyo => $orderCode) {
                //$product = Service_Product::getByField($v,'product_sku');
                $orderInfo = Service_Orders::getByField($orderCode, 'order_code');

                $receiving_order_detail = array(
                    'receiving_id' => $receiving_id,
                    'receiving_code' => $ASNCode,
                    'rd_status' => '0',
                    'order_code' => $orderCode,
                    'rd_add_time' => $date
                );
                $receivingOrderDetailArr[] = $receiving_order_detail;
                if (!Service_ReceivingOrderDetail::add($receiving_order_detail)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
                }
                //修改订单到已提交状态
                $orderRow = array(
                    'order_status' => '4',
                    'update_time' => $date
                );
                Service_Orders::update($orderRow, $orderCode, 'order_code');
                $ol_type = 1;
                if ($orderInfo['order_status'] != 4) {
                    $ol_type = 0;
                }
                $logRow = array(
                    'order_id' => $orderInfo['order_id'],
                    'order_code' => $orderInfo['order_code'],
                    'ol_type' => $ol_type,
                    'order_status_from' => $orderInfo['order_status'],
                    'order_status_to' => 4,
                    'ol_add_time' => date('Y-m-d H:i:s'),
                    'user_id' => '-1',
                    'account_id' => Service_Login::getUserId(),
                    'ol_ip' => Common_Common::getIP()
                );
                Service_OrderLog::add($logRow);

                $w = Service_Warehouse::getByField($orderInfo['warehouse_id'], 'warehouse_id', '*');
                $shipOrderTracking = array(
                    'order_code' => $orderInfo['order_code'],
                    'sot_location' => "客户仓库",
                    'sot_add_time' => date("Y-m-d H:i:s"),
                    'warehouse_id' => $orderInfo['warehouse_id'],
                    'sot_description' => '集货ASN新建成功,集货订单自动提交',
                    'sot_type' => '0',
                    'sot_time_offset' => '',
                    'tracking_number' => $orderInfo['order_code'],
                    'ref_tracking_number' => '',
                    'status_desc' => '已提交',
                    'user_id' => -1 * $sessionData['id']
                );
                Service_ShipOrderTracking::add($shipOrderTracking);

                $orderOperationTime = array(
                    'order_id' => $orderInfo['order_id'],
                    'order_code' => $orderCode,
                    'submit_time' => date("Y-m-d H:i:s"),
                    'submit_user_id' => -1 * $sessionData['id']
                );
                Service_OrderOperationTime::update($orderOperationTime, $orderCode, "order_code");

                //预扣费
                $balanceProcess = new Service_CustomerBalanceProcess();
                $feeResult = $balanceProcess->freezeFee($orderCode, $customerId);
                if ($feeResult !== true) throw new Exception($feeResult);
            }

            $note = 'create ASN';
            /* foreach ($receivingOrderDetailArr as $val) {
    			$productRow = Service_Product::getByField($val['product_id'], 'product_id', array('product_sku'));
    			$note .= ' sku:' . $productRow['product_sku'] . ' quantity:' . $val['rd_receiving_qty'] . ' ';
    		} */
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'user_id' => '-1',
                'customer_code' => $this->_customerInfo['customer_code'],
                'rl_note' => $note,
                'rl_add_time' => $date,
                'rl_status_from' => '1',
                'rl_status_to' => '1',
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            $result['ask'] = '1';
            $result['msg'] = "收货单号:{$ASNCode}创建成功"; //Ec_Lang::getInstance()->getTranslate('ASNCreatingSuccess'); //'ASN创建成功';
            $result['ASNCode'] = $ASNCode;
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    /**
     * @return array('ask'=>0,'Error'=>array());
     * @todo 用于添加asn详情
     * @author william-fan
     */
    public function createAsnDetail($asnCode = '', $itemArr = array())
    {
        $return = array('ask' => 0, 'Error' => array());
        $addItem = array(
            'receiving_code' => $asnCode,
            'created' => date('Y-m-d H:i:s'),
            'status' => 0
        );
        //print_r($itemArr);

        $productIds = $errorArr = array();
        foreach ($itemArr as $key => $val) {
            if (!in_array($val['product_id'], $productIds)) {
                $productIds[] = $val['product_id'];
            } else {
                $errorArr[] = 'No.' . ($key + 1) . ' 产品存在.';
                continue;
            }
            $result = $this->checkProductStatus($val['product_id']);
            //var_dump($result.'ss');
            if (!isset($result['productInfo']['product_sku'])) {
                $errorArr[] = array(
                    'errorCode' => 20038,
                    'errorMessage' => 'No.' . ($key + 1) . ' product exists.'
                );
            }
            if (isset($result['productInfo']['product_type']) && !in_array($result['productInfo']['product_type'], array('0', '2'))) {
                $errorArr[] = array(
                    'errorCode' => 20009,
                    'errorMessage' => 'SKU:' . $result['productInfo']['product_sku'] . ' type error.'
                );
            }
            if ($result['ask'] == '0') {
                $errorArr[] = array(
                    'errorCode' => 20008,
                    'errorMessage' => 'Item ' . $key . ' can not be found.'
                );
                continue;
            }
            if ($result['ask'] == '2') {
                $errorArr[] = array(
                    'errorCode' => 20010,
                    'errorMessage' => 'SKU: ' . $result['productInfo']['product_sku'] . ' can not be found.'
                );
                continue;
            }
            $addItem['po'] = isset($val['po']) ? $val['po'] : '';
            // $addItem['po_line'] = isset($val['po_line']) ? $val['po_line'] : '';
            //po
            if (!empty($addItem['po'])) {
                $poRows = Merchant_Service_PurchaseOrder::getByCondition(array('po_code' => $addItem['po'], 'customer_id' => $this->_customerId), '*');
                if (empty($poRows)) {
                    $errorArr[] = array(
                        'errorCode' => 20011,
                        'errorMessage' => 'POCode: ' . $addItem['po'] . ' can not be found.'
                    );
                } else {
                    $poProductRows = Merchant_Service_PurchaseOrderProduct::getByCondition(array('po_id' => $poRows[0]['po_id'], 'product_id' => $val['product_id']), '*');
                    if (empty($poProductRows)) {
                        $errorArr[] = array(
                            'errorCode' => 20011,
                            'errorMessage' => 'POCode: ' . $addItem['po'] . ' The product does not match. ' . $result['productInfo']['product_sku']
                        );
                    }
                }

                /*
    			 if (empty($addItem['po_line'])) {
    			$errorArr[] = array(
    					'errorCode' => 20012,
    					'errorMessage' => 'POLine: ' . $addItem['po_line'] . ' can not be empty.'
    			);
    			}
    			*/
            }
            if (!empty($errorArr)) {
                continue;
            }
            $addItem['product_id'] = $val['product_id'];
            $addItem['order_qty'] = $val['order_qty'];
            $addItem['attribute'] = isset($val['attribute']) ? $val['attribute'] : '';
            Service_ReceivingDetail::add($addItem);
        }
        if (!empty($errorArr)) {
            $return['Error'] = $errorArr;
        } else {
            $return['ask'] = 1;
        }
        return $return;
    }

    /*
    * 更新 ASN 信息（备货模式）
    * @param $order ASN ,$item ASN产品 ,$customerId 客户ID
    * @return array('ask' => 0, 'msg' => '', 'Error'=>array(),'ASNCode' => '');
    */
    public function updateTransaction($data, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        $data['customerId'] = $customerId;
        $error = self::validate($data, $customerId);
        //var_dump($error);
        //exit('cccnnn');
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        //print_r($data);var_dump($data['haveconta']=='1');exit;
        $date = date('Y-m-d H:i:s');
        try {
            if (isset($order['ref_id'])) {
                unset($order['ref_id']);
            }
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            //var_dump($customerId);

            if ($customerId) {
                $this->setCustomer($customerId);
            }
            //var_dump($this->_customerInfo);
            $ASNCode = $data['ASNCode'];
            if (empty($ASNCode)) {
                throw new Exception('ASNCode ' . Ec_Lang::getInstance()->getTranslate('DoesNotExist'));
            }
            $asnRows = Service_Receiving::getByCondition(array('receiving_code' => $ASNCode, 'customer_id' => $this->_customerId), '*');
            $this->_receiving = $asnRows[0];
            $this->_warehouseId = $asnRows[0]['warehouse_id'];
            if (empty($asnRows)) {
                throw new Exception('ASNCode:' . $ASNCode . ' can not be found.', 20013);
            }
            $ASNRow = $asnRows[0];
            if (!in_array($ASNRow['receiving_status'], array('1')) || (isset($order['receiving_status']) && !in_array($ASNRow['receiving_status'], array('0', '1')))) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('CanNotBeModified') . ",ASNCode:" . $ASNCode . " " . Ec_Lang::getInstance()->getTranslate('StateDoesNotAllow'));
            }
            if (isset($data['warehouse_id']) && $data['warehouse_id'] == '') {
                throw new Exception("AsnCode:" . Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist') . '.', 20007);
            }

            $warehouseAll = Common_DataCache::getWareHouse();
            if (isset($order['warehouse_id']) && !isset($warehouseAll[$order['warehouse_id']])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist') . ".");
            }

            $order['modified'] = $date;

            //$receiving['receiving_code']	= $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            //$receiving['warehouse_id']		= $warehouseId;
            //$receiving['customer_id']		= $customerId;
            //$receiving['customer_code'] 	= $this->_customerInfo['customer_code'];
            //$receiving['receiving_type']	= isset($data['receiving_type'])?$data['receiving_type']:'0';
            //$receiving['receiving_add_time']= $date;
            $receiving['receiving_update_time'] = $date;
            $receiving['is_delivery'] = $data['is_delivery'];

            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving['trade_mode'] = $data['trade_mode'];
            $receiving['trans_mode'] = $data['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];
            $receiving['netweight'] = $data['netweight'];
            if ($data['haveconta'] == '1') {
                $receiving['haveconta'] = '1';
                $receiving['conta_id'] = $data['conta_id'];
                $receiving['conta_model'] = $data['conta_model'];
                $receiving['conta_wt'] = $data['conta_wt'];
            } else {
                $receiving['haveconta'] = '0';
                $receiving['conta_id'] = '';
                $receiving['conta_model'] = '';
                $receiving['conta_wt'] = '0';
            }
            $receiving['receiving_description'] = $data['instructions'];
            $receiving['receiving_update_time'] = date("Y-m-d H:i:s");

            Service_Receiving::update($receiving, $ASNCode, 'receiving_code');
            $note = 'update';

            $session = new Zend_Session_Namespace('customerAuth');
            $sessionData = $session->data;
            $customerCode = $sessionData['code'];

            if (isset($data['product_sku'])) {
                $product_sku = $data['product_sku'];
                $sku = $data['sku'];

                $haveDeclare = false;
                if (isset($data['declared_value'])) {
                    $haveDeclare = true;
                    $declare = $data['declared_value'];
                }
                Service_ReceivingDetail::delete($ASNCode, 'receiving_code');
                foreach ($product_sku as $k => $v) {
                    //$product = Service_Product::getByField($v,'product_sku');
                    $productList = Service_Product::getByCondition(array('product_sku' => $v, 'customer_code' => $customerCode), "*");
                    //$product = Service_Product::getByField($v,'product_sku');
                    $product = $productList[0];

                    if ($haveDeclare) {
                        $declare_vale = $declare[$k];
                    } else {
                        $declare_vale = $product['product_declared_value'];
                    }
                    $receivingDetail = array(
                        'receiving_id' => $ASNRow['receiving_id'],
                        'receiving_code' => $ASNCode,
                        'rd_status' => '0',
                        'product_id' => $product['product_id'],
                        'product_barcode' => $product['product_barcode'],
                        'op_declared_value' => trim($declare_vale),
                        'rd_receiving_qty' => trim($sku[$k]),
                        'rd_add_time' => $date
                    );
                    $receivingDetailArr[] = $receivingDetail;
                    if (!Service_ReceivingDetail::add($receivingDetail)) {
                        throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
                    }
                }
                foreach ($receivingDetailArr as $val) {
                    $productRow = Service_Product::getByField($val['product_id'], 'product_id', array('product_sku'));
                    $note .= ' sku:' . $productRow['product_sku'] . ' quantity:' . $val['rd_receiving_qty'] . ' ';
                }
                $ASNLog = array(
                    'receiving_id' => $ASNRow['receiving_id'],
                    'receiving_code' => $ASNCode,
                    'user_id' => '-1',
                    'customer_code' => $this->_customerInfo['customer_code'],
                    'rl_note' => $note,
                    'rl_status_from' => $ASNRow['receiving_status'],
                    'rl_status_to' => $ASNRow['receiving_status'],
                    //'rl_add_time'=>date("Y-m-d H:i:s"),
                    //'rl_ip'=>Common_Common::getIP()
                );
                //print_r($ASNLog);
                self::createAsnLog($ASNLog);
            }
            //$DB->rollBack();
            $DB->commit();
            return array('ask' => 1, 'msg' => "收货订单[{$ASNCode}]" . Ec_Lang::getInstance()->getTranslate('update') . Ec_Lang::getInstance()->getTranslate('success') . '.', 'error' => array(), 'ASNCode' => $ASNCode);
        } catch (Zend_Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getInternalError();
            $result['msg'] = $e->getInternalError();
            return $result;
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /**
     * @author william-fan
     * @todo 用于集货模式的ASN更新
     */
    public function updatejihuoTransaction($data, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        $error = self::validate($data, $customerId);
        //var_dump($error);
        //exit('cccnnn');
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        //print_r($data);var_dump($data['haveconta']=='1');exit;
        $date = date('Y-m-d H:i:s');
        try {
            if (isset($order['ref_id'])) {
                unset($order['ref_id']);
            }
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            //var_dump($customerId);

            if ($customerId) {
                $this->setCustomer($customerId);
            }
            //var_dump($this->_customerInfo);
            $ASNCode = $data['ASNCode'];
            if (empty($ASNCode)) {
                throw new Exception('ASNCode ' . Ec_Lang::getInstance()->getTranslate('DoesNotExist'));
            }
            $asnRows = Service_Receiving::getByCondition(array('receiving_code' => $ASNCode, 'customer_id' => $this->_customerId), '*');
            $this->_receiving = $asnRows[0];
            $this->_warehouseId = $asnRows[0]['warehouse_id'];
            if (empty($asnRows)) {
                throw new Exception('ASNCode:' . $ASNCode . ' can not be found.', 20013);
            }
            $ASNRow = $asnRows[0];
            if (!in_array($ASNRow['receiving_status'], array('1')) || (isset($order['receiving_status']) && !in_array($ASNRow['receiving_status'], array('0', '1')))) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('CanNotBeModified') . ",ASNCode:" . $ASNCode . " " . Ec_Lang::getInstance()->getTranslate('StateDoesNotAllow'));
            }
            if (isset($data['warehouse_id']) && $data['warehouse_id'] == '') {
                throw new Exception("AsnCode:" . Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist') . '.', 20007);
            }

            $warehouseAll = Common_DataCache::getWareHouse();
            if (isset($order['warehouse_id']) && !isset($warehouseAll[$order['warehouse_id']])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist') . ".");
            }

            $order['modified'] = $date;

            //$receiving['receiving_code']	= $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            //$receiving['warehouse_id']		= $warehouseId;
            //$receiving['customer_id']		= $customerId;
            //$receiving['customer_code'] 	= $this->_customerInfo['customer_code'];
            //$receiving['receiving_type']	= isset($data['receiving_type'])?$data['receiving_type']:'0';
            //$receiving['receiving_add_time']= $date;
            $receiving['receiving_update_time'] = $date;
            $receiving['is_delivery'] = $data['is_delivery'];
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving['trade_mode'] = $data['trade_mode'];
            $receiving['trans_mode'] = $data['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];
            $receiving['netweight'] = $data['netweight'];
            if ($data['haveconta'] == '1') {
                $receiving['haveconta'] = '1';
                $receiving['conta_id'] = $data['conta_id'];
                $receiving['conta_model'] = $data['conta_model'];
                $receiving['conta_wt'] = $data['conta_wt'];
            } else {
                $receiving['haveconta'] = '0';
                $receiving['conta_id'] = '';
                $receiving['conta_model'] = '';
                $receiving['conta_wt'] = '0';
            }
            $receiving['receiving_description'] = $data['instructions'];
            $receiving['receiving_update_time'] = date("Y-m-d H:i:s");

            Service_Receiving::update($receiving, $ASNCode, 'receiving_code');
            $note = 'update';

            $asnOrders = $data['asn_order'];
            //$sku =  $data['sku'];


            /*得到原来的收货单的订单列表*/
            $oldReceivingOrders = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $ASNCode));
            $oldReceivingOrderCodeList = array();
            if ($oldReceivingOrders) {
                foreach ($oldReceivingOrders as $oldReceivingOrder) {
                    $oldReceivingOrderCodeList[] = $oldReceivingOrder['order_code'];
                }
            }

            /*得到新的收货单的订单列表*/
            $newReceivingOrderCodeList = array();
            foreach ($asnOrders as $keyo => $orderCode) {
                $newReceivingOrderCodeList[] = $orderCode;
            }
            /*构成订单变化*/
            if ($newReceivingOrderCodeList != $oldReceivingOrderCodeList) {
                $AddedOrders = array_diff($newReceivingOrderCodeList, $oldReceivingOrderCodeList); //新增加的订单
                $DeletedAddOrders = array_diff($oldReceivingOrderCodeList, $newReceivingOrderCodeList); //被删除的订单
            }


            if ($DeletedAddOrders) {//将删除的订单的状态改为确认状态
                foreach ($DeletedAddOrders as $keyDeleteno => $orderCode) {
                    $orderInfo = Service_Orders::getByField($orderCode, 'order_code');

                    $orderRow = array(
                        'order_status' => '2',
                        'update_time' => date("Y-m-d H:i:s")
                    );
                    Service_Orders::update($orderRow, $orderCode, 'order_code');

                    $logRow = array(
                        'order_id' => $orderInfo['order_id'],
                        'order_code' => $orderCode,
                        'ol_type' => '1',
                        'order_status_from' => $orderInfo['order_status'],
                        'order_status_to' => 2,
                        'ol_add_time' => date("Y-m-d H:i:s"),
                        'user_id' => '-1',
                        'account_id' => Service_Login::getUserId(),
                        'ol_ip' => Common_Common::getIP()
                    );
                    Service_OrderLog::add($logRow);
                    $warehouse = Service_Warehouse::getByField($orderInfo['warehouse_id'], 'warehouse_id');
                    $shipOrderTracking = array(
                        'order_code' => $orderCode,
                        'sot_location' => '客户仓库',
                        'sot_add_time' => date("Y-m-d H:i:s"),
                        'warehouse_id' => $orderInfo['warehouse_id'],
                        'sot_description' => '从集货入库单中被删除导致订单状态变为确认状态',
                        'sot_type' => '0',
                        'sot_time_offset' => '',
                        'tracking_number' => $orderCode,
                        'ref_tracking_number' => '',
                        'status_desc' => '确认',
                        'user_id' => -1
                    );
                    Service_ShipOrderTracking::add($shipOrderTracking);
                    /*解冻*/
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult = $balanceProcess->unfreezeFee($orderCode);
                    if ($feeResult !== true) {
                        throw new Exception($feeResult);
                    }


                }
            }//if($DeletedAddOrders){


            Service_ReceivingOrderDetail::delete($ASNCode, 'receiving_code');
            foreach ($asnOrders as $keyo => $orderCode) {
                //$product = Service_Product::getByField($v,'product_sku');

                $orderInfo = Service_Orders::getByField($orderCode, 'order_code');

                $receiving_order_detail = array(
                    'receiving_id' => $ASNRow['receiving_id'],
                    'receiving_code' => $ASNCode,
                    'rd_status' => '0',
                    'order_code' => $orderCode,
                    'rd_add_time' => $date
                );
                $receivingOrderDetailArr[] = $receiving_order_detail;
                Service_ReceivingOrderDetail::add($receiving_order_detail);
                //修改订单到已提交状态
                $orderRow = array(
                    'order_status' => '4',
                    'update_time' => $date
                );
                Service_Orders::update($orderRow, $orderCode, 'order_code');

                $customerId = $this->_customerId;
                if (in_array($orderCode, $AddedOrders)) {


                    $logRow = array(
                        'order_id' => $orderInfo['order_id'],
                        'order_code' => $orderCode,
                        'ol_type' => '1',
                        'order_status_from' => $orderInfo['order_status'],
                        'order_status_to' => 4,
                        'ol_add_time' => date("Y-m-d H:i:s"),
                        'user_id' => '-1',
                        'account_id' => Service_Login::getUserId(),
                        'ol_ip' => Common_Common::getIP()
                    );
                    Service_OrderLog::add($logRow);
                    $warehouse = Service_Warehouse::getByField($orderInfo['warehouse_id'], 'warehouse_id');
                    $shipOrderTracking = array(
                        'order_code' => $orderCode,
                        'sot_location' => '客户仓库',
                        'sot_add_time' => date("Y-m-d H:i:s"),
                        'warehouse_id' => $orderInfo['warehouse_id'],
                        'sot_description' => '入库单编辑致订单状态变为已提交状态',
                        'sot_type' => '0',
                        'sot_time_offset' => '',
                        'tracking_number' => $orderCode,
                        'ref_tracking_number' => '',
                        'status_desc' => '已提交',
                        'user_id' => -1
                    );
                    Service_ShipOrderTracking::add($shipOrderTracking);
                    //预扣费
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult = $balanceProcess->freezeFee($orderCode, $customerId);
                    if ($feeResult !== true) throw new Exception($feeResult);


                }


            }


            $ASNLog = array(
                'receiving_id' => $ASNRow['receiving_id'],
                'receiving_code' => $ASNCode,
                'user_id' => '-1',
                'customer_code' => $this->_customerInfo['customer_code'],
                'rl_note' => $note,
                'rl_status_from' => $ASNRow['receiving_status'],
                'rl_status_to' => $ASNRow['receiving_status'],
                //'rl_add_time'=>date("Y-m-d H:i:s"),
                //'rl_ip'=>Common_Common::getIP()
            );
            //print_r($ASNLog);
            self::createAsnLog($ASNLog);
            //$DB->rollBack();
            $DB->commit();
            return array('ask' => 1, 'msg' => "收货单[{$ASNCode}]更新成功.", 'error' => array(), 'ASNCode' => $ASNCode);
            //return array('ask' => 1, 'msg' => Ec_Lang::getInstance()->getTranslate('update').Ec_Lang::getInstance()->getTranslate('success'), 'error' => array(), 'ASNCode' => $ASNCode);
        } catch (Zend_Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getInternalError();
            $result['msg'] = $e->getInternalError();
            return $result;
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /*
    * 删除 ASN 信息
    * @param $order ASN ,$productArr=array() ASN产品 ,$customerId 客户ID
    * @return array('ask' => 0, 'msg' => '','errorCode'=>array(), 'ASNCode' => $ASNCode);
    */
    public function deleteAsnProductTransaction($ASNCode = '', $productArr = array(), $customerId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'errorCode' => array(), 'ASNCode' => $ASNCode);
        $date = date('Y-m-d H:i:s');
        try {

            $DB = Default_Service_Common::getAdapter();
            $DB->beginTransaction();
            if ($customerId != '') {
                $this->_customerId = $customerId;
            }
            if (empty($ASNCode) || empty($productArr)) {
                throw new Exception('request Data Err.', 20000);
            }
            $ASNRow = Merchant_Service_Receiving::getByField($ASNCode, 'receiving_code');
            if (!isset($ASNRow['customer_id']) || $ASNRow['customer_id'] != $this->_customerId) {
                throw new Exception('ASNCode:' . $ASNCode . ' can not be found.', 20013);
            }
            if (!in_array($ASNRow['status'], array('1'))) {
                throw new Exception("permission deny,ASNCode:" . $ASNCode . " status is not allow.", 20002);
            }

            $order['customer_id'] = $this->_customerId;
            $this->_warehouseId = $ASNRow['warehouse_id'];
            $oldProductIds = array();
            $oldItemStatus = array();
            $oldItemIds = $delProduct = array();
            $note = 'delete';
            $itemRows = Merchant_Service_ReceivingItem::getByCondition(array('receiving_code' => $ASNCode), '*');
            foreach ($itemRows as $val) {
                $oldProductIds[] = $val['product_id'];
                $oldItemStatus[$val['product_id']] = $val['status'];
                $oldItemIds[$val['product_id']] = $val['ri_id'];
                if (in_array($val['product_id'], $productArr)) {
                    $delProduct[$val['product_id']] = $val['order_qty'];
                }
            }

            //删除产品
            foreach ($productArr as $productId) {
                $productRow = Merchant_Service_Product::getByField($productId, 'product_id');
                if (!in_array($productId, $oldProductIds)) {
                    throw new Exception('ASNCode:' . $ASNCode . ' ,sku:' . $productRow['product_sku'] . ' is not belong this AsnCode', 20003);
                }
                if (!in_array($oldItemStatus[$productId], array('0'))) {
                    throw new Exception('permission deny,AsnCode:' . $ASNCode . ' ,sku:' . $productRow['product_sku'] . ' status is not allow.', 20002);
                }
                Merchant_Service_ReceivingItem::delete($oldItemIds[$productId], 'ri_id');
                $note .= ' sku:' . $productRow['product_sku'] . ' ';
            }
            //当所有产品删除后,删除ASN
            if (count($productArr) == count($oldProductIds)) {
                Merchant_Service_Receiving::delete($ASNCode, 'receiving_code');
            } else {
                $order['modified'] = $date;
                Merchant_Service_Receiving::update($order, $ASNCode, 'receiving_code');
            }
            //库存调整
            self::deleteInventory($ASNCode, $delProduct, $ASNRow['warehouse_id'], 'delete asn product');
            $ASNLog = array(
                'receiving_code' => $ASNCode,
                'customer_id' => $this->_customerId,
                'rl_statu_now' => $ASNRow['status'],
                'rl_note' => $note
            );
            self::createAsnLog($ASNLog);
            $DB->commit();
            return array('ask' => 1, 'msg' => 'Success', 'errorCode' => array(), 'ASNCode' => $ASNCode);
        } catch (Zend_Exception $e) {
            $DB->rollBack();
            $result['Error'][] = array(
                'errorMessage' => $e->getInternalError(),
                'errorCode' => $e->getCode(),
            );
            $result['msg'] = $e->getInternalError();
            return $result;
        } catch (Exception $e) {
            $DB->rollBack();
            $result['Error'][] = array(
                'errorCode' => $e->getCode(),
                'errorMessage' => $e->getMessage()
            );
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }

    /**
     * @author william-fan
     * @todo 检查 receiving 表 ref_id 字段值(客户参考号)的唯一性
     *  $referenceNo已存在返回 false;不存在返回 true;
     */
    public static function checkReferenceNo($params = array())
    {
        $condition = array(
            'reference_no' => $params['reference_no'],
            'customer_id' => $params['customer_id'],
            'receiving_status_arr' => $params['receiving_status_arr']
        );
        $rows = Service_Receiving::getByCondition($condition, '*');
        return $rows;
    }

    /*
     * 检查产品状态是否可用
     * @params $productId,customerId
     * @return ask  0:没有数据  1:符合customerId  2:有数据不符合customerId  3:产品不可用 ;  productInfo=>产品数据
     */
    public function checkProductStatus($productId = '', $customerId = null)
    {
        if (!$customerId) {
            $customerId = $this->_customerId;
        }
        $result = array('ask' => 0, 'productInfo' => array());
        $productRow = Service_Product::getByField($productId, 'product_id');
        //var_dump(Service_Product::getByField($productId, 'product_id'));
        //exit;
        $result['productInfo'] = $productRow;
        if (empty($productRow)) {
            return $result;
        } elseif ($productRow['customer_id'] != $customerId) {
            $result['ask'] = 2;
            return $result;
        } elseif ($productRow['product_status'] == '0') {
            $result['ask'] = 3;
            return $result;
        } else {
            $result['ask'] = 1;
            return $result;
        }
        return array('ask' => 0, 'productInfo' => $productRow);
    }


    /*
     * 针对指定用户，生成一个新的相应 AsnCode
     * @return ASNCode
     */
    public function createCode()
    {
        if ($this->_pro == '') {
            //$this->_pro = 'RE';
            $this->_pro = 'BHR';
        }
        $this->_pro = strtoupper($this->_pro);
        //return Common_GetNumbers::getCode('ASN', '', $this->_pro);
        return Common_GetNumbers::getOnlyCode('ASNOnly', '', $this->_pro);
    }

    /*
    * 针对指定用户，生成一个新的相应 BoxCode
    * @return BoxCode
    */
    public function createBoxCode()
    {
        return Merchant_Service_GetNumbers::getCode($this->_customerId, 'box', 'P');
    }

    /*
     *  创建日志
     */
    public static function createAsnLog($row)
    {
        $row['rl_add_time'] = date('Y-m-d H:i:s');
        $row['rl_ip'] = Common_Common::getIP();
        $row['account_id'] = Service_Login::getUserId(); // 操作人账号ID，0为主账号，其他为子账号ID
        Service_ReceivingLog::add($row);
    }

    /*
     * 根据ASN订单号，获取ASN信息
     */
    public static function getAsnInfo($asnCode, $customerCode = '')
    {
        $result = array('ask' => 0, 'message' => '', 'Error' => array(), 'result' => array());
        $asnRow = Service_Receiving::getByField($asnCode, 'receiving_code');
        if (empty($asnRow) || $asnRow['customer_id'] != $customerCode) {
            $result['message'] = 'AsnCode:' . $asnCode . '不存在';
            $result['Error'][] = array('errorCode' => '20013', 'errorMessage' => 'AsnCode:' . $asnCode . ' can not be found.');
            return $result;
        }
        //集货模式的ASN
        /*if($asnRow['receive_model_type']=='1'){
			$receiveOrders = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $asnCode));
			$asnDetail = array();
			if(!empty($receiveOrders)){
				foreach($receiveOrders as $keyo=>$order){
					//获取订单的产品信息
					$orderProducts=Service_OrderProduct::getByCondition(array('order_code'=>$order['order_code']));
					if(!empty($orderProducts)){
						//$product_unit = 0;
						foreach($orderProducts as $keyop=>$vop){
							$productRow = Service_Product::getProductAllInfo($vop['product_id'],$customerCode);
							//$product_unit+=$val['rd_receiving_qty'];
							$detail = array();
							$detail['goods_id'] 	= $productRow['goods_id'];
							$detail['hs_code'] = $productRow['hs_code'];
							$detail['product_barcode'] 	= $productRow['product_barcode'];
							$detail['hs_goods_name'] 	= $productRow['hs_goods_name'];
							$detail['product_title'] 	= $productRow['product_title'];
							$detail['product_title_en']	= $productRow['product_title_en'];
							//申报要素
							$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$vop['product_id']), 'hem_detail');
							$elements = array();
							foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
							$detail['product_model'] 	= implode('|',$elements);
							//获取法定单位和数量
							$detail['pu_name_law'] = ''; //法定单位
							$detail['hum_quantity_law'] = ''; //法定单位数量
							if(isset($productRow['hs_uom_map']['pu_name_law'])){
								$detail['pu_name_law'] = $productRow['hs_uom_map']['pu_name_law'];
							}
							if(isset($productRow['hs_uom_map']['hum_quantity_law'])){
								$detail['hum_quantity_law'] = $productRow['hs_uom_map']['hum_quantity_law'];
							}
							$detail['pu_name_second'] = ''; //第二单位
							$detail['hum_quantity_second'] = ''; //第二单位数量


							if(isset($productRow['hs_uom_map']['pu_name_second'])){
								$detail['pu_name_second'] = $productRow['hs_uom_map']['pu_name_second'];
							}
							if(isset($productRow['hs_uom_map']['hum_quantity_second']) && $productRow['hs_uom_map']['hum_quantity_second']>0 ){
								$detail['hum_quantity_second'] = $productRow['hs_uom_map']['hum_quantity_second'];
							}
							$detail['product_unit_price'] 		= $productRow['product_declared_value']/$detail['hum_quantity_law'];
							$detail['product_total_price']	= $productRow['product_declared_value']*$vop['op_quantity'];
							$asnDetail[] = $detail;
						}
					}
				}
			}
			$asnRow['net_weight'] = Service_ReceivingOrderDetail::sumNetWeight($asnCode);
        }else{
        	$asnItem = Service_ReceivingDetail::getByCondition(array('receiving_code' => $asnCode));
        	$asnDetail = array();
        	$product_unit = 0;
        	foreach ($asnItem as $key => $val) {
        		$detail = $val;
        		$productRow = Service_Product::getProductAllInfo($val['product_id'],$customerCode);
        		$product_unit+=$val['rd_receiving_qty'];
        		$detail['goods_id'] 	= $productRow['goods_id'];
        		$detail['hs_code'] = $productRow['hs_code'];
        		$detail['product_barcode'] 	= $productRow['product_barcode'];
        		$detail['product_title'] 	= $productRow['product_title'];
        		$detail['product_title_en']	= $productRow['product_title_en'];
        		//申报要素
        		$hemList = Service_HsElementMap::getByCondition(array('product_id'=>$val['product_id']), 'hem_detail');
        		$elements = array();
        		foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
        		$detail['product_model'] 	= implode('|',$elements);
        		//获取法定单位和数量
        		$detail['pu_name_law'] = ''; //法定单位
        		$detail['hum_quantity_law'] = ''; //法定单位数量
        		if(isset($productRow['hs_uom_map']['pu_name_law'])){
        			$detail['pu_name_law'] = $productRow['hs_uom_map']['pu_name_law'];
        		}
        		if(isset($productRow['hs_uom_map']['hum_quantity_law'])){
        			$detail['hum_quantity_law'] = $productRow['hs_uom_map']['hum_quantity_law'];
        		}
        		$detail['pu_name_second'] = ''; //第二单位
        		$detail['hum_quantity_second'] = ''; //第二单位数量


        		if(isset($productRow['hs_uom_map']['pu_name_second'])){
        			$detail['pu_name_second'] = $productRow['hs_uom_map']['pu_name_second'];
        		}
        		if(isset($productRow['hs_uom_map']['hum_quantity_second']) && $productRow['hs_uom_map']['hum_quantity_second']>0 ){
        			$detail['hum_quantity_second'] = $productRow['hs_uom_map']['hum_quantity_second'];
        		}
        		$detail['product_unit_price'] 		= $productRow['product_declared_value']/$detail['hum_quantity_law'];
        		$detail['product_declared_value']	= $productRow['product_declared_value'];
        		$detail['product_total_price']	= $productRow['product_declared_value']*$val['rd_receiving_qty'];
        		$asnDetail[$key] = $detail;
        	}
        	$asnRow['product_unit'] = $product_unit;
        	$asnRow['net_weight'] = Service_ReceivingDetail::sumNetWeight($asnCode);
        	unset($asnItem);
        }*/

        $asnDetail = array();
        if ($asnRow['receive_model_type'] == '1') {
            $orderCodes = Service_ReceivingOrderDetail::getOrderCodes($asnCode);
            $asnDetail = Service_ReceivingOrderDetail::getXmlProducts($orderCodes, $asnCode);
            $asnRow['net_weight'] = number_format(Service_ReceivingOrderDetail::sumNetWeight($asnCode), 2, '.', '');
        } else {
            $asnDetail = Service_ReceivingDetail::getXmlProducts($asnCode);
            $asnRow['net_weight'] = number_format(Service_ReceivingDetail::sumNetWeight($asnCode), 2, '.', '');
        }
        $productList = array();
        foreach ($asnDetail as $info) {
            $hemList = Service_HsElementMap::getByCondition(array('product_id' => $info['product_id']), 'hem_detail');
            $elements = array();
            foreach ($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
            $info['product_model'] = implode('|', $elements);
            $info['quantity_law'] = round($info['hum_quantity_law'] * $info['quantity'], 4);
            $total_price = sprintf("%.4f", $info['total_price']);
            //$info['product_unit_price'] = sprintf("%.4f", $info['product_declared_value']/$info['hum_quantity_law']);
            $info['product_unit_price'] = sprintf("%.4f", $total_price / $info['quantity_law']);
            $info['quantity_second'] = $info['pu_code_second'] ? round($info['hum_quantity_second']* $info['quantity'], 4) : '';
            //$info['product_total_price'] = sprintf("%.2f", $info['product_declared_value']*$info['quantity']);
            $info['product_total_price'] = $total_price;
            $productList[] = $info;
        }

        $warehouseAll = Common_DataCache::getWareHouse();
        $warehouseCode = $warehouseAll[$asnRow['warehouse_id']]['warehouse_code'];
        $asnRow['warehouse_name'] = $warehouseCode;
        $asnRow['form_id'] = $asnRow['receiving_code'];
        $asnData = array(
            'asnRow' => $asnRow,
            'ASNCode' => $asnRow['receiving_code'],
            'addTime' => $asnRow['receiving_add_time'],
            'lastModifyTime' => $asnRow['receiving_update_time'],
            'warehouseCode' => $warehouseCode,
            'ASNDetail' => $productList,
        );
        $result['result'] = $asnData;
        $result['ask'] = 1;
        return $result;
    }

    /**
     * 根据ASNItem 添加onWay库存
     * @param string $asnCode
     * @param array $itemArr
     * @param string $note
     * @return bool
     * @throws Exception
     */
    private function addInventory($asnCode = '', $itemArr = array(), $note = 'create asn')
    {
        $InventoryObj = new Service_ProductInventoryProcess();
        $row = array(
            'type' => 0,
            'warehouse_id' => $this->_warehouseId,
            'application_id' => $asnCode,
            'application_type' => 2,
            'note' => $note,
        );
        foreach ($itemArr as $val) {
            $row['product_id'] = $val['product_id'];
            $row['quantity'] = $val['order_qty'];
            $result = $InventoryObj->update($row);
            if (!isset($result['ask']) || $result['ask'] != 1) {
                throw new Exception('update inventory error.' . $result['msg'], 20014);
                return false;
            }
        }
        return true;
    }

    /**
     * 根据ASNItem 更新onWay库存
     * @param string $asnCode
     * @param array $itemArr
     * @param string $note
     * @return bool
     * @throws Exception
     */
    private function updateInventory($asnCode = '', $itemArr = array(), $note = 'update asn')
    {
        $oldItem = Merchant_Service_ReceivingItem::getByCondition(array('receiving_code' => $asnCode), '*');
        $InventoryObj = new Merchant_Service_ProductInventoryProcess();
        $row = array(
            'type' => 0,
            'warehouse_id' => $this->_warehouseId,
            'application_id' => $asnCode,
            'application_type' => 2,
            'note' => $note,
        );
        foreach ($oldItem as $val) {
            $row['product_id'] = $val['product_id'];
            $row['quantity'] = $val['order_qty'] * -1;
            $row['note'] = 'delete asn product';
            $result = $InventoryObj->update($row);
            if (!isset($result['ask']) || $result['ask'] != 1) {
                throw new Exception('delete inventory error.' . $result['msg'], 20014);
                return false;
            }
        }
        foreach ($itemArr as $val) {
            $row['product_id'] = $val['product_id'];
            $row['quantity'] = $val['order_qty'];
            $row['note'] = 'add asn product';
            $result = $InventoryObj->update($row);
            if (!isset($result['ask']) || $result['ask'] != 1) {
                throw new Exception('update inventory error.' . $result['msg'], 20014);
                return false;
            }
        }
        return true;
    }

    /**
     * 根据ASNItem 更新onWay库存 用于删除ASN产品
     * @param string $asnCode
     * @param array $delItemArr
     * @param string $warehouseId
     * @param string $note
     * @return bool
     * @throws Exception
     */
    private function deleteInventory($asnCode = '', $delItemArr = array(), $warehouseId = '', $note = 'delete asn')
    {
        $InventoryObj = new Merchant_Service_ProductInventoryProcess();
        $row = array(
            'type' => 0,
            'warehouse_id' => $warehouseId,
            'application_id' => $asnCode,
            'application_type' => 2,
            'note' => $note,
        );
        foreach ($delItemArr as $productId => $qty) {
            $row['product_id'] = $productId;
            $row['quantity'] = $qty * -1;
            $row['note'] = 'delete asn product';
            $result = $InventoryObj->update($row);
            if (!isset($result['ask']) || $result['ask'] != 1) {
                throw new Exception('delete inventory error.' . $result['msg'], 20014);
                return false;
            }
        }
        return true;
    }

    /**
     * 转到删除状态
     * @param $order ASN ,$customerId 客户ID
     * @return array('ask' => 0, 'msg' => '','errorCode'=>array(), 'ASNCode' => $ASNCode);
     */
    public function deleteAsnTransaction($ASNCode = '', $customerId = '')
    {
        $result = array('ask' => 0, 'message' => '删除失败', 'errorCode' => array(), 'ASNCode' => $ASNCode);
        $date = date('Y-m-d H:i:s');
        try {

            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();

            if (empty($ASNCode)) {
                throw new Exception('ASN为空', 20000);
            }
            $ASNRow = Service_Receiving::getByField($ASNCode, 'receiving_code');
            if (!isset($ASNRow['customer_id']) || $ASNRow['customer_id'] != $customerId) {
                throw new Exception('ASN不存在或无权限', 20013);
            }
            if ($ASNRow['receiving_status'] == '0') {
                return array('ask' => 1, 'message' => '成功删除', 'errorCode' => array(), 'ASNCode' => $ASNCode);
            }
            if (!in_array($ASNRow['receiving_status'], array('1'))) {
                throw new Exception("ASN状态不允许删除", 20002);
            }

            $order['customer_id'] = $customerId;
            $this->_warehouseId = $ASNRow['warehouse_id'];

            $customerInfo = Service_Customer::getByField($customerId);
            if ($ASNRow['receive_model_type'] == '1') {
                //集货模式的ASN 删除ASN和订单的关联 并将订单改成确认状态
                $receivingOrdersCondition = array(
                    'receiving_code' => $ASNCode,
                );
                $receivingOrders = Service_ReceivingOrderDetail::getByCondition($receivingOrdersCondition);
                // Service_ReceivingOrderDetail::getByCondition()
                //Service_ReceivingDetail::getByCondition()
                if (!empty($receivingOrders)) {
                    foreach ($receivingOrders as $ko => $vo) {
                        $orderRow = Service_Orders::getByField($vo['order_code'], 'order_code', "*");
                        $upOrderRow = array(
                            'order_status' => '2',
                        );
                        if ($orderRow['sm_code'] == "UKTL" || $orderRow['sm_code'] == "SZY-EUB" || $orderRow['sm_code'] == "SZY-ETK" || $orderRow['sm_code'] == "WG-EUB") {
                            $upOrderRow['ref_tracking_number'] = "";
                        }
                        Service_Orders::update($upOrderRow, $vo['order_code'], 'order_code');
                        $logRow = array(
                            'order_id' => $orderRow['order_id'],
                            'order_code' => $vo['order_code'],
                            'ol_type' => 0,
                            'order_status_from' => $orderRow['order_status'],
                            'order_status_to' => 2,
                            'ol_add_time' => date('Y-m-d H:i:s'),
                            'user_id' => '-1',
                            'ol_comments' => 'ASN删除',
                            'account_id' => Service_Login::getUserId(),
                            'ol_ip' => Common_Common::getIP()
                        );
                        Service_OrderLog::add($logRow);
                        //退回费用
                        $balanceProcess = new Service_CustomerBalanceProcess();
                        $feeResult = $balanceProcess->unfreezeFee($vo['order_code'], 'ASN退回,解冻金额');
                    }
                    Service_ReceivingOrderDetail::delete($ASNCode, 'receiving_code');
                } else {
                    throw new Exception("ASN和订单关联不存在");
                }
            } else {
                //备货模式订单和以前处理一样
                //echo 'nnnn';
            }

            $delProduct = array();
            $note = 'delete asn ';

            Service_Receiving::update(array('receiving_status' => 0), $ASNCode, 'receiving_code');

            //self::deleteInventory($ASNCode, $delProduct, $ASNRow['warehouse_id'], 'delete asn');
            $ASNLog = array(
                'receiving_id' => $ASNRow['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type' => '1',
                'user_id' => '-1',
                'customer_code' => $customerInfo['customer_code'],
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_status_from' => 1,
                'rl_status_to' => 0,
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            $DB->commit();
            //$DB->rollBack();
            return array('ask' => 1, 'message' => "收货单号[{$ASNCode}]" . '删除成功', 'errorCode' => array(), 'ASNCode' => $ASNCode);
        } catch (Zend_Exception $e) {
            $DB->rollBack();
            $result['Error'][] = array(
                'errorMessage' => $e->getInternalError(),
                'errorCode' => $e->getCode(),
            );
            $result['message'] = $e->getInternalError();
            return $result;
        } catch (Exception $e) {
            $DB->rollBack();
            $result['Error'][] = array(
                'errorCode' => $e->getCode(),
                'errorMessage' => $e->getMessage()
            );
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }


    /**
     * @param string $ASNCode
     * @param array $productArr
     * @param string $customerId
     * @return array('ask' => 0,'msg'=>'', 'Error' => array(), 'ASNCode' => $ASNCode);
     * @throws Exception
     */
    public function cancelProductTransaction($ASNCode = '', $productArr = array(), $customerId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'Error' => array(), 'ASNCode' => $ASNCode);
        $date = date('Y-m-d H:i:s');
        try {

            $DB = Default_Service_Common::getAdapter();
            $DB->beginTransaction();
            if ($customerId != '') {
                $this->_customerId = $customerId;
            }
            if (empty($ASNCode) || empty($productArr)) {
                throw new Exception('request Data Err.', 20000);
            }
            $ASNRow = Merchant_Service_Receiving::getByField($ASNCode, 'receiving_code');
            if (!isset($ASNRow['customer_id']) || $ASNRow['customer_id'] != $this->_customerId) {
                throw new Exception('ASNCode:' . $ASNCode . ' can not be found.', 20001);
            }
            if (!in_array($ASNRow['status'], array('1', '2'))) {
                throw new Exception("permission deny,ASNCode:" . $ASNCode . " status is not allow.", 20002);
            }

            $order['customer_id'] = $this->_customerId;
            $this->_warehouseId = $ASNRow['warehouse_id'];
            $oldProductIds = array();
            $oldItemStatus = array();
            $oldItemIds = $delProduct = array();
            $note = 'cancel';
            $itemRows = Merchant_Service_ReceivingItem::getByCondition(array('receiving_code' => $ASNCode), '*');
            foreach ($itemRows as $val) {
                $oldProductIds[] = $val['product_id'];
                $oldItemStatus[$val['product_id']] = $val['status'];
                $oldItemIds[$val['product_id']] = $val['ri_id'];
                if (in_array($val['product_id'], $productArr)) {
                    $delProduct[$val['product_id']] = $val['order_qty'];
                }
            }

            //删除产品
            foreach ($productArr as $productId) {
                $productRow = Merchant_Service_Product::getByField($productId, 'product_id');
                if (!in_array($productId, $oldProductIds)) {
                    throw new Exception('ASNCode:' . $ASNCode . ' ,sku:' . $productRow['product_sku'] . ' is not belong this AsnCode', 20003);
                }
                if (!in_array($oldItemStatus[$productId], array('0'))) {
                    throw new Exception('permission deny,AsnCode:' . $ASNCode . ' ,sku:' . $productRow['product_sku'] . ' status is not allow.', 20002);
                }
                Merchant_Service_ReceivingItem::delete($oldItemIds[$productId], 'ri_id');
                $note .= ' sku:' . $productRow['product_sku'] . ' ';
                //清除已删除的产品
                unset($oldItemStatus[$productId]);
            }
            //判断是否全部未到货的产品是否全部已删除
            $received = true;
            $newStatus = array();
            foreach ($oldItemStatus as $k => $v) {
                if ($v == 0) {
                    $received = false;
                    continue;
                }
                $newStatus[] = $v;
            }
            $asnStatus = $ASNRow['status'];
            if ($received) {
                if (in_array(1, $newStatus)) {
                    $asnStatus = 2;
                } elseif (!in_array(1, $newStatus) && !in_array(0, $newStatus) && in_array(2, $newStatus)) {
                    $asnStatus = 3;
                }
                $order['modified'] = $date;
                $order['status'] = $asnStatus;
                Merchant_Service_Receiving::update($order, $ASNCode, 'receiving_code');
            }

            //onWay库存调整
            self::deleteInventory($ASNCode, $delProduct, $ASNRow['warehouse_id'], 'cancel asn product');
            $ASNLog = array(
                'receiving_code' => $ASNCode,
                'customer_id' => $this->_customerId,
                'rl_statu_now' => $asnStatus,
                'rl_note' => $note
            );
            self::createAsnLog($ASNLog);
            $DB->commit();
            return array('ask' => 1, 'Error' => array(), 'ASNCode' => $ASNCode);
        } catch (Zend_Exception $e) {
            $DB->rollBack();
            $result['Error'][] = array(
                'errorMessage' => $e->getInternalError(),
                'errorCode' => $e->getCode(),
            );
            $result['msg'] = $e->getInternalError();
            return $result;
        } catch (Exception $e) {
            $DB->rollBack();
            $result['Error'][] = array(
                'errorCode' => $e->getCode(),
                'errorMessage' => $e->getMessage()
            );
            $result['msg'] = $e->getMessage();
            return $result;
        }
    }


    /**
     * @param array $data
     * @return array('ask' => 0, 'msg' => array(), 'data' => array());
     * @author william-fan
     * @todo 备货表单数据验证
     */
    public static function validate($data = array())
    {
        $error = array();
        if (empty($data)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错';
            return $error;
        }
        if ("" == $data['warehouseId']) {
            $error[] = Ec_Lang::getInstance()->getTranslate('WarehouseRequired');//"仓储必填";
        }
        if (isset($data['receive_model_type']) && ($data['receive_model_type'] == '0' || $data['receive_model_type'] == '1')) {
            if ($data['receive_model_type'] == '1') {
                //集货模式
                if (!isset($data['asn_order']) || empty($data['asn_order'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('OrdersMustBeSelected');//"必须选择订单";
                }
            } else {
                //备货模式
                if (!isset($data['product_sku']) || empty($data['product_sku'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('ProductsMusBeSelected');//"必须选择产品";
                }
            }
        } else {
            $error[] = Ec_Lang::getInstance()->getTranslate('ASNSchema') . Ec_Lang::getInstance()->getTranslate('error');//"仓储必填";
        }
        if (!(isset($data['is_delivery']) && ($data['is_delivery'] == '0' || $data['is_delivery'] == '1'))) {
            $error[] = "是否提货必须填写";
        }
        if ($data['ref_code'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('CustomerReference') . Ec_Lang::getInstance()->getTranslate('require');// '客户参考号必填';
        } else {

        }
        if ($data['ie_port'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('ImportexportPorts') . Ec_Lang::getInstance()->getTranslate('require');//'进出口口岸必填';
        }
        if ($data['form_type'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('BusinessType') . Ec_Lang::getInstance()->getTranslate('require');//'业务类型必填';
        }
        /* if($data['form_type']==''){
        	$error[] = '业务类型必填';
        }
        if($data['traf_name']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('LicensePlateNumber').Ec_Lang::getInstance()->getTranslate('require');//'车牌号必填';
        } */
        if ($data['wrap_type'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('PackingType') . Ec_Lang::getInstance()->getTranslate('require');//'包装种类必填';
        }

        if ($data['pack_no'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('TotalNumber') . Ec_Lang::getInstance()->getTranslate('require');//'总件数必填';
        } else {

            if (!preg_match('/[0-9]+/i', $data['pack_no']) || !is_numeric($data['pack_no']) || $data['pack_no'] < 1) {
                $error[] = Ec_Lang::getInstance()->getTranslate('packNoError');//'总件数必须为正';
            }

        }


        if ($data['trade_mode'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('RegulatoryApproach') . Ec_Lang::getInstance()->getTranslate('require');//'监管方式必填';
        }
        if ($data['trans_mode'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('TransactionMethod') . Ec_Lang::getInstance()->getTranslate('require');//'成交方式必填';
        }
        if ($data['ASNCode'] != '') {
            $receiving = Service_Receiving::getByField($data['ASNCode'], 'receiving_code');
            if (!empty($receiving) && $receiving['receiving_status'] != '1') {
                $error[] = Ec_Lang::getInstance()->getTranslate('CanNotEditOnThisStatus');//"收货单状态不对";
            }
        }


        /*
        if($data['netweight'] && (!is_numeric($data['netweight']) || $data['netweight']<0)){
        		$error[] = Ec_Lang::getInstance()->getTranslate('netweightError');//毛重
        }
		*/
        //$sessionUser = new Zend_Session_Namespace("customerAuth");
        //$customerAuth = new Zend_Session_Namespace("customerAuth");

        //$customerId = $customerAuth->customer['customer_id'];
        $customerAuth = Service_Login::getLoginInfo();
        $customerId = $customerAuth['id'];
        /*if($data['ref_code']!='' && $data['ASNCode']){
	 			$condition = array('reference_no'=>$data['ref_code'],'customer_id'=>$customerId,'receiving_status_arr'=>array('1','2','3','4','5','6','7'));
		 		$receivings = Service_Receiving::getByCondition($condition,'reference_no');
				if($receivings){
					foreach($receivings as $receiving){
							if($receiving['reference_no']!=$data['ref_code']){
									$error[] = Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'); //"参考号已经存在";
									break;
							}

					}


				}


		 }*/

        if ($data['ref_code'] != '' && empty($data['ASNCode'])) {
            $condition = array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7'));
            $receivings = Service_Receiving::getByCondition($condition, 'reference_no');
            if ($receivings) {
                $error[] = Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'); //"参考号已经存在";
            }
        }

        if ($data['receive_model_type'] != '1') {//备货模式
            if (isset($data['product_sku']) && !empty($data['product_sku'])) {
                $product_sku = $data['product_sku'];
                $sum = 0;
                $sku = @$data['sku'];

                foreach ($product_sku as $k => $v) {
                    $product = Service_Product::getByField($k, 'product_id');
                    if (!$product) {
                        $error[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('DoesNotExist');
                        continue;
                    } else {
                        //if(!preg_match('/[0-9]+/i',$sku[$k]) || $sku[$k]<0){
                        //$error[] = "产品SKU:[{$v}]的数量".Ec_Lang::getInstance()->getTranslate('NumberMustBeAnInteger');
                        //}
                        //判断产品是否是普通产品
                        if (!in_array($product['product_type'], array('0'))) {
                            $error[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('ProductTypeError');
                        }
                        if ($product['product_status'] != '1') {
                            $error[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('ProductStatusError');
                        }
                        $hs_code = Service_Hscodes::getByField($product['hs_code'], 'hs_code');
                        if ($hs_code['hs_code_status'] == '-1') {
                            $error[] = "产品sku:" . $product['product_sku'] . "海关编码{$product['hs_code']}已废止";
                        }
                    }
                }
            }

            $total_weight = 0;
            if (isset($data['sku']) && !empty($data['sku'])) {
                $product_sku_array = $data['product_sku'];
                $number_array = $data['sku'];
                foreach ($number_array as $k => $number) {
                    $number = trim($number);
                    $product = Service_Product::getByField($k, 'product_id');
                    $total_weight += $product['product_weight'] * $number;
                    $sku = $product_sku_array[$k];
                    if (!(preg_match('/^[0-9]+$/i', $number) && is_numeric($number) && $number > 0)) {
                        $error[] = "产品SKU[{$sku}]" . Ec_Lang::getInstance()->getTranslate('NumberMustBeAnInteger');
                    }
                }
            }
            if (isset($data['declared_value']) && !empty($data['declared_value'])) {
                $declare = $data['declared_value'];
                foreach ($declare as $keyd => $valuen) {
                    $sku = $product_sku_array[$keyd];
                    $valuen = trim($valuen);
                    if (!is_numeric($valuen) || $valuen <= 0) {
                        $error[] = "产品SKU[{$sku}]" . '申报价值必须是数字';
                    }
                }
            }


            if ($data['roughweight'] == '') {
                $error[] = "毛重必填.";
            } elseif (!(is_numeric($data['roughweight']) && $data['roughweight'] > 0)) {
                $error[] = Ec_Lang::getInstance()->getTranslate('roughweightError');//毛重
            } else {

                if (isset($data['product_sku']) && !empty($data['product_sku'])) {
                    if ($total_weight > 0 && $data['roughweight'] < $total_weight) {
                        $error[] = "ASN重量({$data['roughweight']}KG)小于净重({$total_weight}KG)";
                    }
                }
            }
        }//if($data['receive_model_type']!='1')备货
        //$data['asn_order']

        //验证客户是否是从属客户
        if (Service_CustomerProcess::getOwner($customerAuth['code']) && $data['is_delivery'] == 1) {
            $error[] = Ec_Lang::getInstance()->getTranslate('deliveryNotSupported'); //"参考号已经存在";
        }

        return $error;
    }

    public static function validatePoAsn($data = array(), $customerId)
    {
        $error = array();
        if (empty($data)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错';
            return $error;
        }
        if ("" == $data['warehouseId']) {
            $error[] = Ec_Lang::getInstance()->getTranslate('WarehouseRequired');//"仓储必填";
        }
        if (isset($data['receive_model_type']) && ($data['receive_model_type'] == '0' || $data['receive_model_type'] == '1')) {
            if ($data['receive_model_type'] == '1') {
                //集货模式
                if (!isset($data['asn_order']) || empty($data['asn_order'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('OrdersMustBeSelected');//"必须选择订单";
                }
            } else {
                //备货模式
                if (!isset($data['product_sku']) || empty($data['product_sku'])) {
                    $error[] = Ec_Lang::getInstance()->getTranslate('ProductsMusBeSelected');//"必须选择产品";
                }
            }
        } else {
            $error[] = Ec_Lang::getInstance()->getTranslate('ASNSchema') . Ec_Lang::getInstance()->getTranslate('error');//"仓储必填";
        }
        if (!(isset($data['is_delivery']) && ($data['is_delivery'] == '0' || $data['is_delivery'] == '1'))) {
            $error[] = "是否提货必须填写";
        }
        if ($data['ref_code'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('CustomerReference') . Ec_Lang::getInstance()->getTranslate('require');// '客户参考号必填';
        } else {

        }
        if ($data['ie_port'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('ImportexportPorts') . Ec_Lang::getInstance()->getTranslate('require');//'进出口口岸必填';
        }
        if ($data['form_type'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('BusinessType') . Ec_Lang::getInstance()->getTranslate('require');//'业务类型必填';
        }
        /* if($data['form_type']==''){
        	$error[] = '业务类型必填';
        }
        if($data['traf_name']==''){
        	$error[] = Ec_Lang::getInstance()->getTranslate('LicensePlateNumber').Ec_Lang::getInstance()->getTranslate('require');//'车牌号必填';
        } */
        if ($data['wrap_type'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('PackingType') . Ec_Lang::getInstance()->getTranslate('require');//'包装种类必填';
        }

        if ($data['pack_no'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('TotalNumber') . Ec_Lang::getInstance()->getTranslate('require');//'总件数必填';
        } else {

            if (!preg_match('/[0-9]+/i', $data['pack_no']) || !is_numeric($data['pack_no']) || $data['pack_no'] < 1) {
                $error[] = Ec_Lang::getInstance()->getTranslate('packNoError');//'总件数必须为正';
            }

        }


        if ($data['trade_mode'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('RegulatoryApproach') . Ec_Lang::getInstance()->getTranslate('require');//'监管方式必填';
        }
        if ($data['trans_mode'] == '') {
            $error[] = Ec_Lang::getInstance()->getTranslate('TransactionMethod') . Ec_Lang::getInstance()->getTranslate('require');//'成交方式必填';
        }
        if ($data['ASNCode'] != '') {
            $receiving = Service_Receiving::getByField($data['ASNCode'], 'receiving_code');
            if (!empty($receiving) && $receiving['receiving_status'] != '1') {
                $error[] = Ec_Lang::getInstance()->getTranslate('CanNotEditOnThisStatus');//"收货单状态不对";
            }
        }
        if ($data['ref_code'] != '' && empty($data['ASNCode'])) {
            $condition = array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7'));
            $receivings = Service_Receiving::getByCondition($condition, 'reference_no');
            if ($receivings) {
                $error[] = Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'); //"参考号已经存在";
            }
        }
        //判断产品

        if (isset($data['po_tb_id']) && !empty($data['po_tb_id'])) {

            foreach ($data['po_tb_id'] as $po_tb_id) {
                if ($po_tb_id) {
                    $PurchaseOrderTrackingBody = Service_PoOrderTrackingBody::getByField($po_tb_id, 'po_tb_id');
                    if (empty($PurchaseOrderTrackingBody)) {
                        $error[] = Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错
                        break;

                    } else {
                        if ($PurchaseOrderTrackingBody['is_created_asn'] == '1') {
                            $error[] = Ec_Lang::getInstance()->getTranslate('AddIsCreateASNFail');
                            break;
                        }

                    }
                }

            }


        } else {
            $error[] = Ec_Lang::getInstance()->getTranslate('DataError');//'数据出错';
            return $error;

        }
        $total_weight = 0;
        if ($data['receive_model_type'] != '1') {//备货模式
            if (isset($data['product_sku']) && !empty($data['product_sku'])) {
                $product_sku = $data['product_sku'];

                foreach ($product_sku as $k => $v) {
                    $product_id = $data['product_id'][$k];
                    $product = Service_Product::getByField($product_id, 'product_id');
                    if (!$product) {
                        $error[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('DoesNotExist');
                        continue;
                    } else {
                        //if(!preg_match('/[0-9]+/i',$sku[$k]) || $sku[$k]<0){
                        //$error[] = "产品SKU:[{$v}]的数量".Ec_Lang::getInstance()->getTranslate('NumberMustBeAnInteger');
                        //}
                        //判断产品是否是普通产品
                        if (!in_array($product['product_type'], array('0'))) {
                            $error[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('ProductTypeError');
                        }
                        if ($product['product_status'] != '1') {
                            $error[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('ProductStatusError');
                        }
                        $hs_code = Service_Hscodes::getByField($product['hs_code'], 'hs_code');
                        if (empty($hs_code)) {
                            $error[] = '产品SKU[' . $v . ']对应海关编码[' . $product['hs_code'] . ']不存在';
                        }
                        if ($hs_code['hs_code_status'] == '-1') {
                            $error[] = "产品sku:" . $product['product_sku'] . "海关编码{$product['hs_code']}已废止";
                        }
                        $total_weight += $product['product_weight'] * $data['num'][$k];
                    }
                }
            }
            /*
        if(isset($data['declared_value']) && !empty($data['declared_value']) ) {
        	$declare	  = $data['declared_value'];
        	foreach ($declare as $keyd=>$valuen){
        		$sku = $product_sku_array[$keyd];
        		$valuen = trim($valuen);
        		if(!is_numeric($valuen) || $valuen<=0){
        			$error[] = "产品SKU[{$sku}]".'申报价值必须是数字';
        		}
        	}
        }
       */

            if ($data['roughweight'] == '') {
                $error[] = "毛重必填.";
            } elseif (!(is_numeric($data['roughweight']) && $data['roughweight'] > 0)) {
                $error[] = Ec_Lang::getInstance()->getTranslate('roughweightError');//毛重
            } else {

                if (isset($data['product_sku']) && !empty($data['product_sku']) && empty($error)) {
                    if ($total_weight > 0 && $data['roughweight'] < $total_weight) {
                        $error[] = "ASN重量({$data['roughweight']}KG)小于净重({$total_weight}KG)";
                    }
                }
            }
        }//if($data['receive_model_type']!='1')备货
        //$data['asn_order']


        return $error;
    }


    /**
     * @author william-fan
     * @todo 检查订单
     */
    public static function validOrder($data = array())
    {
        //检查订单
        $return = array();
        $error = array();
        $detail = array();
        $total_weight = 0;
        if (isset($data['asn_order']) && !empty($data['asn_order'])) {
            $orders = $data['asn_order'];
            foreach ($orders as $keyo => $ordercode) {
                $orderInfo = Service_Orders::getByField($ordercode, 'order_code');
                if (!empty($orderInfo)) {
                    $orderInfo = Service_Orders::getByFieldUpdate($orderInfo['order_id'], "order_id", "*");
                    if ($orderInfo['order_status'] != '2') {
                        //$error[] = Ec_Lang::getInstance()->getTranslate('orderCode').' '.$ordercode.Ec_Lang::getInstance()->getTranslate('IsNotRecognizedInTheState');
                        if ($orderInfo['order_status'] > 2) {
                            $receivingOrder = Service_ReceivingOrderDetail::getByField($ordercode, 'order_code');
                            $error[] = "订单[{$ordercode}]已创建了入区单[{$receivingOrder['receiving_code']}]";
                            $detail[$ordercode] = $receivingOrder['receiving_code'];
                        } else {
                            $orderStatus = Service_OrderProcess::getJHStatusText($orderInfo['order_status']);
                            $error[] = "订单[{$ordercode}]是" . $orderStatus . "状态";
                        }
                    }
                } else {
                    $error[] = Ec_Lang::getInstance()->getTranslate('orderCode') . ' ' . $ordercode . '' . Ec_Lang::getInstance()->getTranslate('DoesNotExist');
                }
                $cal_array = Service_OrderProcess::calucateOrderTotalWeight($ordercode);
                $total_weight += $cal_array['totalWeight'];
                $orderProducts = Service_OrderProduct::getByCondition(array('order_code' => $ordercode), '*');
                if (!empty($orderProducts)) {
                    foreach ($orderProducts as $kop => $vop) {
                        $product = Service_Product::getByField($vop['product_id'], 'product_id');
                        if (!empty($product)) {
                            $hs_code = Service_Hscodes::getByField($product['hs_code'], 'hs_code');
                            if ($hs_code['hs_code_status'] == '-1') {
                                $error[] = "产品sku:" . $product['product_sku'] . "海关编码{$product['hs_code']}已废止";
                            }
                        }
                    }
                }

            }
        }
        if ($data['roughweight'] == '') {
            $error[] = "毛重必填.";
        } else if (!(is_numeric($data['roughweight']) && $data['roughweight'] > 0)) {
            $error[] = Ec_Lang::getInstance()->getTranslate('roughweightError');//毛重
        } else {
            if (isset($data['asn_order']) && !empty($data['asn_order'])) {
                if (!($total_weight > 0 && $data['roughweight'] > $total_weight)) {
                    //$error[] = "毛重要大于净重({$total_weight}KG).";
                }
            }
        }
        $return = array(
            'error' => $error,
            'detail' => $detail
        );
        return $return;
    }

    /**
     * @author william-fan
     * @todo todo 确认ASn
     */
    public static function confirmASn($ASNCode = '', $customerId = '')
    {
        $result = array('ask' => 0, 'message' => '确认失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
        $error = array();
        $pdfSmcode = array('4PX-LYT_GH', //A6
            '4PX-EU_PACKET', //DS
            '4PX-RU_POST-LINK_RMAIL', //BA
            '4PX-HKDHL', //A1
            '4PX-YX', //AI
            '4PX-SG_ordinary_mail+',
            'PNLN', 'PNLG', 'BH-AZAT-G',
            'DHL-BH03',
            'BH-POST-NL',
            'BH-SFEP',
        );
        $sendOrderInfoSmcode = array(
            '4PX-Singapo_SPack_IMAIR', //B1
            '4PX-OZXBTH', //BB
        );
        if (empty($receiving)) {
            $error[] = 'ASN无效';
            $return['message'] = $result['message'] . 'ASN无效';
        } else {
            if ($receiving['receiving_status'] != '1') {
                $error[] = 'ASN状态错误';
                $return['message'] = $result['message'] . 'ASN状态错误';
            }
        }
        if (empty($customerId)) {
            $result['message'] = '客户错误';
            $result['message'] = $result['message'] . '客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        if ($receiving['customer_id'] != $customerId) {
            $result['message'] = '改ASN和客户不一致';
            return $result;
        }
        //判断法定单位总和是否大于毛重
        $law_weight = 0;
        if ($receiving['receive_model_type'] == 0) {
            $law_weight = Service_ReceivingDetail::sumLawWeight($ASNCode);
        } else if ($receiving['receive_model_type'] == 1) {
            $law_weight = Service_ReceivingOrderDetail::sumLawWeight($ASNCode);
        }
        if ($law_weight > $receiving['roughweight']) {
            $result['message'] = '法定单位为千克的SKU的总重量[' . $law_weight . ']大于ASN毛重[' . $receiving['roughweight'] . ']，请修改SKU的法定单位重量';
            return $result;
        }

        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status' => '2',
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("ASN确认失败");
            }
            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type' => '1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "确认ASN单",
                'rl_status_from' => $receiving['receiving_status'],
                'rl_status_to' => '2',
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );


            if ($receiving['receive_model_type'] == '0') {
                $conDetail = array(
                    'receiving_code' => $ASNCode,
                );
                $receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
                if (!empty($receivingDetail)) {
                    $totalWeight = 0;
                    foreach ($receivingDetail as $keyde => $valuede) {
                        $product = Service_Product::getByField($valuede['product_id']);
                        if (empty($product) || $product['product_type'] == '1') {
                            continue;
                        }
                        $totalWeight += $product['product_weight'] * $valuede['rd_receiving_qty'];

                    }
                }

            }//备货


            if ($receiving['receive_model_type'] == '1') {

                $conDetail = array(
                    'receiving_code' => $ASNCode,
                );
                $totalWeight = 0;
                $receivingDetail = Service_ReceivingOrderDetail::getByCondition($conDetail);
                if (!empty($receivingDetail)) {
                    $totalWeight = 0;
                    $noTracingOrder = array();
                    $noSendInfoOrder = array();
                    $errorMsg = '';
                    foreach ($receivingDetail as $keyde => $valuede) {
                        $totalWeight += Service_Orders::calculateWeight($valuede['order_code']);
                        $orderInfo = Service_Orders::getByField($valuede['order_code'], 'order_code');
                        if (in_array($orderInfo['sm_code'], $pdfSmcode)) {
                            if (empty($orderInfo['ref_tracking_number'])) {
                                $noTracingOrder[] = $orderInfo['order_code'];

                            }
                        }
                        if (in_array($orderInfo['sm_code'], $sendOrderInfoSmcode)) {
                            if ($orderInfo['sync_status'] != '1') {
                                $noSendInfoOrder[] = $orderInfo['order_code'];
                            }
                        }
                    }
                    if (!empty($noTracingOrder)) {
                        $errorMsg .= '订单' . implode(",", $noTracingOrder) . '没有获取到服务商单号<br/>';
                    }
                    if (!empty($noSendInfoOrder)) {
                        $errorMsg .= '运输渠道【' . implode("】【", $noSendInfoOrder) . '】订单：' . implode(",", $noSendInfoOrder) . '信息没有推送到4PX<br/>';
                    }
                    if (!empty($errorMsg)) {
                        throw new Exception($errorMsg);
                    }

                }

            }


            $roughweight = $receiving['roughweight'];
            if ($roughweight < $totalWeight) {
                throw new Exception("ASN重量({$roughweight}KG)小于净重({$totalWeight}KG)");
            }


            /*$conDetail = array(
   				'receiving_code'=>$ASNCode,
   			);
			$receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
			if(!empty($receivingDetail)){
				foreach ($receivingDetail as $keyde=>$valuede){
					$product = Service_Product::getByField($valuede['product_id']);

					$conInventory = array(
						'customer_id'=>$customerId,
						'product_id'=>$valuede['product_id'],
						'warehouse_id'=>$receiving['warehouse_id']
					);
					$productInventory = Service_ProductInventory::getByCondition($conInventory);
					if(empty($productInventory)){
						//添加一条product_inventory 记录
						$productInventoryRow = array(
								'product_barcode'=>$product['product_barcode'],
								'customer_id'=>$customerId,
								'product_id'=>$product['product_id'],
								'warehouse_id'=>$receiving['warehouse_id'],
								'pi_onway'=>$valuede['rd_receiving_qty'],
								'pi_add_time'=>date('Y-m-d H:i:s',time()),
						);
						Service_ProductInventory::add($productInventoryRow);
						$productInventoryLogRow = array(
								'product_id'=>$product['product_id'],
								'product_barcode'=>$product['product_barcode'],
								'warehouse_id'=>$receiving['warehouse_id'],
								'user_id'=>'-1',
								'pil_onway'=>$valuede['rd_receiving_qty'],
								'pil_ip'=>Common_Common::getIP(),
						);
						Service_ProductInventoryLog::add($productInventoryLogRow);
					}else{
						$inventory = $productInventory[0];
						//修改product_inventory 记录
						$productInventoryRow = array(
								'pi_onway'=>$valuede['rd_receiving_qty']+$inventory['pi_onway'],
								'pi_update_time'=>date('Y-m-d H:i:s',time()),
						);
						Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
						$productInventoryLogRow = array(
								'product_id'=>$product['product_id'],
								'product_barcode'=>$product['product_barcode'],
								'warehouse_id'=>$receiving['warehouse_id'],
								'user_id'=>'-1',
								'pil_onway'=>$valuede['rd_receiving_qty'],
								'pil_ip'=>Common_Common::getIP(),
						);
						Service_ProductInventoryLog::add($productInventoryLogRow);
					}
					//修改产品的have_asn字段
					$productRow = array(
						'have_asn'=>'1',
						'product_update_time'=>date('Y-m-d H:i:s')
					);
					Service_Product::update($productRow, $valuede['product_id']);
				}
			}*/

            self::createAsnLog($ASNLog);
            $result['ask'] = '1';
            $result['message'] = 'ASN确认成功';
            //$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 待审核 生成xml文件
     */
    public static function PendingAsn($ASNCode = '', $customerId)
    {
        $result = array('ask' => 0, 'message' => '确认失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
        $error = array();
        //print_r($receiving);exit;
        if (empty($receiving)) {
            $error[] = 'ASN无效';
        } else {
            if ($receiving['receiving_status'] != '2') {
                $error[] = 'ASN状态错误';
            }
        }
        if (empty($customerId)) {
            $result['message'] = '客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($receiving['customer_id'] != $customerId) {
            $result['message'] = '该ASN和客户不一致';
            return $result;
        }
        //查看报关单是否上传没上传不允许提交待审核
        if (!($receiving['baoguan_file'] != '' && file_exists($receiving['baoguan_file']))) {
            $result['message'] = '该入库单报关单未上传';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status' => '3',    //方便测试暂时为4
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("ASN移至待审核失败");
            }
            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type' => '-1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "移动ASN至待审核",
                'rl_status_from' => $receiving['receiving_status'],
                'rl_status_to' => '3',    //方便测试暂时为4
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            //改为自动运行程序提交审核
            /**$ftProcess = new Service_FtpMessageProcess();
             * $fml_id = $ftProcess->addSendMessage($ASNCode);
             * $ftProcess->ftpSendMessage($fml_id);*/
            /*$aMessage['fmt_code'] = 'MRK';
	   		$aMessage['fmt_type'] = 'BSG011';
	   		$aMessage['refercence_no'] = $ASNCode;
	   		$aMessage['fml_status'] = 1;
	   		$aMessage['fml_add_time'] = date('Y-m-d H:i:s');
	   		Service_FtpMessageSendlist::add($aMessage);*/

            self::separateAsn($ASNCode);
            $objOtherCalculte = new Common_CalculateOtherFee();
            if ($receiving['is_delivery'] == '1') {
                //提货的ASN要提货费
                //冻结提货费
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code' => $ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                $otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
                $otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
                //print_r($otherfee_tihuo);
                if ($otherfee_tihuo['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult = $balanceProcess->freezeASNFee($ASNCode, $customerId);
                    if ($feeResult !== true) {
                        throw new Exception($feeResult);
                    }
                }
            }
            if ($receiving['receive_model_type'] == 0) {
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code' => $ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                //入库费
                $otherfeeArr = $objOtherCalculte->getOtherFee('RUKU');
                $otherfee_ruku = $otherfeeArr['data']['otherFee']['ruku'];
                if ($otherfee_ruku['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess($customerId);
                    $feeResult = $balanceProcess->freezeOtherFee($otherfee_ruku['price'], $otherfee_ruku['currency_code'], $ASNCode, $otherfee_ruku['fee_id'], 'ASN提交扣入库费，冻结余额');
                }
                //散租费
                $otherfeeArr = $objOtherCalculte->getOtherFee('SANZU');
                $otherfee_sanzu = $otherfeeArr['data']['otherFee']['sanzu'];
                if ($otherfee_sanzu['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess($customerId);
                    $feeResult = $balanceProcess->freezeOtherFee($otherfee_sanzu['price'], $otherfee_sanzu['currency_code'], $ASNCode, $otherfee_sanzu['fee_id'], 'ASN提交扣散租费，冻结余额');
                }
                //操作费-M
                $otherfeeArr = $objOtherCalculte->getOtherFee('CZF-M');
                $otherfee_czfm = $otherfeeArr['data']['otherFee'][strtolower('CZF-M')];
                if ($otherfee_czfm['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess($customerId);
                    $feeResult = $balanceProcess->freezeOtherFee($otherfee_czfm['price'], $otherfee_czfm['currency_code'], $ASNCode, $otherfee_czfm['fee_id'], 'ASN提交扣操作费-M，冻结余额');
                }
            }
            $result['ask'] = '1';
            $result['message'] = 'ASN审核成功';
            //$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 printAsn($ASNCode = '', $customerId)
    {
        $result = array('ask' => 0, 'message' => '确认失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
        $error = array();
        //print_r($receiving);exit;
        if (empty($receiving)) {
            $error[] = 'ASN无效';
        } else {
            if ($receiving['receiving_status'] != '4') {
                $error[] = 'ASN状态错误';
            }
        }
        if (empty($customerId)) {
            $result['message'] = '客户错误';
            return $result;
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($receiving['customer_id'] != $customerId) {
            $result['message'] = '该ASN和客户不一致';
            return $result;
        }
        $session = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status' => '5',
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("ASN状态更新失败");
            }
            if ($receiving['receive_model_type'] == "1") {
                $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $receiving['receiving_code']), "*");
                foreach ($rod as $rodk => $rodv) {
                    $o = Service_Orders::getByField($rodv['order_code'], "order_code", "*");
                    //$w = Service_Warehouse::getByField($o['warehouse_id'],"warehouse_id","*");
                    $shipOrderTracking = array(
                        'order_code' => $o['order_code'],
                        'sot_location' => "运输途中",
                        'sot_add_time' => date("Y-m-d H:i:s"),
                        'warehouse_id' => $o['warehouse_id'],
                        'sot_description' => '集货ASN运输途中',
                        'sot_type' => '0',
                        'sot_time_offset' => '',
                        'tracking_number' => $o['order_code'],
                        'ref_tracking_number' => '',
                        'status_desc' => '已提交',
                        'user_id' => -1 * $sessionData['id']
                    );
                    Service_ShipOrderTracking::add($shipOrderTracking);
                }
            }

            $conDetail = array(
                'receiving_code' => $ASNCode,
            );
            $receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
            if (!empty($receivingDetail)) {
                foreach ($receivingDetail as $keyde => $valuede) {
                    $product = Service_Product::getByField($valuede['product_id']);

                    $conInventory = array(
                        'customer_id' => $customerId,
                        'product_id' => $valuede['product_id'],
                        'warehouse_id' => $receiving['warehouse_id']
                    );
                    $productInventory = Service_ProductInventory::getByCondition($conInventory);
                    if (empty($productInventory)) {
                        //添加一条product_inventory 记录
                        $productInventoryRow = array(
                            'product_barcode' => $product['product_barcode'],
                            'customer_id' => $customerId,
                            'product_id' => $product['product_id'],
                            'warehouse_id' => $receiving['warehouse_id'],
                            'pi_onway' => $valuede['rd_receiving_qty'],
                            'pi_add_time' => date('Y-m-d H:i:s', time()),
                        );
                        Service_ProductInventory::add($productInventoryRow);
                        $productInventoryLogRow = array(
                            'product_id' => $product['product_id'],
                            'product_barcode' => $product['product_barcode'],
                            'warehouse_id' => $receiving['warehouse_id'],
                            'reference_code' => $valuede['receiving_code'],
                            'user_id' => '-1',
                            'pil_onway' => $valuede['rd_receiving_qty'],
                            'pil_ip' => Common_Common::getIP(),
                            'from_it_code' => 'Audited',
                            'to_it_code' => 'onway',
                            'pil_add_time' => date('Y-m-d H:i:s', time()),
                            'pil_note' => '清单打印',
                            'pil_quantity' => $valuede['rd_receiving_qty'],
                        );
                        Service_ProductInventoryLog::add($productInventoryLogRow);
                    } else {
                        $inventory = $productInventory[0];
                        //修改product_inventory 记录
                        $productInventoryRow = array(
                            'pi_onway' => $valuede['rd_receiving_qty'] + $inventory['pi_onway'],
                            'pi_update_time' => date('Y-m-d H:i:s', time()),
                        );
                        Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
                        $productInventoryLogRow = array(
                            'product_id' => $product['product_id'],
                            'product_barcode' => $product['product_barcode'],
                            'warehouse_id' => $receiving['warehouse_id'],
                            'reference_code' => $valuede['receiving_code'],
                            'user_id' => '-1',
                            'pil_onway' => $valuede['rd_receiving_qty'],
                            'pil_pending' => $inventory['pi_pending'],
                            'pil_sellable' => $inventory['pi_sellable'],
                            'pil_unsellable' => $inventory['pi_unsellable'],
                            'pil_reserved' => $inventory['pi_reserved'],
                            'pil_shipped' => $inventory['pi_shipped'],
                            'pil_ip' => Common_Common::getIP(),
                            'from_it_code' => 'Audited',
                            'to_it_code' => 'onway',
                            'pil_add_time' => date('Y-m-d H:i:s', time()),
                            'pil_note' => '清单打印',
                            'pil_quantity' => $valuede['rd_receiving_qty'],
                        );
                        Service_ProductInventoryLog::add($productInventoryLogRow);
                    }
                    //修改产品的have_asn字段
                    $productRow = array(
                        'have_asn' => '1',
                        'product_update_time' => date('Y-m-d H:i:s')
                    );
                    Service_Product::update($productRow, $valuede['product_id']);
                }
            }

            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type' => '-1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "打印ASN单",
                'rl_status_from' => $receiving['receiving_status'],
                'rl_status_to' => '5',
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            $rab = array(
                'receiving_id' => $receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'onway_time' => date("Y-m-d H:i:s")
            );
            Service_ReceivingAttribute::add($rab);

            $result['ask'] = '1';
            $result['message'] = 'ASN状态更新成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    /**
     * @author william-fan
     * @todo 用于ASn关闭
     */
    public static function closeAssn($rd_id, $customerId)
    {
        $result = array('ask' => 0, 'message' => '关闭失败', 'error' => array());
        $receivingDetail = Service_ReceivingDetail::getByField($rd_id);

        $error = array();
        if (!empty($receivingDetail)) {
            $receiving = Service_Receiving::getByField($receivingDetail['receiving_code'], 'receiving_code');
            if ($receivingDetail['rd_status'] != '1') {
                $error[] = '状态不是收货中不能关闭';
            }
            if ($receiving['receiving_status'] != '6') {
                $error[] = 'ASN状态不是收货中';
                $result['message'] = 'ASN状态不是收货中';
            }
        } else {
            $error[] = '该ASN产品无效';
        }
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        //送货数量和收货数量的差值
        $gapreceives = $receivingDetail['rd_receiving_qty'] - $receivingDetail['rd_received_qty'];
        if ($gapreceives == 0) {
            $result['message'] = '送货数量和收货数量一致,不能关闭';
            return $result;
        }
        if (isset($receiving['customer_id']) && $receiving['customer_id'] != $customerId) {
            $result['message'] = '该ASN和客户不一致';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $datetime = date('Y-m-d H:i:s', time());
            //获取asn产品信息
            $receivingdetails = array(
                'receiving_code' => $receivingDetail['receiving_code']
            );
            $updateReceiving = true; //是否更新ASN状态

            if (count($receivingdetails) > 1) {
                foreach ($receivingdetails as $red => $valred) {
                    if ($valred['rd_id'] != $rd_id) {
                        if ($valred['rd_status'] == '1') {
                            //还有收货中的产品不要更新ASN状态
                            $updateReceiving = false;
                            break;
                        }
                    }
                }
            }
            $receivingDetailRow = array(
                'rd_status' => '1',
                'rd_update_time' => $datetime
            );

            if (Service_ReceivingDetail::update($receivingDetailRow, $rd_id)) {
                //写日志
                $customerRow = Service_Customer::getByField($customerId);
                $ASNLog = array(
                    'receiving_id' => $rd_id,
                    'receiving_code' => $receivingDetail['receiving_code'],
                    'rl_type' => '-1',
                    'user_id' => '-1',
                    'customer_code' => $customerRow['customer_code'],
                    'rl_note' => "关闭ASN产品信息{$receivingDetail['product_barcode']},减少在途库存{$receivingDetail['rd_received_qty']}-{$receivingDetail['rd_received_qty']}",
                    'rl_add_time' => date('Y-m-d H:i:s', time()),
                    'rl_ip' => Common_Common::getIP()
                );
                self::createAsnLog($ASNLog);

                //减少 product_inventory中pi_onway（在途）库存
                $conInventory = array(
                    'customer_id' => $customerId,
                    'product_id' => $receivingDetail['product_id'],
                    'warehouse_id' => $receiving['warehouse_id'],
                );
                /* print_r($conInventory);
		   		exit; */
                $productInventory = Service_ProductInventory::getByCondition($conInventory);//查找product_inventory中该customer_id该产品 该仓储的
                if (!empty($productInventory)) {
                    $productInventoryInfo = $productInventory[0];
                    $productInventoryRow = array(
                        'pi_onway' => $productInventoryInfo['pi_onway'] - $gapreceives,
                        'pi_update_time' => $datetime,
                    );
                    Service_ProductInventory::update($productInventoryRow, $productInventory[0]['pi_id']);

                    $productInventoryLogRow = array(
                        'product_id' => $receivingDetail['product_id'],
                        'product_barcode' => $receivingDetail['product_barcode'],
                        'warehouse_id' => $receiving['warehouse_id'],
                        'pil_onway' => $productInventoryInfo['pi_onway'] - $gapreceives,
                        'from_it_code' => 'onway',
                        'to_it_code' => 'onway',
                        'pil_quantity' => $gapreceives,
                        'application_code' => 'userClose',
                        'pil_add_time' => $datetime,
                        'pil_ip' => Common_Common::getIP(),
                    );
                    Service_ProductInventoryLog::add($productInventoryLogRow);

                    //更新ASN单
                    if ($updateReceiving) {
                        $receivingRow = array(
                            'receiving_status' => '7',
                            'receiving_update_time' => $datetime,
                        );
                        if (!Service_Receiving::update($receivingRow, $receiving['receiving_code'], 'receiving_code')) {
                            throw new Exception("ASN状态更新失败");
                        }
                        $ASNLog = array(
                            'receiving_id' => $receiving['receiving_id'],
                            'receiving_code' => $receiving['receiving_code'],
                            'rl_type' => '-1',
                            'user_id' => '-1',
                            'customer_code' => $customerRow['customer_code'],
                            'rl_note' => "关闭ASN,ASN状态改变",
                            'rl_add_time' => $datetime,
                            'rl_ip' => Common_Common::getIP()
                        );
                        self::createAsnLog($ASNLog);
                    }

                } else {
                    throw new Exception("{$receivingDetail['product_barcode']}无库存信息");
                }

            } else {
                //更新失败
                throw new Exception("关闭失败,ASN详情数据更新失败");
            }

            $result['ask'] = '1';
            $result['message'] = 'ASN确认成功';
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['message'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    /**
     * @author william-fan
     * @todo 移至草稿
     */
    public static function draftAsn($ASNCode = '', $customerId = '')
    {
        $result = array('ask' => 0, 'message' => '移至草稿失败', 'error' => array());
        $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
        $error = array();
        if (empty($receiving)) {
            $error[] = '收货单不存在';
            $return['message'] = $result['message'] . '收货单不存在';
            return $result;
        } else {
            if ($receiving['receiving_status'] != '0' && $receiving['receiving_status'] != '2') {
                $error[] = 'ASN状态错误';
                $return['message'] = $result['message'] . '收货单状态只有删除和确认状态才能移至草稿';
                return $result;
            }
        }
        if (empty($customerId)) {
            $result['message'] = '客户错误';
            $result['message'] = $result['message'] . '客户错误';
            return $result;
        }
        $condition = array('reference_no' => $receiving['reference_no'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7'));
        $receivings = Service_Receiving::getByCondition($condition, '*');
        $receiving = $receivings[0];
        if (!empty($receivings) && $receiving['receiving_code'] != $ASNCode) {
            $result['message'] = "客户参考号已经存在";
            return $result;
        }

        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }

        if ($receiving['customer_id'] != $customerId) {
            $result['message'] = '该收货单不属于当前客户';
            return $result;
        }
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $receivingRow = array(
                'receiving_status' => '1',
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("移至草稿失败");
            }
            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving['receiving_id'],
                'receiving_code' => $ASNCode,
                'rl_type' => '1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_status_from' => $receiving['receiving_status'],
                'rl_status_to' => 1,
                'rl_note' => "ASN移至草稿",
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );

            $conDetail = array(
                'receiving_code' => $ASNCode,
            );
            /*
			$receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
			if(!empty($receivingDetail)){
				foreach ($receivingDetail as $keyde=>$valuede){
					$product = Service_Product::getByField($valuede['product_id']);

					$conInventory = array(
						'customer_id'=>$customerId,
						'product_id'=>$valuede['product_id'],
						'warehouse_id'=>$receiving['warehouse_id']
					);
					$productInventory = Service_ProductInventory::getByCondition($conInventory);
					if(!empty($productInventory)){
						$inventory = $productInventory[0];
						//修改product_inventory 记录
						$productInventoryRow = array(
								'pi_onway'=>$inventory['pi_onway']-$valuede['rd_receiving_qty'],
								'pi_update_time'=>date('Y-m-d H:i:s',time()),
						);
						Service_ProductInventory::update($productInventoryRow, $inventory['pi_id']);
						$productInventoryLogRow = array(
								'product_id'=>$product['product_id'],
								'product_barcode'=>$product['product_barcode'],
								'warehouse_id'=>$receiving['warehouse_id'],
								'user_id'=>'-1',
								'pil_onway'=>$valuede['rd_receiving_qty'],
								'pil_ip'=>Common_Common::getIP(),
						);
						Service_ProductInventoryLog::add($productInventoryLogRow);
					}

					//修改产品的have_asn字段
					$receivingDetails =Service_ReceivingDetail::getByCondition(array('product_id'=>$valuede['product_id']));
					$updateOrders = true; //是否更改产品是否有ASN
					if(!empty($receivingDetail)){
						foreach($receivingDetails as $kde=>$vde){
							$deReceiving = Service_Receiving::getByField($vde['receiving_id']);
							if(!$deReceiving['receiving_code']!==$ASNCode){
								if($deReceiving['receiving_status']!='0' && $deReceiving['receiving_status']!='1'){
									//不为草稿和删除的ASN 产品为有ASN 不能更新
									$updateOrders = false;
									break;
								}
							}
						}
					}

					if($updateOrders){
						$productRow = array(
								'have_asn'=>'0',
								'product_update_time'=>date('Y-m-d H:i:s')
						);
						Service_Product::update($productRow, $valuede['product_id']);
					}

				}
			}
			*/
            self::createAsnLog($ASNLog);
            $result['ask'] = '1';
            $result['message'] = "ASN{$ASNCode}移至草稿失败";
            //$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;
    }

    /**
     * 状态统计
     * @param int $customer_id
     * @param int $$mode_type
     * @param
     */
    public static function statStatus($customer_id, $mode_type, $warehouse_ids)
    {
        $result = array(0 => array());
        $statusText = self::getAsnStatus($mode_type);
        if ($mode_type == 1) unset($statusText['7']);
        else unset($statusText['0'], $statusText['7']);
        $list = Service_Receiving::stat($customer_id, $mode_type);
        foreach ($list as $row) {
            if (!isset($statusText[$row['receiving_status']])) continue;
            $result[$row['warehouse_id']][$row['receiving_status']]['num'] = $row['num'];
        }
        $not_ids = array_diff($warehouse_ids, array_keys($result));
        foreach ($not_ids as $warehouse_id) $result[$warehouse_id] = array();
        foreach ($result as $warehouse_id => $info) {
            foreach ($statusText as $status => $text) {
                if (isset($info[$status])) {
                    $result[$warehouse_id][$status]['text'] = $text;
                } else {
                    $result[$warehouse_id][$status]['num'] = 0;
                    $result[$warehouse_id][$status]['text'] = $text;
                }
                if (!isset($result[0][$status])) {
                    $result[0][$status] = array('text' => $text, 'num' => 0);
                }
                $result[0][$status]['num'] += $result[$warehouse_id][$status]['num'];
            }
            ksort($result[$warehouse_id]);
        }
        return $result;
    }

    public function createJHAsnToDsh($data, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        $session = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();
            $error = self::validate($data, $customerId);
            $errorOrder = self::validOrder($data);
            $errorAll = array_merge($error, $errorOrder['error']);
            if (!empty($errorAll)) {
                $result['error'] = $errorAll;
                $result['detail'] = $errorOrder['detail'];
                throw new Exception("错误");
            }

            $date = date('Y-m-d H:i:s');

            if (isset($data['ref_code']) && $data['ref_code'] != '') {
                $r = self::checkReferenceNo(array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
                if (!empty($r)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'));
                }
            }
            if ($customerId) {
                $this->setCustomer($customerId);
            }
            if ($this->_customerInfo['customer_status'] != 2) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('AccountIsNotActivated'));
            }
            if ($warehouseId) {
                $this->_warehouseId = $warehouseId;
            }

            $ASNCode = self::createCode();
            $receiving['receiving_code'] = $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            $receiving['warehouse_id'] = $warehouseId;
            $receiving['customer_id'] = $customerId;
            $receiving['customer_code'] = $this->_customerInfo['customer_code'];
            $receiving['receiving_type'] = isset($data['receiving_type']) ? $data['receiving_type'] : '0';
            $receiving['receiving_status'] = '1';
            $receiving['receiving_add_time'] = $date;
            $receiving['receiving_update_time'] = date("Y-m-d H:i:s");
            $receiving['is_delivery'] = $data['is_delivery'];
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving ['trade_mode'] = $data ['trade_mode'];
            $receiving ['trans_mode'] = $data ['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];
            //$receiving['netweight']			= $data['netweight'];

            $receiving ['haveconta'] = '0';
            $receiving ['conta_id'] = '';
            $receiving ['conta_model'] = '';
            $receiving ['conta_wt'] = '0';

            $receiving['receive_model_type'] = '1';
            $receiving ['receiving_description'] = $data ['instructions'];

            if (!isset ($receiving ['receiving_type']) || $receiving ['receiving_type'] === '') {
                throw new Exception (Ec_Lang::getInstance()->getTranslate('ASNTypeIsEmpty'));
            }

            if ($warehouseId === '') {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehouseIsEmpty'));
            }
            $warehouse = Common_DataCache::getWareHouse();
            if (!isset($warehouse[$warehouseId])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist'));
            }

            if (!isset($receiving['customer_id']) || $receiving['customer_id'] == '') {
                $receiving['customer_id'] = $this->_customerId;
            }

            $receiving_id = Service_Receiving::add($receiving);

            $asnOrders = $data['asn_order'];
            //$sku =  $data['sku'];
            foreach ($asnOrders as $keyo => $orderCode) {
                //$product = Service_Product::getByField($v,'product_sku');
                $orderInfo = Service_Orders::getByField($orderCode, 'order_code');

                $receiving_order_detail = array(
                    'receiving_id' => $receiving_id,
                    'receiving_code' => $ASNCode,
                    'rd_status' => '0',
                    'order_code' => $orderCode,
                    'rd_add_time' => $date
                );
                $receivingOrderDetailArr[] = $receiving_order_detail;
                if (!Service_ReceivingOrderDetail::add($receiving_order_detail)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
                }
                //修改订单到已提交状态
                $orderRow = array(
                    'order_status' => '4',
                    'update_time' => $date
                );
                Service_Orders::update($orderRow, $orderCode, 'order_code');
                $ol_type = 1;
                if ($orderInfo['order_status'] != 4) {
                    $ol_type = 0;
                }
                $logRow = array(
                    'order_id' => $orderInfo['order_id'],
                    'order_code' => $orderInfo['order_code'],
                    'ol_type' => $ol_type,
                    'order_status_from' => $orderInfo['order_status'],
                    'order_status_to' => 4,
                    'ol_add_time' => date('Y-m-d H:i:s'),
                    'user_id' => '-1',
                    'account_id' => Service_Login::getUserId(),
                    'ol_ip' => Common_Common::getIP()
                );
                Service_OrderLog::add($logRow);

                $w = Service_Warehouse::getByField($orderInfo['warehouse_id'], 'warehouse_id', '*');
                $shipOrderTracking = array(
                    'order_code' => $orderInfo['order_code'],
                    'sot_location' => "客户仓库",
                    'sot_add_time' => date("Y-m-d H:i:s"),
                    'warehouse_id' => $orderInfo['warehouse_id'],
                    'sot_description' => '集货ASN新建成功,集货订单自动提交',
                    'sot_type' => '0',
                    'sot_time_offset' => '',
                    'tracking_number' => $orderInfo['order_code'],
                    'ref_tracking_number' => '',
                    'status_desc' => '已提交',
                    'user_id' => -1 * $sessionData['id']
                );
                Service_ShipOrderTracking::add($shipOrderTracking);

                $orderOperationTime = array(
                    'order_id' => $orderInfo['order_id'],
                    'order_code' => $orderCode,
                    'submit_time' => date("Y-m-d H:i:s"),
                    'submit_user_id' => -1 * $sessionData['id']
                );
                Service_OrderOperationTime::update($orderOperationTime, $orderCode, "order_code");

                //预扣费
                $balanceProcess = new Service_CustomerBalanceProcess();
                $feeResult = $balanceProcess->freezeFee($orderCode, $customerId);
                if ($feeResult !== true) throw new Exception($feeResult);
            }

            $note = 'create ASN';

            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'user_id' => '-1',
                'customer_code' => $this->_customerInfo['customer_code'],
                'rl_note' => $note,
                'rl_add_time' => $date,
                'rl_status_from' => '1',
                'rl_status_to' => '1',
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            if ($receiving['receive_model_type'] == 0) {
                $law_weight = Service_ReceivingDetail::sumLawWeight($ASNCode);
            } else if ($receiving['receive_model_type'] == 1) {

            }
            $law_weight = Service_ReceivingOrderDetail::sumLawWeight($ASNCode);
            if ($law_weight > $receiving['roughweight']) {
                throw new Exception('法定单位为千克的SKU的总重量[' . $law_weight . ']大于ASN毛重[' . $receiving['roughweight'] . ']，请修改SKU的法定单位重量');
            }

            $receivingRow = array(
                'receiving_status' => '2',
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );

            Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code');

            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'rl_type' => '1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "确认ASN单",
                'rl_status_from' => 1,
                'rl_status_to' => '2',
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            $conDetail = array(
                'receiving_code' => $ASNCode,
            );
            $totalWeight = 0;
            $receivingDetail = Service_ReceivingOrderDetail::getByCondition($conDetail);
            if (!empty($receivingDetail)) {
                $totalWeight = 0;
                foreach ($receivingDetail as $keyde => $valuede) {
                    $totalWeight += Service_Orders::calculateWeight($valuede['order_code']);
                }
            }

            $roughweight = $receiving['roughweight'];
            if ($roughweight < $totalWeight) {
                throw new Exception("ASN重量({$roughweight}KG)小于净重({$totalWeight}KG)");
            }

            $receivingRow = array(
                'receiving_status' => '3',    //方便测试暂时为4
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("ASN移至待审核失败");
            }

            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'rl_type' => '-1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "移动ASN至待审核",
                'rl_status_from' => 2,
                'rl_status_to' => '3',    //方便测试暂时为4
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            self::separateAsn($ASNCode);

            if ($receiving['is_delivery'] == '1') {
                //提货的ASN要提货费
                //冻结提货费
                $objOtherCalculte = new Common_CalculateOtherFee();
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code' => $ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                $otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
                $otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
                //print_r($otherfee_tihuo);
                if ($otherfee_tihuo['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult = $balanceProcess->freezeASNFee($ASNCode, $customerId);
                    if ($feeResult !== true) {
                        throw new Exception($feeResult);
                    }
                }
            }

            $result['ask'] = '1';
            $result['msg'] = "收货单号:{$ASNCode}创建成功"; //Ec_Lang::getInstance()->getTranslate('ASNCreatingSuccess'); //'ASN创建成功';
            $result['ASNCode'] = $ASNCode;
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    public function createBHAsnToDsh($data, $customerId = '', $warehouseId = '')
    {
        $result = array('ask' => 0, 'msg' => '', 'error' => array(), 'ASNCode' => '');
        $error = self::validate($data, $customerId);
        if (!empty($error)) {
            $result['error'] = $error;
            return $result;
        }
        $session = new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        try {
            $DB = Common_Common::getAdapter();
            $DB->beginTransaction();

            $date = date('Y-m-d H:i:s');
            if (isset($data['ref_code']) && $data['ref_code'] != '') {
                $r = self::checkReferenceNo(array('reference_no' => $data['ref_code'], 'customer_id' => $customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
                if (!empty($r)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('CustomerReferenceNumberExistence'));
                }
            }
            if ($customerId) {
                $this->setCustomer($customerId);
            }
            if ($this->_customerInfo['customer_status'] != 2) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('AccountIsNotActivated'));
            }
            if ($warehouseId) {
                $this->_warehouseId = $warehouseId;
            }

            $ASNCode = self::createCode();
            $receiving['receiving_code'] = $ASNCode;
            $receiving['reference_no'] = $data['ref_code'];
            $receiving['warehouse_id'] = $warehouseId;
            $receiving['customer_id'] = $customerId;
            $receiving['customer_code'] = $this->_customerInfo['customer_code'];
            $receiving['receiving_type'] = isset($data['receiving_type']) ? $data['receiving_type'] : '0';
            $receiving['receiving_status'] = '1';
            $receiving['receiving_add_time'] = $date;
            $receiving['is_delivery'] = $data['is_delivery'];
            //以下新增的内容
            //$receiving['refercence_form_id']= $data['refercence_form_id'];
            $receiving['ie_port'] = $data['ie_port'];
            $receiving['form_type'] = $data['form_type'];
            $receiving['traf_name'] = $data['traf_name'];
            $receiving['wrap_type'] = $data['wrap_type'];
            $receiving['pack_no'] = $data['pack_no'];
            $receiving['traf_mode'] = $data['traf_mode'];
            $receiving ['trade_mode'] = $data ['trade_mode'];
            $receiving ['trans_mode'] = $data ['trans_mode'];
            $receiving['roughweight'] = $data['roughweight'];

            $receiving ['haveconta'] = '0';
            $receiving ['conta_id'] = '';
            $receiving ['conta_model'] = '';
            $receiving ['conta_wt'] = '0';

            $receiving ['receiving_description'] = $data ['instructions'];
            $receiving['receive_model_type'] = '0';
            if (!isset ($receiving ['receiving_type']) || $receiving ['receiving_type'] === '') {
                throw new Exception (Ec_Lang::getInstance()->getTranslate('ASNTypeIsEmpty'));
            }

            if ($warehouseId === '') {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehouseIsEmpty'));
            }
            $warehouse = Common_DataCache::getWareHouse();
            if (!isset($warehouse[$warehouseId])) {
                throw new Exception(Ec_Lang::getInstance()->getTranslate('WarehousingDoesNotExist'));
            }

            if (!isset($receiving['customer_id']) || $receiving['customer_id'] == '') {
                $receiving['customer_id'] = $this->_customerId;
            }

            $receiving_id = Service_Receiving::add($receiving);

            $product_sku = $data['product_sku'];
            $sku = $data['sku'];
            $haveDeclare = false;
            if (isset($data['declared_value'])) {
                $haveDeclare = true;
                $declare = $data['declared_value'];
            }
            foreach ($product_sku as $k => $v) {
                $productList = Service_Product::getByCondition(array('product_sku' => $v, 'customer_code' => $this->_customerInfo['customer_code']), "*");
                //$product = Service_Product::getByField($v,'product_sku');
                $product = $productList[0];

                if ($haveDeclare) {
                    $declare_vale = $declare[$k];
                } else {
                    $declare_vale = $product['product_declared_value'];
                }
                $receivingDetail = array(
                    'receiving_id' => $receiving_id,
                    'receiving_code' => $ASNCode,
                    'rd_status' => '0',
                    'product_id' => $product['product_id'],
                    'product_barcode' => $product['product_barcode'],
                    'op_declared_value' => trim($declare_vale),
                    'rd_receiving_qty' => trim($sku[$k]),
                    'rd_add_time' => $date
                );
                $receivingDetailArr[] = $receivingDetail;
                if (!Service_ReceivingDetail::add($receivingDetail)) {
                    throw new Exception(Ec_Lang::getInstance()->getTranslate('AddASNDetailsFail'));
                }

            }

            $note = 'create';
            foreach ($receivingDetailArr as $val) {
                $productRow = Service_Product::getByField($val['product_id'], 'product_id', array('product_sku'));
                $note .= ' sku:' . $productRow['product_sku'] . ' quantity:' . $val['rd_receiving_qty'] . ' ';
            }
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'user_id' => '-1',
                'customer_code' => $this->_customerInfo['customer_code'],
                'rl_note' => $note,
                'rl_add_time' => $date,
                'rl_status_from' => '1',
                'rl_status_to' => '1',
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            $receivingRow = array(
                'receiving_status' => '2',
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("ASN确认失败");
            }
            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'rl_type' => '1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "确认ASN单",
                'rl_status_from' => 1,
                'rl_status_to' => '2',
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );
            $conDetail = array(
                'receiving_code' => $ASNCode,
            );
            $receivingDetail = Service_ReceivingDetail::getByCondition($conDetail);
            if (!empty($receivingDetail)) {
                $totalWeight = 0;
                foreach ($receivingDetail as $keyde => $valuede) {
                    $product = Service_Product::getByField($valuede['product_id']);
                    if (empty($product) || $product['product_type'] == '1') {
                        continue;
                    }
                    $totalWeight += $product['product_weight'] * $valuede['rd_receiving_qty'];

                }
            }

            $roughweight = $receiving['roughweight'];
            if ($roughweight < $totalWeight) {
                throw new Exception("ASN重量({$roughweight}KG)小于净重({$totalWeight}KG)");
            }

            self::createAsnLog($ASNLog);

            $receivingRow = array(
                'receiving_status' => '3',    //方便测试暂时为4
                'receiving_update_time' => date('Y-m-d H:i:s', time()),
            );
            if (!Service_Receiving::update($receivingRow, $ASNCode, 'receiving_code')) {
                throw new Exception("ASN移至待审核失败");
            }
            $customerRow = Service_Customer::getByField($customerId);
            $ASNLog = array(
                'receiving_id' => $receiving_id,
                'receiving_code' => $ASNCode,
                'rl_type' => '-1',
                'user_id' => '-1',
                'customer_code' => $customerRow['customer_code'],
                'rl_note' => "移动ASN至待审核",
                'rl_status_from' => 2,
                'rl_status_to' => '3',    //方便测试暂时为4
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);

            self::separateAsn($ASNCode);

            if ($receiving['is_delivery'] == '1') {
                //提货的ASN要提货费
                //冻结提货费
                $objOtherCalculte = new Common_CalculateOtherFee();
                $keys = array(
                    'warehouseId' => $receiving['warehouse_id'],
                    'receiving_code' => $ASNCode,
                );
                $objOtherCalculte->setParams($keys);
                $otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
                $otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
                //print_r($otherfee_tihuo);
                if ($otherfee_tihuo['price'] > 0) {
                    $balanceProcess = new Service_CustomerBalanceProcess();
                    $feeResult = $balanceProcess->freezeASNFee($ASNCode, $customerId);
                    if ($feeResult !== true) {
                        throw new Exception($feeResult);
                    }
                }
            }

            $result['ask'] = '1';
            $result['msg'] = "收货订单[{$ASNCode}]创建成功."; //'ASN创建成功';
            $result['ASNCode'] = $ASNCode;
            //$DB->rollBack();
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        return $result;
    }

    public static function separateAsn($receivingCode)
    {
        $receiving = Service_Receiving::getByField($receivingCode, 'receiving_code', "*");
        if ($receiving['trade_mode'] == "9610" || $receiving['trade_mode'] == "1210") {
            if ($receiving['receive_model_type'] == "1") {
                $goodsIdArr = Service_OrderProduct::getGoodsId($receiving['receiving_code']);
                $sumNetWeight = Service_OrderProduct::calNetWeightByCondition(array('receiving_code' => $receiving['receiving_code']));
            } else {
                $goodsIdArr = Service_ReceivingDetail::getGoodsId($receiving['receiving_code']);
                $sumNetWeight = Service_ReceivingDetail::sumNetWeight($receiving['receiving_code']);
            }
            $goodsIdArr = array_chunk($goodsIdArr, 35);
            $subIndex = 1;
            //$gross_wt = ($receiving['roughweight']-$sumNetWeight)/count($goodsIdArr);
            $totalNetWeight = $sumNetWeight;
            foreach ($goodsIdArr as $gk => $gv) {
                if ($subIndex < 10) {
                    $sub_receiving_code = $receiving['receiving_code'] . "-0" . $subIndex;
                } else {
                    $sub_receiving_code = $receiving['receiving_code'] . "-" . $subIndex;
                }
                $subIndex++;
                $receivingXml = array(
                    'receiving_code' => $receiving['receiving_code'],
                    'sub_receiving_code' => $sub_receiving_code,
                    'gross_wt' => '0',
                    'net_wt' => '0',
                    'pack_no' => '0',
                    'refercence_form_id' => '',
                    'rx_add_time' => date("Y-m-d H:i:s"),
                    'receiving_xml_status' => '3',
                );
                Service_ReceivingXml::add($receivingXml);
                $RXdbObj = new Table_ReceivingXml();
                $rxId = $RXdbObj->getAdapter()->lastInsertId();
                $net_wt = 0;
                //$pack_no = 0;
                $G_NO_index = 1;
                foreach ($gv as $goods_id) {
                    if ($receiving['receive_model_type'] == "1") {
                        $productList = Service_OrderProduct::getJoinProductByCondition(array('goods_id' => $goods_id, 'receiving_code' => $receiving['receiving_code']));
                    } else {
                        $productList = Service_ReceivingDetail::getJoinProductByCondition(array('goods_id' => $goods_id, 'receiving_code' => $receiving['receiving_code']));
                    }
                    $productRow = Service_Product::getByField($productList[0]['product_id'], 'product_id', "*");
                    $currencyRow = Service_Currency::getByField($productRow['currency_code'], 'currency_code', "*");
                    $receivingXmlDetail = array(
                        'rx_id' => $rxId,
                        'from_id' => $receiving['receiving_code'],
                        'sub_receiving_code' => $sub_receiving_code,
                        'g_no' => $G_NO_index,
                        'goods_id' => $productList[0]['goods_id'],
                        'merger_g_no' => $G_NO_index,
                        'code_ts' => $productList[0]['hs_code'],
                        'g_name_cn' => $productList[0]['hs_goods_name'],
                        //'decl_price'=>"",
                        'curr' => $currencyRow['currency_hs_code'],
                        'qty_1' => 0,
                        'unit_1' => '',
                        'qty_2' => '',
                        'unit_2' => '',
                    );

                    $g_qty = 0;
                    $decl_total = 0;
                    $decl_price = 0;
                    foreach ($productList as $p) {
                        if ($receiving['receive_model_type'] == "1") {
                            $quantity = $p['op_quantity'];
                            $g_qty += $p['op_quantity'];
                        } else {
                            $quantity = $p['rd_receiving_qty'];
                            $g_qty += $p['rd_receiving_qty'];
                        }

                        $hemList = Service_HsElementMap::getByCondition(array('product_id' => $p['product_id']), 'hem_detail');
                        $elements = array();

                        foreach ($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
                        $receivingXmlDetail['g_model'] = implode('|', $elements);

                        $hs_uom_map = Service_HsUomMap::getByField($p['product_id'], 'product_id', "*");
                        $quantitylaw1 = isset($hs_uom_map['hum_quantity_law']) ? $hs_uom_map['hum_quantity_law'] : '0';
                        $receivingXmlDetail['qty_1'] += $quantitylaw1 * $quantity;
                        $quantitylaw2 = isset($hs_uom_map['hum_quantity_second']) ? $hs_uom_map['hum_quantity_second'] : "0";
                        $receivingXmlDetail['qty_2'] += $quantitylaw2 * $quantity;
                        if (!empty($hs_uom_map)) $hs_uom = Service_HsUom::getByField($hs_uom_map['hu_id'], 'hu_id', "*");
                        $receivingXmlDetail['unit_1'] = isset($hs_uom['pu_code_law']) ? $hs_uom['pu_code_law'] : "";
                        $receivingXmlDetail['unit_2'] = isset($hs_uom['pu_code_second']) ? $hs_uom['pu_code_second'] : "";
                        $product = Service_Product::getByField($p['product_id'], "product_id", "*");
                        $decl_total += $product['product_declared_value'] * $quantity;
                        $receivingXmlDetail['g_unit'] = $product['pu_code'];

                    }
                    //$pack_no+=$g_qty;
                    $origin_country = "110";
                    if ($receiving['receive_model_type'] == "1") {
                        $ntWeight = Service_OrderProduct::calNetWeightByCondition(array('goods_id' => $goods_id, 'receiving_code' => $receiving['receiving_code']));
                        $getTradeCountry = Service_ReceivingOrderDetail::getTradeCountry($receiving['receiving_code'], $goods_id);
                        if (!empty($getTradeCountry)) $origin_country = $getTradeCountry[0]['trade_country'];
                    } else {
                        $ntWeight = Service_ReceivingDetail::calNetWeightByCondition(array('goods_id' => $goods_id, 'receiving_code' => $receiving['receiving_code']));
                    }
                    $net_wt += $ntWeight;
                    $decl_price = sprintf("%.4f", $decl_total / $g_qty);
                    $receivingXmlDetail['decl_price'] = $decl_price;
                    $receivingXmlDetail['g_qty'] = $g_qty;
                    $receivingXmlDetail['decl_total'] = $decl_total;
                    $receivingXmlDetail['origin_country'] = $origin_country;
                    Service_ReceivingXmlDetail::add($receivingXmlDetail);
                    $G_NO_index++;
                }
                $updateReceivingXml = array(
                    //'gross_wt'=>$net_wt+$gross_wt,
                    'net_wt' => $net_wt,
                    //'pack_no'=>$pack_no,
                );
                Service_ReceivingXml::update($updateReceivingXml, $sub_receiving_code, 'sub_receiving_code');

                $aMessage['fmt_code'] = 'MRK';
                $aMessage['fmt_type'] = 'BSG011';
                $aMessage['refercence_no'] = $sub_receiving_code;
                $aMessage['fml_status'] = 1;
                $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                Service_FtpMessageSendlist::add($aMessage);

            }
            $rxList = Service_ReceivingXml::getByCondition(array('receiving_code' => $receivingCode), "*");
            $growWeight = $receiving['roughweight'];
            $packNo = $receiving['pack_no'];
            $divPackNo = $receiving['pack_no'];
            foreach ($rxList as $kk => $rx) {

                $gross_wt = ($rx['net_wt'] / $totalNetWeight) * $growWeight;
                $rx_pack_no = ($rx['net_wt'] / $totalNetWeight) * $packNo;
                if ($gross_wt <= 1) {
                    $gross_wt = 1;
                }
                if ($kk == count($rxList) - 1) {
                    $rx_pack_no = $divPackNo;
                } else {
                    if ($rx_pack_no <= 1) {
                        $rx_pack_no = 1;
                    } else {
                        $rx_pack_no = floor($rx_pack_no);
                    }
                    $divPackNo = $divPackNo - $rx_pack_no;
                }
                if ($rx_pack_no <= 0) $rx_pack_no = 1;
                $updateReceivingXml = array(
                    'gross_wt' => $gross_wt,
                    //'net_wt'=>$net_wt,
                    'pack_no' => $rx_pack_no,
                );
                Service_ReceivingXml::update($updateReceivingXml, $rx['sub_receiving_code'], 'sub_receiving_code');
            }
        }
    }

    /**
     * [unfreezeFeeSanZu 解冻杂费]
     * @param  [type] $receivingData [description]
     * @param  [type] $otherFeeObj   [description]
     * @param  [type] $otherFeeCode  [description]
     * @return [type]                [description]
     */
    public static function unfreezeFee($receivingData, $otherFeeCode)
    {
        $lowerOtherFeeCode = strtolower($otherFeeCode);
        $keys = array(
            'warehouseId' => (int)$receivingData['warehouse_id'],
            'receiving_weight' => $receivingData['roughweight'],
            'receiving_code' => $receivingData['receiving_code'],
        );
        $objOtherCalculte = new Common_CalculateOtherFee();
        $objOtherCalculte->setParams($keys);
        $otherfeeArr = $objOtherCalculte->getOtherFee($otherFeeCode);
        $otherfeeRow = $otherfeeArr['data']['otherFee'][$lowerOtherFeeCode];
        if ($otherfeeRow['price'] > 0) {
            $otherFeeInfo = Service_OtherFee::getByField($otherFeeCode, 'fee_code');
            //解冻费用
            if (!empty($otherFeeInfo)) {
                $asnOrder = $receivingData;
                $asnOrder['order_code'] = $receivingData['receiving_code'];
                $otherfeeArr = array(
                    'customer_id' => $receivingData['customer_id'],
                    'cbl_type' => '0',
                    'fee_id_gt' => '0',
                    'cbl_refer_code' => $receivingData['receiving_code'],
                    'fee_id' => $otherFeeInfo['fee_id'],
                );
                //查询是其它费用的情况
                $customerBalances = Service_CustomerBalanceLog::getByCondition($otherfeeArr);
                if (!empty($customerBalances)) {
                    foreach ($customerBalances as $customerBalanceRow) {
                        if ($customerBalanceRow['un_cbl_id'] > 0) {
                            continue;
                        }
                        Service_CustomerBalanceProcess::unfreezeOtherFee($asnOrder, $customerBalanceRow, 'ASN删除, 解冻' . $otherFeeInfo['fee_name']);
                    }
                }
            }
        }
    }

    //通过分销平台的接口删除asn
    public static function deleteAsnFromFxInterface($receivingCode, $reason)
    {
        $receivingRow = Service_Receiving::getByField($receivingCode, 'receiving_code', "*");
        $DB = Common_Common::getAdapter();
        $DB->beginTransaction();
        $result = array(
            'ask' => '0',
            'message' => '入区单删除成功',
        );
        try {
            if ($receivingRow['receive_model_type'] == '1') {
                $receivingOrdersCondition = array(
                    'receiving_code' => $receivingCode,
                );
                $receivingOrders = Service_ReceivingOrderDetail::getByCondition($receivingOrdersCondition);
                if (!empty($receivingOrders)) {
                    foreach ($receivingOrders as $ko => $vo) {
                        $orderRow = Service_Orders::getByField($vo['order_code'], 'order_code', "*");
                        $upOrderRow = array(
                            'order_status' => '2',
                        );
                        if ($orderRow['sm_code'] == "UKTL" || $orderRow['sm_code'] == "SZY-EUB" || $orderRow['sm_code'] == "SZY-ETK" || $orderRow['sm_code'] == "WG-EUB") {
                            $upOrderRow['ref_tracking_number'] = "";
                        }
                        Service_Orders::update($upOrderRow, $vo['order_code'], 'order_code');
                        $logRow = array(
                            'order_id' => $orderRow['order_id'],
                            'order_code' => $vo['order_code'],
                            'ol_type' => 0,
                            'order_status_from' => $orderRow['order_status'],
                            'order_status_to' => 2,
                            'ol_add_time' => date('Y-m-d H:i:s'),
                            'user_id' => '-1',
                            'ol_comments' => '通过接口删除ASN:' . $reason,
                            'account_id' => Service_Login::getUserId(),
                            'ol_ip' => Common_Common::getIP()
                        );
                        Service_OrderLog::add($logRow);
                        $balanceProcess = new Service_CustomerBalanceProcess();
                        $feeResult = $balanceProcess->unfreezeFee($vo['order_code'], 'ASN删除,解冻金额');
                    }
                    Service_ReceivingOrderDetail::delete($receivingCode, 'receiving_code');
                } else {
                    throw new Exception("ASN和订单关联不存在");
                }
            }
            //$objOtherCalculte = new Common_CalculateOtherFee();
            if ($receivingRow['is_delivery'] == '1') {
                self::unfreezeFee($receivingRow, 'TIHUO');
            }
            if ($receivingRow['receive_model_type'] == 0) {
                //解冻入库费
                self::unfreezeFee($receivingRow, 'RUKU');
                //解冻散租费
                self::unfreezeFee($receivingRow, 'SANZU');
            }
            $update = array(
                'receiving_status' => 0,
            );
            Service_Receiving::update($update, $receivingCode, "receiving_code");
            $ASNLog = array(
                'receiving_id' => $receivingRow['receiving_id'],
                'receiving_code' => $receivingCode,
                'rl_type' => '1',
                'user_id' => '-1',
                'customer_code' => $receivingRow['customer_code'],
                'rl_add_time' => date('Y-m-d H:i:s', time()),
                'rl_status_from' => $receivingRow['receiving_status'],
                'rl_status_to' => 0,
                'rl_ip' => Common_Common::getIP()
            );
            self::createAsnLog($ASNLog);
            $DB->commit();
            $result['ask'] = 1;
        } catch (Exception $e) {
            $DB->rollBack();
            $result['ask'] = 0;
            $result['message'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * @获取不合并的数据
     */
    public static function getAsnInfoNotMerge($asnCode, $customerCode = '')
    {
        $result = array('ask' => 0, 'message' => '', 'Error' => array(), 'result' => array());
        $asnRow = Service_Receiving::getByField($asnCode, 'receiving_code');
        if (empty($asnRow) || $asnRow['customer_id'] != $customerCode) {
            $result['message'] = 'AsnCode:' . $asnCode . '不存在';
            $result['Error'][] = array('errorCode' => '20013', 'errorMessage' => 'AsnCode:' . $asnCode . ' can not be found.');
            return $result;
        }

        $asnDetail = array();
        if ($asnRow['receive_model_type'] == '1') {
            $orderCodes = Service_ReceivingOrderDetail::getOrderCodes($asnCode);
            $asnDetail = Service_ReceivingOrderDetail::getXmlProducts($orderCodes, $asnCode);
            $asnRow['net_weight'] = number_format(Service_ReceivingOrderDetail::sumNetWeight($asnCode), 2, '.', '');
        } else {
            $asnDetail = Service_ReceivingDetail::getXmlProductsNotMerge($asnCode);
            $asnRow['net_weight'] = number_format(Service_ReceivingDetail::sumNetWeight($asnCode), 2, '.', '');
        }
        $productList = array();
        foreach ($asnDetail as $info) {
            $hemList = Service_HsElementMap::getByCondition(array('product_id' => $info['product_id']), 'hem_detail');
            $elements = array();
            foreach ($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
            $info['product_model'] = implode('|', $elements);
            $info['quantity_law'] = round($info['hum_quantity_law'] * $info['quantity'], 4);
            $total_price = sprintf("%.4f", $info['total_price']);
            //$info['product_unit_price'] = sprintf("%.4f", $info['product_declared_value']/$info['hum_quantity_law']);
            $info['product_unit_price'] = sprintf("%.4f", $total_price / $info['quantity_law']);
            $info['quantity_second'] = $info['pu_code_second'] ? round($info['hum_quantity_second']* $info['quantity'], 4) : '';
            //$info['product_total_price'] = sprintf("%.2f", $info['product_declared_value']*$info['quantity']);
            $info['product_total_price'] = $total_price;
            $productList[] = $info;
        }

        $warehouseAll = Common_DataCache::getWareHouse();
        $warehouseCode = $warehouseAll[$asnRow['warehouse_id']]['warehouse_code'];
        $asnRow['warehouse_name'] = $warehouseCode;
        $asnRow['form_id'] = $asnRow['receiving_code'];
        $asnData = array(
            'asnRow' => $asnRow,
            'ASNCode' => $asnRow['receiving_code'],
            'addTime' => $asnRow['receiving_add_time'],
            'lastModifyTime' => $asnRow['receiving_update_time'],
            'warehouseCode' => $warehouseCode,
            'ASNDetail' => $productList,
        );
        $result['result'] = $asnData;
        $result['ask'] = 1;
        return $result;
    }

    /**
     * @todo 生成报关单草单
     * $mergebygoods 1:合并料号,2不合并料号
     */
    public static function downTemplateBaoguan($ASNCode,$customerId='',$mergebygoods='1'){
        $result = array(
            'state'=>0,
            'message'=>'',
            'data'=>'',
        );
        try{
            $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
            if($receiving['receiving_status']!='2'){
                throw new Exception("入库单状态不对");
            }
            $error = array();
            if (empty($receiving)) {
                $error[] = '收货单不存在';
                $result['message'] = $result['message'] . '收货单不存在';
                return $result;
            } else {
                if ($receiving['receiving_status'] != '0' && $receiving['receiving_status'] != '2') {
                    $error[] = 'ASN状态错误';
                    $return['message'] = $result['message'] . '收货单状态只有删除和确认状态才能移至草稿';
                    return $result;
                }
            }
            if (empty($customerId)) {
                $result['message'] = '客户错误';
                $result['message'] = $result['message'] . '客户错误';
                return $result;
            }

            if($mergebygoods=='1'){
                $asnInfo = Service_AsnProccess::getAsnInfo($ASNCode, $customerId);
            }else{
                //不通过料号合并商品
                //echo "not merge";
                $asnInfo = Service_AsnProccess::getAsnInfoNotMerge($ASNCode, $customerId);
            }
            if($asnInfo['ask']=='1'){
                $result['state'] = 1;
                $result['data'] = $asnInfo['result'];
            }else{
                $result['message'] = implode("|",$asnInfo['Error']);
            }
        }catch (Exception $e){
            $result['message'] = $e->getMessage();
        }
        return $result;
    }
    /**
     * @todo 上传的报关单草单
     */
    public static function uploadTempleteBaoguan(){

    }
}

?>