<?php

class Merchant_ReceivingController extends Ec_Controller_Action
{

    public function preDispatch()
    {
        $this->tplDirectory = "merchant/views/receiving/";
        $this->customerAuth = new Zend_Session_Namespace("customerAuth");
        //print_r($this->customerAuth);
        //$this->customerId = Service_Login::getLoginInfo()->customer['customer_id'];
        $this->customerId = $this->_customerAuth['id'];
    }

    public function indexAction()
    {
        $this->listbhAction();
    }

    /**
     * @author william-fan
     * @todo  创建ASN 及 编辑ASN （备货模式）
     */
    public function createAction()
    {
        if (Service_Customer::checkIsService()) {
            $this->_redirect('/merchant/receiving/service-create');
        }
        set_time_limit(0);
        $customer = $this->_customerAuth;
        $ASNCode = $this->_request->getParam('ASNCode', '');
        $warehouseAll = Common_DataCache::getWarehouse();
        $warehouse = array();
        foreach ($warehouseAll as $key => $val) {
            $warehouse[$val['warehouse_id']] = $val['warehouse_code'];
        }
        $result = array(
            'ask' => '0',
            'msg' => '',
            'ASNCode' => '',
            'navTabId' => 'asnAdd',
            'callbackType' => 'forward',
            'forwardUrl' => '/merchant/receiving/list'
        );
        $customerId = $customer['id'];
        if ($this->_request->isPost()) {
            $data = $this->getRequest()->getParams();
            if ($data) {
                foreach ($data as $k => &$v) {
                    if (!is_array($v)) {
                        $v = trim($v);
                    }
                }

            }


            $ASNObj = new Service_AsnProccess('ZHR');
            //receive_model_type 收货类型
            $receive_model_type = $this->_request->getParam('receive_model_type', '0');


            //$validate = $ASNObj->validate($data);

            //print_r($data);exit;
            if (empty($ASNCode)) {
                if ($receive_model_type == '0') {
                    //备货模式
                    //$data['receiving_add_time'] = date('Y-m-d H:i:s');
                    //$data['receiving_update_time'] = date('Y-m-d H:i:s');
                    $doresult = $ASNObj->createTransaction($data, $customerId, $data['warehouseId']);
                } else {
                    //集货模式
                    ///$data['receiving_add_time'] = date('Y-m-d H:i:s');
                    //$data['receiving_update_time'] = date('Y-m-d H:i:s');
                    $doresult = $ASNObj->createjihuoTransaction($data, $customerId, $data['warehouseId']);
                    //exit('cc');
                }
            } else {
                $order['receiving_code'] = $ASNCode;
                if ($receive_model_type == '0') {
                    //备货模式
                    //$data['receiving_add_time'] = date('Y-m-d H:i:s');
                    //$data['receiving_update_time'] = date('Y-m-d H:i:s');
                    $doresult = $ASNObj->updateTransaction($data, $customerId, $data['warehouseId']);
                } else {
                    //集货模式
                    //$data['receiving_add_time'] = date('Y-m-d H:i:s');
                    //$data['receiving_update_time'] = date('Y-m-d H:i:s');
                    $doresult = $ASNObj->updatejihuoTransaction($data, $customerId, $data['warehouseId']);
                }
            }
            //print_r($doresult);
            if (isset($doresult['msg'])) {
                $result['msg'] = $doresult['msg'];
            }
            $result['error'] = $doresult['error'];
            $result['ask'] = $doresult['ask'];
            $result['ASNCode'] = $doresult['ASNCode'];
            //print_r($result);
            //$this->view->infoArray =  $result;
            //print_r($result);exit;
            die(json_encode($result));
        }
        $ecg_category = Common_DataCache::getProductCategory();
        $this->view->ecg_category = $ecg_category;
        $this->view->warehouseArr = $warehouse;
        $this->view->receiving_code = $ASNCode;

        $receivingDetail = array();
        $tpl = 'receiving-create.tpl';
        if (!empty($ASNCode)) {
            $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
            if (!empty($receiving)) {
                //receiving_detail
                $con = array(
                    'receiving_code' => $ASNCode,
                );
                if ($receiving['receive_model_type'] == '1') {
                    $receivingDetail = Service_ReceivingOrderDetail::getByCondition($con);
                    if (!empty($receivingDetail)) {
                        foreach ($receivingDetail as $kre => $vre) {
                            $orderInfo = Service_Orders::getByField($vre['order_code'], 'order_code');
                            if (!empty($orderInfo)) {
                                $orderAddressBook = Service_OrderAddressBook::getByField($orderInfo['order_id'], 'order_id');
                                if (!empty($orderAddressBook)) {
                                    $country = Service_Country::getByField($orderAddressBook['oab_country_id']);
                                    $orderInfo['country_name'] = $country['country_name'];
                                }
                                $receivingDetail[$kre] = array_merge($vre, $orderInfo);
                            }
                            /* $receivingDetail[$kre]['product_sku'] = $orderInfo['product_sku'];
                            $receivingDetail[$kre]['product_title'] = $product['product_title'];
                            $receivingDetail[$kre]['category_name'] = $product['category_name']; */
                        }
                    }
                } else {
                    $receivingDetail = Service_ReceivingDetail::getByCondition($con);
                    if (!empty($receivingDetail)) {
                        foreach ($receivingDetail as $kre => $vre) {
                            $product = Common_DataCache::getProduct($vre['product_id'], $customerId);
                            $receivingDetail[$kre]['product_sku'] = $product['product_sku'];
                            $receivingDetail[$kre]['product_title'] = $product['product_title'];
                            $receivingDetail[$kre]['category_name'] = $product['category_name'];
                            $receivingDetail[$kre]['product_weight'] = $product['product_weight'];
                        }
                    }
                }

                $this->view->modify = '1';
            }
            //print_r($receiving);exit;
            $this->view->receiving = $receiving;

        }
        $ordermodel = $this->_request->getParam('receivemodel', '');
        $type = $this->_request->getParam('type', '');

        $modelTitle = '';
        if ($type == 'getTpl') {
            if ($ordermodel == 1) {
                $modelTitle = "-集货模式";
            }
            if ($ordermodel == 0) {
                $modelTitle = "-备货模式";
            }
        }

        if ($ASNCode) {
            $this->view->actions = Ec_Lang::getInstance()->getTranslate('editAsn') . $modelTitle;//"修改";
            $this->view->actionLabel = "update";
        } else {
            $this->view->actions = Ec_Lang::getInstance()->getTranslate('ASNAdd') . $modelTitle;//"新增";
            $this->view->actionLabel = "add";
        }

        //以下内容为新增的
        //$iePorts = Service_IePort::getAll();
        $iePorts = Service_IePort::getByCondition();
        $this->view->iePorts = $iePorts;
        $conformtypes = array(
            'is_display' => '1',
            'ie_flag' => 'I',
        ); //只找给前台显示的
        $formtypes = Service_FormType::getByCondition($conformtypes);

        $this->view->formtypes = $formtypes;

        $wrapTypes = Service_WrapType::getAll(); //包装种类
        $this->view->wrapTypes = $wrapTypes;

        $contrafModes = array(
            'is_display' => '1'
        );
        $trafModes = Service_TrafMode::getByCondition($contrafModes); //出入港区运输方式
        $this->view->trafModes = $trafModes;

        $contradeModes = array(
            'is_display' => '1'
        );
        $tradeModes = Service_TradeMode::getByCondition($contradeModes); //监管方式
        $this->view->tradeModes = $tradeModes;

        $transModes = Service_TransMode::getByCondition(array('is_display' => '1')); //成交方式
        $this->view->transModes = $transModes;

        //环球创建入库单时会把SKU放到URL上
        $skuFromUrl = $this->_request->getParam('sku', array());
        if (!empty($skuFromUrl)) {
            $this->customerAuth->skuFromUrl = $skuFromUrl;
        }
        $m = $this->_request->getParam('m', '');//来源于URL，用于入库单是备货还是集货，目前这个参数只用于环球
        //print_r($transModes);
        if ($type == 'getTpl') {
            if ($ordermodel == '0') {
                $tpl = 'bh-receiving-create.tpl';
                $skuError = array();
                $skuFromUrl = $this->customerAuth->skuFromUrl;
                $this->customerAuth->skuFromUrl = array();//用完就清除
                if ($skuFromUrl) {
                    foreach ($skuFromUrl as $value) {
                        $tempProduct = Service_Product::getByCondition(array('product_sku' => $value, 'customer_id' => $customerId));
                        if (empty($tempProduct)) {
                            $skuError[] = 'sku:' . $value . '不存在';
                        } else if (!in_array($tempProduct[0]['product_type'], array('0'))) {
                            $skuError[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('ProductTypeError');
                        } else if ($tempProduct[0]['product_status'] != '1') {
                            $skuError[] = "product sku:[{$v}] " . Ec_Lang::getInstance()->getTranslate('ProductStatusError');
                        } else {
                            $receivingDetail[] = array(
                                'product_id' => $tempProduct[0]['product_id'],
                                'product_sku' => $tempProduct[0]['product_sku'],
                                'product_title' => $tempProduct[0]['product_title'],
                                'category_name' => $tempProduct[0]['category_name'],
                                'product_sku' => $tempProduct[0]['product_sku'],
                                'product_weight' => $tempProduct[0]['product_weight'],
                                'op_declared_value' => $tempProduct[0]['product_declared_value'],
                                'rd_receiving_qty' => 1,
                            );
                        }
                    }
                }

                $this->view->noTab = Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner($this->customerAuth->data['code']) ? 1 : 0;//先这样写，暂时只有环球是这样的,用于创建ASN成功后跳转到列表
                $this->view->diabledPicking = Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner($this->customerAuth->data['code']) ? true : false;
                $this->view->isHuanQiu = Service_CustomerProcess::$HuanQiu == Service_CustomerProcess::getOwner($this->customerAuth->data['code']) ? true : false;
                $this->view->skuError = implode('<br/>', $skuError);
            } elseif ($ordermodel == '1') {
                $tpl = 'jh-receiving-create.tpl';
            } else {
                exit(Ec_Lang::getInstance()->getTranslate('DataError'));
            }
            $this->view->receivingDetail = $receivingDetail;
            echo $this->view->render($this->tplDirectory . $tpl);
            exit;
        } else {
            $this->view->m = $m;
            echo Ec::renderTpl($this->tplDirectory . $tpl, 'noleftlayout');
        }
    }

    /*
     * 服务商创建ASn
     */
    public function serviceCreateAction()
    {
        set_time_limit(0);
        $ASNCode = $this->_request->getParam('ASNCode', '');
        $warehouseAll = Common_DataCache::getWarehouse();
        $selectCustomer = $this->_request->getParam('custome_code');
        $warehouse = array();
        foreach ($warehouseAll as $key => $val) {
            $warehouse[$val['warehouse_id']] = $val['warehouse_code'];
        }
        $result = array(
            'ask' => '0',
            'msg' => '',
            'ASNCode' => '',
            'navTabId' => 'asnAdd',
            'callbackType' => 'forward',
            'forwardUrl' => '/merchant/receiving/list'
        );
        $customerId = $this->_request->getParam('selectCustomer');
        if ($this->_request->isPost()) {
            try {
                $DB = Common_Common::getAdapter();
                $DB->beginTransaction();
                $poProcess = new Service_PoOrderProcess();
                $data = $this->getRequest()->getParams();
                if ($data) {
                    foreach ($data as $k => &$v) {
                        if (!is_array($v)) {
                            $v = trim($v);
                        } else {
                            $v = array_map('trim', $v);
                        }
                    }

                }
                $postPoData = $poProcess->dealPostData($data);
                $msg = $poProcess->validator($postPoData);

                if ($msg !== true) {
                    throw new Exception($msg['p_list']);
                }
                $insertId = $poProcess->createPoOrderTracking($postPoData);
                $ASNObj = new Service_AsnProccess('ZHR');
                //receive_model_type 收货类型
                $receive_model_type = $this->_request->getParam('receive_model_type', '0');
                if (empty($ASNCode)) {
                    //备货模式默认
//            	if($receive_model_type=='0'){
                    $doresult = $ASNObj->createPoAsn($data, $insertId, $customerId, $data['warehouseId']);
//            	}else{
//            		$doresult = $ASNObj->createjihuoTransaction($data, $customerId, $data['warehouseId']);
//            	}
                } else {
                    throw new Exception('非法操作');
                    /*
                    $order['receiving_code'] = $ASNCode;
                    if($receive_model_type=='0'){
                        //备货模式
                        //$data['receiving_add_time'] = date('Y-m-d H:i:s');
                        //$data['receiving_update_time'] = date('Y-m-d H:i:s');
                        $doresult = $ASNObj->updateTransaction($data, $customerId, $data['warehouseId']);
                    }else{
                        //集货模式
                        //$data['receiving_add_time'] = date('Y-m-d H:i:s');
                        //$data['receiving_update_time'] = date('Y-m-d H:i:s');
                        $doresult = $ASNObj->updatejihuoTransaction($data, $customerId, $data['warehouseId']);
                    }
                     * */
                }
                //print_r($doresult);
                if (isset($doresult['msg'])) {
                    $result['msg'] = $doresult['msg'];
                }
                $result['error'] = $doresult['error'];
                $result['ask'] = $doresult['ask'];
                $result['ASNCode'] = $doresult['ASNCode'];
                if ($result['ask'] == 1) {
                    $DB->commit();
                }
            } catch (Exception $e) {
                $result['error'] = array($e->getMessage());
                $DB->rollBack();
            }
            //print_r($result);
            //$this->view->infoArray =  $result;
            //print_r($result);exit;
            die(json_encode($result));
        }
        $ecg_category = Common_DataCache::getProductCategory();
        $this->view->ecg_category = $ecg_category;
        $this->view->warehouseArr = $warehouse;
        $this->view->receiving_code = $ASNCode;

        $receivingDetail = '';
        $tpl = 'po-receiving-create.tpl';
        if (!empty($ASNCode)) {
            $receiving = Service_Receiving::getByField($ASNCode, 'receiving_code');
            if (!empty($receiving)) {
                //receiving_detail
                $con = array(
                    'receiving_code' => $ASNCode,
                );
                if ($receiving['receive_model_type'] == '1') {
                    $receivingDetail = Service_ReceivingOrderDetail::getByCondition($con);
                    if (!empty($receivingDetail)) {
                        foreach ($receivingDetail as $kre => $vre) {
                            $orderInfo = Service_Orders::getByField($vre['order_code'], 'order_code');
                            if (!empty($orderInfo)) {
                                $orderAddressBook = Service_OrderAddressBook::getByField($orderInfo['order_id'], 'order_id');
                                if (!empty($orderAddressBook)) {
                                    $country = Service_Country::getByField($orderAddressBook['oab_country_id']);
                                    $orderInfo['country_name'] = $country['country_name'];
                                }
                                $receivingDetail[$kre] = array_merge($vre, $orderInfo);
                            }
                            /* $receivingDetail[$kre]['product_sku'] = $orderInfo['product_sku'];
                            $receivingDetail[$kre]['product_title'] = $product['product_title'];
                            $receivingDetail[$kre]['category_name'] = $product['category_name']; */
                        }
                    }
                } else {
                    $receivingDetail = Service_ReceivingDetail::getByCondition($con);
                    if (!empty($receivingDetail)) {
                        foreach ($receivingDetail as $kre => $vre) {
                            $product = Common_DataCache::getProduct($vre['product_id'], $customerId);
                            $receivingDetail[$kre]['product_sku'] = $product['product_sku'];
                            $receivingDetail[$kre]['product_title'] = $product['product_title'];
                            $receivingDetail[$kre]['category_name'] = $product['category_name'];
                            $receivingDetail[$kre]['product_weight'] = $product['product_weight'];
                        }
                    }
                }

                $this->view->modify = '1';
            }
            //print_r($receiving);exit;
            $this->view->receiving = $receiving;

        }
        $ordermodel = $this->_request->getParam('receivemodel', '');
        $type = $this->_request->getParam('type', '');

        $modelTitle = '';
        if ($type == 'getTpl') {
            $modelTitle = "-备货模式";
        }

        if ($ASNCode) {
            $this->view->actions = Ec_Lang::getInstance()->getTranslate('editAsn') . $modelTitle;//"修改";
            $this->view->actionLabel = "update";
        } else {
            $this->view->actions = Ec_Lang::getInstance()->getTranslate('ASNAdd') . $modelTitle;//"新增";
            $this->view->actionLabel = "add";
        }

        /* echo '<pre>';
        print_r($receivingDetail);
        echo '</pre>'; */
        $this->view->receivingDetail = $receivingDetail;

        //以下内容为新增的
        //$iePorts = Service_IePort::getAll();
        $iePorts = Service_IePort::getByCondition($condition = array('ie_port' => '5349'));
        $this->view->iePorts = $iePorts;
        $conformtypes = array(
            'is_display' => '1'
        ); //只找给前台显示的
        $formtypes = Service_FormType::getByCondition($conformtypes);

        $this->view->formtypes = $formtypes;

        $wrapTypes = Service_WrapType::getAll(); //包装种类
        $this->view->wrapTypes = $wrapTypes;

        $contrafModes = array(
            'is_display' => '1'
        );
        $trafModes = Service_TrafMode::getByCondition($contrafModes); //出入港区运输方式
        $this->view->trafModes = $trafModes;

        $contradeModes = array(
            'is_display' => '1'
        );
        $tradeModes = Service_TradeMode::getByCondition($contradeModes); //监管方式
        $this->view->tradeModes = $tradeModes;

        $transModes = Service_TransMode::getByCondition(array('is_display' => '1')); //成交方式
        $this->view->transModes = $transModes;
        $customerListCondition = array(
            'customer_type' => '0',
            'customer_status' => '2',
        );
        $this->view->customeList = Service_Customer::getByCondition($customerListCondition, array('customer_code', 'customer_company_name', 'customer_id'));
        //print_r($transModes);
        if ($type == 'getTpl') {
            if ($ordermodel == '0') {
                $tpl = 'po-bh-receiving-create.tpl';
            } else {
                exit(Ec_Lang::getInstance()->getTranslate('DataError'));
            }
            $this->view->selectCustomer = Service_Customer::getByField($selectCustomer, 'customer_code');
            echo $this->view->render($this->tplDirectory . $tpl);
            exit;
        } else {
            echo Ec::renderTpl($this->tplDirectory . $tpl, 'noleftlayout');
        }
    }

    /*
     * 寄存ASN数据
     */
    public function validateAction()
    {
        $appType = $this->_request->getParam('type', 2);
        $params = array();
        if ($this->_request->isPost()) {
            $params = $this->getRequest()->getParams();
        }
        $result = Merchant_Service_AsnProccess::getTemp($appType, $params);
        die(json_encode($result));
    }

    /*
     * 验证参考号
     * @return ask,msg
     */
    public function checkRefcodeAction()
    {
        $result = array('ask' => '1', 'msg' => 'Success');
        if ($this->_request->isPost()) {
            $refCode = $this->_request->refCode;
            $ASNCode = $this->_request->ASNCode;

            $asn_arrays = Service_AsnProccess::checkReferenceNo(array('reference_no' => $refCode, 'customer_id' => $this->customerId, 'receiving_status_arr' => array('1', '2', '3', '4', '5', '6', '7')));
            //如果存在
            if ($asn_arrays) {
                if ($ASNCode) {
                    foreach ($asn_arrays as $row) {
                        if ($row['receiving_code'] != $ASNCode) {
                            $result = array('ask' => '0', 'msg' => '客户参考号存在!');
                            break;
                        }

                    }    //if($ASNCode){


                } else {    //if($ASNCode){
                    $result = array('ask' => '0', 'msg' => '客户参考号存在!');
                }
            } else {//如果不重复，则提示OK
                $result = array('ask' => '1', 'msg' => 'Success');
            }//if($asn_arrays)
        }
        die(json_encode($result));
    }

    /**
     * @author william-fan
     * @todo ASN 列表(备货模式)
     */
    public function listbhAction()
    {
        $customer = $this->_customerAuth;
        $allStatus = Service_AsnProccess::getAsnStatus();
        $allType = Service_AsnProccess::getAsnType();
        $warehouseAll = Common_DataCache::getWarehouse();
        $warehouse = array();
        foreach ($warehouseAll as $key => $val) {
            $warehouse[$val['warehouse_id']] = $val['warehouse_code'];
        }
        //if ($this->_request->isPost()) {
        //$customerId = $this->customerId;
        $customerId = $customer['id'];
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);

        $AsnCode = trim($this->_request->getParam('receiving_code', ''));
        $receiving_status = $this->_request->getParam('receiving_status', '1');
        $trackingNumber = trim($this->_request->getParam('tracking_number', ''));
        $receivingType = $this->_request->getParam('ASNType', '');
        $refCode = trim($this->_request->getParam('reference_no', ''));
        $warehouseId = $this->_request->getParam('warehouseId', '');

        $created_start = trim($this->_request->getParam('created_start', ''));
        $created_end = trim($this->_request->getParam('created_end', ''));
        //echo $created_end;
        $created_start = ($created_start) ? $created_start . ' 00:00:00' : '';
        $created_end = ($created_end) ? $created_end . ' 59:59:59' : '';
        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 20;
        $condition = array(
            'receiving_code' => $AsnCode,
            'receiving_status' => $receiving_status,
            'tracking_number_like' => $trackingNumber,
            'receiving_type' => $receivingType,
            'reference_no' => $refCode,
            'warehouse_id' => $warehouseId,
            'customer_id' => $customerId,
            'created_start' => $created_start,
            'created_end' => $created_end,
            'receive_model_type' => '0',
        );
        if (Service_Customer::checkIsService()) {
            unset($condition['customer_id']);
            $condition['supplier_id'] = $customer['id'];
        }
        //print_r($condition);
        //$return = array('ask' => '0', 'msg' => 'No Data.', 'count' => 0, 'result' => array());
        $count = Service_Receiving::getByCondition($condition, 'count(*)');
        //$return['status'] = Service_Receiving::getCustomerAsnStatusGroup($condition);
        $result = '';
        if ($count > 0) {
            $cacheProduct = array();
            $result = Service_Receiving::getByCondition($condition, '*', $pageSize, $page, array('receiving_id desc'));
            foreach ($result as $key => $val) {
                $result[$key]['statustext'] = $allStatus[$val['receiving_status']];
                $result[$key]['warehouse'] = $warehouse[$val['warehouse_id']];
                $result[$key]['typetext'] = $allType[$val['receiving_type']];
                $asnItem = Service_ReceivingDetail::getByCondition(array('receiving_code' => $val['receiving_code']), '*');
                $products = array();
                foreach ($asnItem as $p) {
                    if (isset($cacheProduct[$p['product_id']])) {
                        $product = $cacheProduct[$p['product_id']];
                    } else {
                        $product = Service_Product::getByField($p['product_id'], 'product_id');
                        if ($product['pc_id']) {
                            $category = Common_DataCache::getProductCategory($product['pc_id']);
                        }
                        /* print_r($category);
                        exit; */
                        $product['category_name'] = !empty($category) ? $category['pc_name'] : '--';
                        /* $product['op_quantity'] = $p['order_qty'];
                        $product['putaway'] = $p['putaway_qty'];
                        $product['received'] = $p['received_qty'];
                        $product['problem'] = $p['problem_qty']; */
                        //$product['weight'] = $p['weight'];
                        $cacheProduct[$p['product_id']] = $product;
                    }

                    $products[] = $product;
                }
                $result[$key]['asnItem'] = $products;
            }
            /* echo '<pre>';
            print_r($result);
            echo '</pre>'; */
        }

        //print_r($allStatus);
        //处理数量问题
        if (!empty($allStatus)) {
            $numConditon = $condition;
            foreach ($allStatus as $keys => $values) {
                $numConditon['receiving_status'] = $keys;
                $countstatus = Service_Receiving::getByCondition($numConditon, 'count(*)');
                $allStatus[$keys] = $values . "({$countstatus})";
            }
        }

        //print_r($condition);

        //print_r($return);
        $this->view->page = $page;
        $this->view->pageSize = $pageSize;
        $this->view->count = $count;

        //die(Zend_Json::encode($return));
        //}
        $this->view->AsnTypeArr = $allType;
        $this->view->AsnStatusArr = $allStatus;
        $this->view->warehouseArr = $warehouse;
        $this->view->result = $result;
        //重构时间
        $condition['created_end'] = $this->_request->getParam('created_end', '');
        $condition['created_start'] = $this->_request->getParam('created_start', '');
        $this->view->params = $condition;
        $this->view->nt = $this->_request->getParam('nt', '');//是否在框架内，目前环球需要这样弄。
        echo Ec::renderTpl($this->tplDirectory . "bh-receiving-list.tpl", 'noleftlayout');
    }

    /**
     * @author william-fan
     * @todo 集货模式的订单
     */
    public function listjhAction()
    {
        $customer = $this->_customerAuth;
        $allStatus = Service_AsnProccess::getAsnStatus();
        $allType = Service_AsnProccess::getAsnType();
        $warehouseAll = Common_DataCache::getWarehouse();
        $warehouse = array();
        foreach ($warehouseAll as $key => $val) {
            $warehouse[$val['warehouse_id']] = $val['warehouse_code'];
        }
        //if ($this->_request->isPost()) {
        //$customerId = $this->customerId;
        $customerId = $customer['id'];
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);

        $AsnCode = $this->_request->getParam('receiving_code', '');
        $receiving_status = $this->_request->getParam('receiving_status', '1');
        $trackingNumber = trim($this->_request->getParam('tracking_number', ''));
        $receivingType = $this->_request->getParam('ASNType', '');
        $refCode = trim($this->_request->getParam('reference_no', ''));
        $warehouseId = $this->_request->getParam('warehouseId', '');

        $relativedOrderCode = trim($this->_request->getParam('relativedOrderCode', ''));

        $relate_receiving_code = '';
        if ($relativedOrderCode != "") {
            $rodRow = Service_ReceivingOrderDetail::getByField($relativedOrderCode, 'order_code', "*");
            if (empty($rodRow)) {
                $orderRow = Service_Orders::getByField($relativedOrderCode, 'reference_no', "*");
                if (!empty($orderRow)) {
                    $rodRow = Service_ReceivingOrderDetail::getByField($orderRow['order_code'], 'order_code', "*");
                    if (!empty($rodRow)) {
                        $relate_receiving_code = $rodRow['receiving_code'];
                    }
                } else {
                    $relate_receiving_code = "does not exist";
                }
            } else {
                $relate_receiving_code = $rodRow['receiving_code'];
            }
        }


        $created_start = $this->_request->getParam('created_start', '');
        $created_end = $this->_request->getParam('created_end', '');
        //echo $created_end;
        $created_start = ($created_start) ? $created_start . ' 00:00:00' : '';
        $created_end = ($created_end) ? $created_end . ' 59:59:59' : '';
        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 20;
        $condition = array(
            'receiving_code' => $AsnCode,
            'receiving_status' => $receiving_status,
            'tracking_number_like' => $trackingNumber,
            'receiving_type' => $receivingType,
            'reference_no' => $refCode,
            'warehouse_id' => $warehouseId,
            'customer_id' => $customerId,
            'created_start' => $created_start,
            'created_end' => $created_end,
            'receive_model_type' => '1',
            'relativedOrderCode' => $relativedOrderCode,
            'relate_receiving_code' => $relate_receiving_code
        );
        //print_r($condition);
        //$return = array('ask' => '0', 'msg' => 'No Data.', 'count' => 0, 'result' => array());
        $count = Service_Receiving::getByCondition($condition, 'count(*)');
        //$return['status'] = Service_Receiving::getCustomerAsnStatusGroup($condition);
        $result = '';
        if ($count > 0) {
            $result = Service_Receiving::getByCondition($condition, '*', $pageSize, $page, array('receiving_id desc'));
            foreach ($result as $key => $val) {
                $result[$key]['statustext'] = $allStatus[$val['receiving_status']];
                $result[$key]['warehouse'] = $warehouse[$val['warehouse_id']];
                $result[$key]['typetext'] = $allType[$val['receiving_type']];
                $asnItem = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $val['receiving_code']), '*');
                $orders = array();
                foreach ($asnItem as $p) {
                    $orderInfo = Service_Orders::getByField($p['order_code'], 'order_code');
                    $orders[] = $orderInfo;
                }
                $result[$key]['asnItem'] = $orders;
            }
            /* echo '<pre>';
             print_r($result);
            echo '</pre>'; */
        }

        //print_r($allStatus);
        //处理数量问题
        if (!empty($allStatus)) {
            $numConditon = $condition;
            foreach ($allStatus as $keys => $values) {
                $numConditon['receiving_status'] = $keys;
                $countstatus = Service_Receiving::getByCondition($numConditon, 'count(*)');
                $allStatus[$keys] = $values . "({$countstatus})";
            }
        }

        //print_r($condition);

        //print_r($return);
        $this->view->page = $page;
        $this->view->pageSize = $pageSize;
        $this->view->count = $count;

        //die(Zend_Json::encode($return));
        //}
        $this->view->AsnTypeArr = $allType;
        $this->view->AsnStatusArr = $allStatus;
        $this->view->warehouseArr = $warehouse;
        $this->view->result = $result;
        //重定义时间
        $condition['created_end'] = $this->_request->getParam('created_end', '');
        $condition['created_start'] = $this->_request->getParam('created_start', '');
        $this->view->params = $condition;
        echo Ec::renderTpl($this->tplDirectory . "jh-receiving-list.tpl", 'noleftlayout');
    }

    /**
     * @author william-fan
     * @todo 获取ASN 产品
     */
    public function receivingProductAction()
    {
        $customer = $this->_customerAuth;
        $customerId = $customer['id'];
        $result = array('ask' => '0', 'msg' => 'No Data.', 'result' => array());
        if ($this->_request->isPost()) {
            $AsnCode = $this->_request->getParam('ASNCode', '');
            if ($AsnCode == '') {
                die(json_encode($result));
            }
            $asnRows = Service_Receiving::getByCondition(array('receiving_code' => $AsnCode, 'customer_id' => $customerId), '*');
            if (empty($asnRows)) {
                die(json_encode($result));
            } else {
                $result = array('ask' => '1', 'msg' => 'Success!', 'result' => array());
                /* if (strtotime($asnRows[0]['expected_date']) > 0) {
                    $asnRows[0]['expected_date'] = date('Y-m-d', strtotime($asnRows[0]['expected_date']));
                } else {
                    $asnRows[0]['expected_date'] = '';
                } */
                $result['result'] = $asnRows[0];
                $asnItem = Service_ReceivingDetail::getByCondition(array('receiving_code' => $AsnCode), '*');
                $products = array();
                $cacheCategory = Common_DataCache::getProductCategory();
                foreach ($asnItem as $p) {
                    $product = Service_Product::getByField($p['product_id'], 'product_id');
                    $category = $cacheCategory[$product['pc_id']];
                    $product['category_name'] = $category['pc_name'];
                    $product['rd_receiving_qty'] = $p['rd_receiving_qty'];
                    //$product['attribute'] = $p['attribute']; 
                    $products[] = $product;
                }
                $result['result']['products'] = $products;
            }
        }
        die(json_encode($result));
    }

    /*
    * 获取ASN 详细产品
    */
    public function detailAction()
    {
        $ASNCode = $this->_request->getParam('ASNCode', '');

        $asnRow = Service_Receiving::getByField($ASNCode, 'receiving_code', "*");

        $receivingAddUser = Service_User::getByField($asnRow['receiving_add_user'], "user_id", "*");
        $asnRow['add_user'] = $receivingAddUser['user_code'];

        $lastUpdateUser = Service_User::getByField($asnRow['receiving_update_user'], "user_id", "*");
        $asnRow['luuser'] = $lastUpdateUser['user_code'];

        $ieport = Service_IePort::getByField($asnRow['ie_port'], "ie_port", "*");
        $asnRow['ie_port_name'] = $ieport['ie_port_name'];

        $fromType = Service_FormType::getByField($asnRow['form_type'], "form_type", "*");
        $asnRow['form_type_name'] = $fromType['form_type_name'];

        $wrapType = Service_WrapType::getByField($asnRow['wrap_type'], "wrap_type", "*");
        $asnRow['wrap_type_name'] = $wrapType['wrap_type_name'];

        $traf_mode = Service_TrafMode::getByField($asnRow['traf_mode'], "traf_mode", "*");
        $asnRow['traf_mode_name'] = $traf_mode['traf_mode_name'];

        $trade_mode = Service_TradeMode::getByField($asnRow['trade_mode'], "trade_mode", "*");
        $asnRow['trade_mode_name'] = $trade_mode['trade_mode_name'];

        $trans_mode = Service_TransMode::getByField($asnRow['trans_mode'], "trans_mode", "*");
        $asnRow['trans_mode_name'] = $trans_mode['trans_mode_name'];

        //状态:0删除,1草稿,2确认,3待审核,4审核,5在途,6收货中,7收货完成
        $this->view->asnStatus = array(
            '0' => Ec_Lang::getInstance()->getTranslate('delete'),//'删除',
            '1' => Ec_Lang::getInstance()->getTranslate('Draft'),//'草稿',
            '2' => Ec_Lang::getInstance()->getTranslate('Confirm'),//'确认',
            '3' => Ec_Lang::getInstance()->getTranslate('PendingAudit'),//'待审核',
            '4' => Ec_Lang::getInstance()->getTranslate('Audited'),//'审核',
            '5' => Ec_Lang::getInstance()->getTranslate('onway'),//'在途',
            '6' => Ec_Lang::getInstance()->getTranslate('ReceiptOf'),//'收货中',
            '7' => Ec_Lang::getInstance()->getTranslate('ReceiptComplete')//'收货完成'
        );
        //收货类型：0:标准;1:订单退货;2:指定产品退件,3:中转
        $this->view->receivingType = array(
            '0' => Ec_Lang::getInstance()->getTranslate('Standard'),//'标准',
            '1' => Ec_Lang::getInstance()->getTranslate('OrdersReturns'),//'订单退货',
            '2' => Ec_Lang::getInstance()->getTranslate('SpecifyTheProductBackPieces'),//'指定产品退件',
            '3' => Ec_Lang::getInstance()->getTranslate('Transit')//'中转'
        );
        if ($asnRow['receive_model_type'] == '1') {
            //集货模式的ASN
            $detail = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $ASNCode), "*");
            if (!empty($detail)) {
                foreach ($detail as $k => &$order) {
                    $order_array = Service_Orders::getByField($order['order_code'], 'order_code');
                    $order['order_status'] = $order_array['order_status'];
                    $order['order_update_time'] = $order_array['update_time'];
                    $order['order_add_time'] = $order_array['add_time'];
                    $order['time_of_receipt'] = $order_array['time_of_receipt'];
                    $order['order_status_text'] = Service_OrderProcess::getJHStatusText2($order_array['order_status']);

                }

            }//if(!empty($detail)){
            //print_r($detail);
            $this->view->orderCount = empty($detail) ? 0 : count($detail);
        } else {
            //备货模式的ASN
            $detail = Service_ReceivingDetail::getByCondition(array('receiving_code' => $ASNCode), "*");
        }

        $netTotalWeight = 0;
        if ($asnRow['receive_model_type'] != '1') {
            if ($detail) {
                foreach ($detail as $row) {
                    $prd = Service_Product::getByField($row['product_id'], "product_id", "*");
                    if (!$prd || $prd['product_type'] == 1) {
                        continue;
                    }
                    $netTotalWeight += $prd['product_weight'] * $row['rd_receiving_qty'];

                }//foreach

            }
        }//备货模式


        if ($asnRow['receive_model_type'] == '1') {
            if ($detail) {
                foreach ($detail as $row) {
                    $order_code = $row['order_code'];
                    if (empty($order_code)) {
                        continue;
                    }
                    $calucate_array = Service_OrderProcess::calucateOrderTotalWeight($order_code);
                    $netTotalWeight += $calucate_array['totalWeight'];
                }
            }
        }//集货模式

        $asnRow['netTotalWeight'] = $netTotalWeight;

        $this->view->asnRow = $asnRow;


        $this->view->detail = $detail;
        $logs = Service_ReceivingLog::getByCondition(array('receiving_code' => $ASNCode), "*", 0, 0, 'rl_id desc');
        foreach ($logs as $k => $v) {
            if ($v['user_id'] > 0) {
                //$user = Service_User::getByField($v['user_id'],"user_id","*");
                $logs[$k]['user_code'] = '系统';//$user['user_code'];
            } else {
                $logs[$k]['user_code'] = $v['customer_code'];

                if ((int)$v['account_id']) {
                    $user = Service_Account::getByCondition(array('account_id' => $v['account_id']));
                    $logs[$k]['user_code'] = $user ? $user['account_name'] : $v['customer_code'];
                }
            }
        }
        $this->view->logs = $logs;
        $batchDetail = Service_ReceivingDetailBatch::getByCondition(array('receiving_code' => $ASNCode), "*");
        foreach ($batchDetail as $key => $value) {
            $P = Service_Product::getByField($value['product_id'], "product_id", "*");
            $batchDetail[$key]['product_sku'] = $P['product_sku'];
        }
        $this->view->batchDetail = $batchDetail;
        echo Ec::renderTpl($this->tplDirectory . "receiving-detail.tpl", 'noleftlayout');
    }

    /*
     *获取ASN 日志
     */
    public function detailLogAction()
    {
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;
            $condition = array();
            /* 以下为提交数据整理 */

            $ASNCode = $this->_request->getParam("ASNCode", "");
            $condition["receiving_code"] = $ASNCode;
            $condition["customer_id"] = $this->customerId;

            $return = array(
                "ask" => 0,
                "msg" => "No Data."
            );

            /* 以下为业务逻辑方法调用 */
            $count = Merchant_Service_ReceivingLog::getByCondition($condition, 'count(*)');
            $return['count'] = $count;

            if ($count) {
                $rows = Merchant_Service_ReceivingLog::getByCondition($condition, '*', $pageSize, $page, array('rl_id desc'));
                $return['result'] = $rows;
                $return['ask'] = 1;
                $return['msg'] = "Success";
            }

            die(Zend_Json::encode($return));
        }
    }

    /**
     * @author william-fan
     * @todo ASN收货信息
     */
    public function receivingBatchAction()
    {
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;
            $condition = array();
            /* 以下为提交数据整理 */

            $ASNCode = $this->_request->getParam("ASNCode", "");
            $condition["receiving_code"] = $ASNCode;
            $condition["customer_id"] = $this->customerId;

            $return = array(
                "ask" => 0,
                "msg" => "No Data."
            );

            /* 以下为业务逻辑方法调用 */
            $count = Service_ReceivingBatch::getByCondition($condition, 'count(*)');;
            $return['count'] = $count;

            if ($count) {
                $rows = Service_ReceivingBatch::getByCondition($condition, '*', $pageSize, $page, array('rb_id desc'));
                //print_r($rows);
                foreach ($rows as $key => $value) {
                    $product = Merchant_Service_Product::getByField($value['product_id']);
                    $rows[$key]['product_sku'] = $product['product_sku'];
                }
                $return['result'] = $rows;
                $return['ask'] = 1;
                $return['msg'] = "Success";
            }

            die(Zend_Json::encode($return));
        }
    }
    /*
     * Print packing List
     */
    /*public function printAction()
    {
        $ASNCode = $this->_request->getParam('ASNCode', '');
        if (!empty($ASNCode)) {
            $result = Service_AsnProccess::getAsnInfo($ASNCode, $this->customerId);
            $receivingInfo = $result['result'];
            $customerinfo=Service_Customer::getByField($this->customerId);
            //$customerinfo = $this->_customerAuth;
            $currencyRow = Service_Currency::getByField($customerinfo['customer_currency'], 'currency_code');
            $ieprot = Service_IePort::getByField($receivingInfo['asnRow']['ie_port'],'ie_port');
            if(!empty($ieprot)){
            	$receivingInfo['asnRow']['ie_port_name'] = $ieprot['ie_port_name'];
            }else{
            	$receivingInfo['asnRow']['ie_port_name'] = '';
            }
            $trade_mode = Service_TradeMode::getByField($receivingInfo['asnRow']['trade_mode'],'trade_mode');
            if(!empty($trade_mode)){
            	$receivingInfo['asnRow']['trade_mode_name'] = $trade_mode['trade_mode_name'];
            }else{
            	$receivingInfo['asnRow']['trade_mode_name'] = '';
            }
            $form_type = Service_FormType::getByField($receivingInfo['asnRow']['form_type'],'form_type');
            if(!empty($form_type)){
            	$receivingInfo['asnRow']['form_type_name'] = $form_type['form_type_name'];
            }else{
            	$receivingInfo['asnRow']['form_type_name'] = '';
            }
            $wrap_type = Service_WrapType::getByField($receivingInfo['asnRow']['wrap_type'],'wrap_type');
            if(!empty($wrap_type)){
            	$receivingInfo['asnRow']['wrap_type_name'] = $wrap_type['wrap_type_name'];
            }else{
            	$receivingInfo['asnRow']['wrap_type_name'] = '';
            }
            if (!empty($result)) {
                $this->view->asnInfo = $receivingInfo;
            }
            //$this->view->customerinfo=$customerinfo;
            $this->view->customerRow = $customerinfo;
            $this->view->currencyRow = $currencyRow;
            //更新Asn单
           $result = Service_AsnProccess::printAsn($ASNCode,$this->customerId);
           if($result['ask']=='1'){
           		echo $this->view->render($this->tplDirectory . "receiving-print.tpl");exit;
           		//echo Ec::renderTpl($this->tplDirectory . "receiving-print.tpl", 'layout-print');
           }else{
           		die($result['message']);
           }
           //print_r($result);
        }

        //echo Ec::renderTpl($this->tplDirectory . "receiving-print.tpl", 'noleftlayout');
    }*/

    public function printAction()
    {
        $ASNCode = $this->_request->getParam('ASNCode', '');
        if (!empty($ASNCode)) {
            $aFtpMessageType = Service_FtpMessageType::getByField('MRK', 'fmt_code');
            if (Service_Customer::checkIsService()) {
                $ansnInfo = Service_Receiving::getByField($ASNCode, 'receiving_code');
                if ($ansnInfo['supplier_id'] != $this->_customerAuth['id']) {
                    die('AsnCode:' . $ASNCode . '不存在');
                }
                $customerinfo = Service_Customer::getByField($ansnInfo['customer_id']);
                $customerinfo['id'] = $customerinfo['customer_id'];
            } else {
                $customerinfo = $this->_customerAuth;
                $customerinfo['customer_id'] = $customerinfo['id'];
            }
            $result = Service_AsnProccess::getAsnInfo($ASNCode, $customerinfo['customer_id']);
            $receivingInfo = $result['result'];
            if ($receivingInfo['asnRow']['receiving_status'] != '4') {
                exit('状态不对不允许打印');
            }

            $customerRow = Service_Customer::getByField($receivingInfo['asnRow']['customer_id']);
            //申报海关
            $decl_port = Service_IePort::getByField($aFtpMessageType['fmt_decl_port'], 'ie_port');
            if (!empty($decl_port)) {
                $aFtpMessageType['decl_port_name'] = $decl_port['ie_port_name'];
            } else {
                $aFtpMessageType['decl_port_name'] = '';
            }
            //进口口岸
            $ieprot = Service_IePort::getByField($receivingInfo['asnRow']['ie_port'], 'ie_port');
            if (!empty($ieprot)) {
                $receivingInfo['asnRow']['ie_port_name'] = $ieprot['ie_port_name'];
            } else {
                $receivingInfo['asnRow']['ie_port_name'] = '';
            }
            $trans_mode = Service_TransMode::getByField($receivingInfo['asnRow']['trans_mode'], 'trans_mode');
            if (!empty($trans_mode)) {
                $receivingInfo['asnRow']['trans_mode_name'] = $trans_mode['trans_mode_name'];
            } else {
                $receivingInfo['asnRow']['trans_mode_name'] = '';
            }
            $traf_mode = Service_TrafMode::getByField($receivingInfo['asnRow']['traf_mode'], 'traf_mode');
            if (!empty($traf_mode)) {
                $receivingInfo['asnRow']['traf_mode_name'] = $traf_mode['traf_mode_name'];
            } else {
                $receivingInfo['asnRow']['traf_mode_name'] = '';
            }
            $trade_mode = Service_TradeMode::getByField($receivingInfo['asnRow']['trade_mode'], 'trade_mode');
            if (!empty($trade_mode)) {
                $receivingInfo['asnRow']['trade_mode_name'] = $trade_mode['trade_mode_name'];
            } else {
                $receivingInfo['asnRow']['trade_mode_name'] = '';
            }
            $form_type = Service_FormType::getByField($aFtpMessageType['form_type'], 'form_type');
            if (!empty($form_type)) {
                $receivingInfo['asnRow']['form_type_name'] = $form_type['form_type_name'];
            } else {
                $receivingInfo['asnRow']['form_type_name'] = '';
            }
            $wrap_type = Service_WrapType::getByField($receivingInfo['asnRow']['wrap_type'], 'wrap_type');
            if (!empty($wrap_type)) {
                $receivingInfo['asnRow']['wrap_type_name'] = $wrap_type['wrap_type_name'];
            } else {
                $receivingInfo['asnRow']['wrap_type_name'] = '';
            }

            if (!empty($result)) {
                $this->view->asnInfo = $receivingInfo;
            }
            $this->view->kvCurrency = Service_Currency::getKeyVal();
            $this->view->kvProductUom = Service_ProductUom::getKeyVal();
            $this->view->customerinfo = $customerinfo;
            $this->view->customerRow = $customerRow;
            $this->view->aFtpMessageType = $aFtpMessageType;


            //更新Asn单
            $result = Service_AsnProccess::printAsn($ASNCode, $customerinfo['customer_id']);
            if ($result['ask'] == '1') {
                echo $this->view->render($this->tplDirectory . "receiving-print.tpl");
                exit;
                //echo Ec::renderTpl($this->tplDirectory . "receiving-print.tpl", 'layout-print');
            } else {
                die($result['message']);
            }
            //print_r($result);
        }

        //echo Ec::renderTpl($this->tplDirectory . "receiving-print.tpl", 'noleftlayout');
    }

    /**
     * @author william-fan
     * @todo 重新打印
     */
    public function reprintAction()
    {
        $ASNCode = $this->_request->getParam('ASNCode', '');
        if (!empty($ASNCode)) {
            $aFtpMessageType = Service_FtpMessageType::getByField('MRK', 'fmt_code');
            $result = Service_AsnProccess::getAsnInfo($ASNCode, $this->customerId);
            $receivingInfo = $result['result'];
            if ($receivingInfo['asnRow']['receiving_status'] != '5') {
                //$this->_redirect('');
                exit('状态不对不允许重新打印');
            }
            $customerinfo = $this->_customerAuth;
            $customerRow = Service_Customer::getByField($receivingInfo['asnRow']['customer_id']);
            //$currencyRow = Service_Currency::getByField($customerRow['customer_currency'], 'currency_code');
            //申报海关
            $decl_port = Service_IePort::getByField($aFtpMessageType['fmt_decl_port'], 'ie_port');
            if (!empty($decl_port)) {
                $aFtpMessageType['decl_port_name'] = $decl_port['ie_port_name'];
            } else {
                $aFtpMessageType['decl_port_name'] = '';
            }
            //进口口岸
            $ieprot = Service_IePort::getByField($receivingInfo['asnRow']['ie_port'], 'ie_port');
            if (!empty($ieprot)) {
                $receivingInfo['asnRow']['ie_port_name'] = $ieprot['ie_port_name'];
            } else {
                $receivingInfo['asnRow']['ie_port_name'] = '';
            }
            $trans_mode = Service_TransMode::getByField($receivingInfo['asnRow']['trans_mode'], 'trans_mode');
            if (!empty($trans_mode)) {
                $receivingInfo['asnRow']['trans_mode_name'] = $trans_mode['trans_mode_name'];
            } else {
                $receivingInfo['asnRow']['trans_mode_name'] = '';
            }
            $traf_mode = Service_TrafMode::getByField($receivingInfo['asnRow']['traf_mode'], 'traf_mode');
            if (!empty($traf_mode)) {
                $receivingInfo['asnRow']['traf_mode_name'] = $traf_mode['traf_mode_name'];
            } else {
                $receivingInfo['asnRow']['traf_mode_name'] = '';
            }
            $trade_mode = Service_TradeMode::getByField($receivingInfo['asnRow']['trade_mode'], 'trade_mode');
            if (!empty($trade_mode)) {
                $receivingInfo['asnRow']['trade_mode_name'] = $trade_mode['trade_mode_name'];
            } else {
                $receivingInfo['asnRow']['trade_mode_name'] = '';
            }
            $form_type = Service_FormType::getByField($aFtpMessageType['form_type'], 'form_type');
            if (!empty($form_type)) {
                $receivingInfo['asnRow']['form_type_name'] = $form_type['form_type_name'];
            } else {
                $receivingInfo['asnRow']['form_type_name'] = '';
            }
            $wrap_type = Service_WrapType::getByField($receivingInfo['asnRow']['wrap_type'], 'wrap_type');
            if (!empty($wrap_type)) {
                $receivingInfo['asnRow']['wrap_type_name'] = $wrap_type['wrap_type_name'];
            } else {
                $receivingInfo['asnRow']['wrap_type_name'] = '';
            }
            //print_r($receivingInfo);

            if (!empty($result)) {
                $this->view->asnInfo = $receivingInfo;
            }
            $this->view->kvCurrency = Service_Currency::getKeyVal();
            $this->view->kvProductUom = Service_ProductUom::getKeyVal();
            $this->view->customerinfo = $customerinfo;
            $this->view->customerRow = $customerRow;
            //$this->view->currencyRow = $currencyRow;
            $this->view->aFtpMessageType = $aFtpMessageType;
            //更新Asn单
            //$result = Service_AsnProccess::printAsn($ASNCode,$this->customerId);


        }
        echo $this->view->render($this->tplDirectory . "receiving-print.tpl");
        //echo Ec::renderTpl($this->tplDirectory . "receiving-print.tpl", 'layout-print');
    }

    /*
     * Print ASNCode Label
     */
    public function printLabelAction()
    {
        $ASNCodeArr = $this->_request->getParam('AsnArr', '');
        if (empty($ASNCodeArr) || !is_array($ASNCodeArr)) {
            die('no data.');
        }
        $this->view->results = $ASNCodeArr;
        echo Ec::renderTpl($this->tplDirectory . "print-label.tpl", 'layout-print');
    }

    /**
     * @author william-fan
     * 转状态到删除
     */
    public function deleteAction()
    {
        $return = array('ask' => 0, 'message' => '删除出错.');
        $ASNCode = $this->_request->getParam('ASNCode', '');
        if (!empty($ASNCode)) {
            $asnObj = new Service_AsnProccess();
            $return = $asnObj->deleteAsnTransaction($ASNCode, $this->customerId);
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @author william-fan
     * @todo 确认ASN 生成 生产产品库存信息
     */
    public function confirmAction()
    {
        //$ASNCode = $this->_request->getParam('ASNCode', '');
        $AsnArr = $this->_request->getParam('AsnArr', '');

        $return = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('ConfirmFailure'), 'orderCodeArr' => array());
        $ASNArr = $this->_request->getParam('AsnArr', '');
        $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', 'LYT-SMTGH-X',
            'BH-SFEP',
        );
        if (!empty($ASNArr)) {
            $success = 0;
            $failse = 0;
            $customer = $this->_customerAuth;
            $customerId = $customer['id'];
            $errstr = '';
            $orderCodeArr = array();
            $printPdfSmCode = array();
            foreach ($ASNArr as $key => $ASNCode) {
                $result = Service_AsnProccess::confirmASn($ASNCode, $customerId);
                if (!empty($result) && $result['ask'] == '1') {
                    $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $ASNCode), "*");
                    foreach ($rod as $k => $v) {
                        $order = Service_Orders::getByField($v['order_code'], 'order_code', '*');
                        if (in_array($order['sm_code'], $pdfSmcode) && $order['order_mode_type'] == 1) {
                            $printPdfSmCode[] = $order['sm_code'];
                        } elseif (!in_array($v['order_code'], $orderCodeArr)) {
                            $orderCodeArr[] = $v['order_code'];
                        }

                    }
                    $return['detailmessage'][] = '收货单号' . "[{$ASNCode}]成功.";
                    $success++;
                } else {
                    $return['detailmessage'][] = '收货单号' . "[{$ASNCode}]失败.";
                    $failse++;
                    $errstr .= $result['message'] . "<br/>";
                }
            }
            if ($success > 0) {
                $return['ask'] = 1;
                $return['AsnArr'] = $AsnArr;
                if (!empty($orderCodeArr)) {
                    $return['orderCodeArr'] = $orderCodeArr;
                }
                if (!empty($printPdfSmCode)) {
                    $return['has_pdf_smcode'] = array_unique($printPdfSmCode);
                }
            }
            $return['message'] = '移至确认' . Ec_Lang::getInstance()->getTranslate('success') . '：' . $success . "，" . Ec_Lang::getInstance()->getTranslate('fail') . ':' . $failse . $errstr;
        } else {
            $return['message'] = Ec_Lang::getInstance()->getTranslate('InvalidParameter');//'参数错误';
        }
        die(Zend_Json::encode($return));


        /* $return['message']='操作成功';

        //header('Content-type: text/xml; charset=utf-8');
        $recxProcess = new Service_ReceiptXmlProcess($ASNCode);
        //echo $recxProcess->generate();

        $ftProcess = new Service_FtpMessageProcess();
        $result = $ftProcess->addSendMessage($ASNCode); */


        die(Zend_Json::encode($result));
    }

    /**
     * @author william-fan
     * @todo 移至待审核 生成xml
     */
    public function pendingAction()
    {
        //$ASNCode = $this->_request->getParam('ASNCode', '');

        $AsnArr = $this->_request->getParam('AsnArr', '');

        $return = array('ask' => 0, 'message' => Ec_Lang::getInstance()->getTranslate('MovePendingAuditFailure'));
        $ASNArr = $this->_request->getParam('AsnArr', '');
        if (!empty($ASNArr)) {
            $success = 0;
            $failse = 0;
            $customer = $this->_customerAuth;
            $customerId = $customer['id'];
            $errstr = '';
            foreach ($ASNArr as $key => $ASNCode) {
                $result = Service_AsnProccess::PendingAsn($ASNCode, $customerId);
                if (!empty($result) && $result['ask'] == '1') {
                    $return['detailmessage'][] = '收货单号' . "[{$ASNCode}]成功.";
                    $success++;
                    //$errstr .= $result['message']."<br/>";
                } else {
                    $return['detailmessage'][] = '收货单号' . "[{$ASNCode}]失败.(失败原因:" . $result['message'] . ")";
                    //$errstr .= $result['message']."<br/>";
                    $failse++;
                }
            }
            if ($success > 0) {
                $return['ask'] = 1;
            }
            $return['message'] = Ec_Lang::getInstance()->getTranslate('MovePendingAuditSuccess') . ':' . $success . Ec_Lang::getInstance()->getTranslate('fail') . ' :' . $failse . $errstr;
        }

        die(Zend_Json::encode($return));
    }

    /**
     * @author william-fan
     * @todo 用于处理ASN在途和收货部一样的情况
     */
    public function dealAsnAction()
    {
        $customerId = $this->customerId;
        if ($this->_request->isPost()) {
            $rd_id = $this->_request->getParam('rd_id', '');

            $result = Service_AsnProccess::closeAssn($rd_id, $customerId);
            die(Zend_Json::encode($result));
        }


        $ASNCode = $this->_request->getParam('ASNCode', '');
        $result = Service_AsnProccess::getAsnInfo($ASNCode, $this->customerId);
        $receivingInfo = $result['result'];
        /* echo '<pre>';
        print_r($receivingInfo);
        echo '</pre>'; */
        $this->view->asnInfo = $receivingInfo;
        echo Ec::renderTpl($this->tplDirectory . "deal-asn.tpl", 'noleftlayout');
    }

    /**
     * @author william-fan
     * @todo 移至草稿
     */
    public function draftAction()
    {

        $AsnArr = $this->_request->getParam('AsnArr', '');

        $return = array('ask' => 0, 'message' => '移至草稿,失败.');
        $ASNArr = $this->_request->getParam('AsnArr', '');
        if (!empty($ASNArr)) {
            $success = 0;
            $failse = 0;
            $customer = $this->_customerAuth;
            $customerId = $customer['id'];
            foreach ($ASNArr as $key => $ASNCode) {
                $result = Service_AsnProccess::draftAsn($ASNCode, $customerId);
                if (!empty($result) && $result['ask'] == '1') {
                    $return['detailmessage'][] = '收货单号' . "[{$ASNCode}]成功.";
                    $success++;
                } else {
                    $failse++;
                    $return['detailmessage'][] = '收货单号' . "[{$ASNCode}]失败." . "(失败原因:" . $result['message'] . ")";
                }
            }
            if ($success > 0) {
                $return['ask'] = 1;
            }
            $return['message'] = '移至草稿,成功:' . $success . ' 失败:' . $failse;
        }

        die(Zend_Json::encode($return));
    }

    public function getOrderAction()
    {
        $return = array('state' => '0', 'has_pdf_smcode' => '0');
        $receivingCode = $this->_request->getParam("receiving_code", "");
        $rod = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $receivingCode), "*");
        $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', 'LYT-SMTGH-X',
            'BH-SFEP',
        );
        if ($rod) {
            $return['state'] = 1;
            $total = 0;
            $hasPdfSmCode = array();
            foreach ($rod as $r) {

                $order = Service_Orders::getByField($r['order_code'], 'order_code', '*');
                if (in_array($order['sm_code'], $pdfSmcode) && $order['order_mode_type'] == 1) {
                    $hasPdfSmCode[] = $order['sm_code'];
                } else {
                    $total++;
                }
            }
            $return['has_lable'] = $total;
            if (!empty($hasPdfSmCode)) {
                $return['has_pdf_smcode'] = array_unique($hasPdfSmCode);
            }
        }
        die(json_encode($return));
    }

    /**
     * @todo 下载报关单
     */
    public function downbaoguanAction()
    {
        $return = array('ask' => 0, 'message' => '生成报关单草单失败.');
        $ASNCode = $this->_request->getParam('receiving_code', '');
        $mergerbygoods = $this->_request->getParam('merge'); //按料号合并，默认合并

        if (!empty($ASNCode)) {
            $asnObj = new Service_AsnProccess();
            $return = $asnObj->downTemplateBaoguan($ASNCode, $this->customerId, $mergerbygoods);

            /*echo "<pre>";
            print_r($return);
            exit;*/
            if ($return['state'] != '1') {
                die($return['message']);
            } else {
                //require_once "PHPExcel.php";
                //require_once "PHPExcel/IOFactory.php";

                /*require_once 'PHPExcel.php';
                require_once("PHPExcel/Reader/Excel5.php");
                require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';*/
                //phpinfo();

                require_once "PHPExcel1.8/PHPExcel.php";
                require_once "PHPExcel1.8/PHPExcel/Reader/Excel2007.php";
                require_once "PHPExcel1.8/PHPExcel/Reader/Excel5.php";
                require_once "PHPExcel1.8/PHPExcel/IOFactory.php";


                $path = APPLICATION_PATH . '/../data/file/baoguantemp.xls';
                $excel = PHPExcel_IOFactory::load($path);
                $baoguanSheet = $excel->getSheet(0);

                $excel->setActiveSheetIndex(0);
                $zhuangxiangSheet = $excel->getSheet(1);
                $fapiaoSheet = $excel->getSheet(2);
                $hetongSheet = $excel->getSheet(3);

                $asnRow = $return['data']['asnRow'];

                $ASNDetail = $return['data']['ASNDetail'];
                $defaultInfo = $return['data']['defaultInfo'];

                $baoguanSheet->setCellValue('B15', $asnRow['receiving_code']);//
                $baoguanSheet->setCellValue('H13', $asnRow['net_weight']);//
                $baoguanSheet->setCellValue('F13', $asnRow['pack_no']);//

                $duty_mode_body = '1-照章征税';

                if ($defaultInfo) {
                    $defaultCell = [
                        "trade_co" => "C4",//境内发货人
                        "trade_name" => 'A5',//"境内发货人名称",
                        "overseas_consignor_ename" => 'A7', //境外收货人
                        "owner_code" => 'C8',//"生产销售单位",
                        "owner_name" => 'A9',//"生产销售单位名称",
                        "declare_port" => 'F5',//"出境关别",
                        "traf_mode" => 'F7',//"运输方式",
                        "trade_mode" => 'F9',//"监管方式",
                        "trade_area_code" => 'F11',//"贸易国别地区",
                        "trade_country" => 'H11',//"运抵国",
                        "destination_port" => 'J11',//"指运港",
                        "enty_port_code" => 'N11',//"离境口岸",
                        "trans_mode" => 'I13',//"成交方式",
                        "duty_mode" => "H9", //征免性质,
                        "jingnei" => "R17", //境内目的地,
//                        "destination_country":"最终目的国",
//                        "destination_country":"142-中国",
//                        "district_code":"境内货源地",
//                        "district_code":"44036-深圳前海湾保税港区",
                    ];
                    foreach ($defaultCell as $key => $cell) {
                        if (isset($defaultInfo[$key])) {
                            $baoguanSheet->setCellValueExplicit($cell, $defaultInfo[$key], PHPExcel_Cell_DataType::TYPE_STRING);
                        }
                    }
                    if (isset($defaultInfo['duty_mode_body'])) {
                        $duty_mode_body = $defaultInfo['duty_mode_body'];
                    }
                }

                $uoms = Service_ProductUom::getByCondition();
                $uomKey = [];
                foreach ($uoms as $k => $uom) {
                    $uomKey[$uom['pu_code']] = $uom;
                }

                $index = 18;
                $i = 1;
                $total_amount = 0;
                foreach ($ASNDetail as $body) {
                    $baoguanSheet->insertNewRowBefore($index, 1);  //在操作行的号前加一空行，这空行的行号就变成了当前的行号
                    $baoguanSheet->setCellValue('A' . $index, $i);//
                    //$baoguanSheet->setCellValue('B' . $index, $body['']);//备案序号
                    $baoguanSheet->setCellValue('C' . $index, $body['goods_id']);//商品料号
                    $baoguanSheet->setCellValueExplicit('D' . $index, $body['hs_code'], PHPExcel_Cell_DataType::TYPE_STRING);//商品编码(必填)
                    $baoguanSheet->setCellValue('E' . $index, $body['hs_goods_name']);//商品名称
                    $baoguanSheet->setCellValue('F' . $index, $body['product_model']);//规格型号
                    $baoguanSheet->setCellValueExplicit('G' . $index, $body['quantity'], PHPExcel_Cell_DataType::TYPE_STRING);//申报数量
                    $pu_code = $body['pu_code'];
                    $pu_name = "";
                    if (isset($uomKey[$pu_code])) {
                        $pu_name = $uomKey[$pu_code]['pu_name'];
                    }
                    $pu_code_law = $body['pu_code_law'];
                    if (isset($uomKey[$pu_code_law])) {
                        $pu_code_law_name = $uomKey[$pu_code_law]['pu_name'];
                    }
                    $baoguanSheet->setCellValueExplicit('H' . $index, $pu_name, PHPExcel_Cell_DataType::TYPE_STRING);//申报单位
                    $baoguanSheet->setCellValueExplicit('I' . $index, $body['quantity_law'], PHPExcel_Cell_DataType::TYPE_STRING);//法定第一数量
                    $baoguanSheet->setCellValueExplicit('J' . $index, $pu_code_law_name, PHPExcel_Cell_DataType::TYPE_STRING);//法定第一单位
                    if ($body['pu_code_second'] != '') {
                        $pu_code_second = $body['pu_code_second'];
                        $pu_code_second_name = "";
                        if (isset($uomKey[$pu_code_second])) {
                            $pu_code_second_name = $uomKey[$pu_code_second]['pu_name'];
                        }
                        $baoguanSheet->setCellValue('K' . $index, $body['quantity_second']);//法定第二数量
                        $baoguanSheet->setCellValue('L' . $index, $pu_code_second_name);//法定第二单位
                    }
                    $currency_code = $body['currency_code'];
                    $currency = Service_Currency::getByField($currency_code, 'currency_code');
                    $currency_hs_code = "";
                    if (!empty($currency)) {
                        $currency_hs_code = $currency['currency_hs_code'];
                        $currency_hs_code = $currency_hs_code . "-" . $currency['currency_name'];
                    }

                    $baoguanSheet->setCellValueExplicit('M' . $index, sprintf("%.4f",$body['product_declared_value']), PHPExcel_Cell_DataType::TYPE_STRING);//申报单价
                    $baoguanSheet->setCellValue('N' . $index, $body['declared_value']);//申报总价
                    $baoguanSheet->setCellValue('O' . $index, $currency_hs_code, PHPExcel_Cell_DataType::TYPE_STRING);//申报币值

                    $baoguanSheet->setCellValueExplicit('P' . $index, '142-中国', PHPExcel_Cell_DataType::TYPE_STRING);//原产国
                    $baoguanSheet->setCellValue('Q' . $index, '110-香港');//最终目的国


                    $baoguanSheet->setCellValue('S' . $index, $duty_mode_body);//征免方式
                    if ($defaultInfo) {
                        if ($defaultInfo['destination_country']) {
                            $baoguanSheet->setCellValue('Q' . $index, $defaultInfo['destination_country']);//最终目的国
                        }
                        if ($defaultInfo['district_code']) {
                            $baoguanSheet->setCellValue('R' . $index, $defaultInfo['district_code']);//最终目的国
                        }

                    }
                    $total_amount += $body['declared_value'];


                    $i++;
                    $index++;
                }
                $baoguanSheet->setCellValue('F15', $total_amount);//

                //装箱单
                $index = 13;
                $i = 1;
                foreach ($ASNDetail as $body) {
                    $zhuangxiangSheet->setCellValue('A' . $index, $i);//标记
                    $zhuangxiangSheet->setCellValue('B' . $index, $body['product_title']);//货物
                    //$zhuangxiangSheet->setCellValue('E' . $index, $body['goods_id']);//
                    $pu_code = $body['pu_code'];
                    $puRow = Service_ProductUom::getByField($pu_code, 'pu_code');
                    $pu_name = "";
                    if (!empty($puRow)) {
                        $pu_name = $puRow['pu_name'];
                    }
                    $zhuangxiangSheet->setCellValueExplicit('F' . $index, $body['quantity'] . $pu_name, PHPExcel_Cell_DataType::TYPE_STRING);//数量(必填)
                    //$zhuangxiangSheet->setCellValue('J' . $index, '');//
                    $zhuangxiangSheet->setCellValue('L' . $index, $body['total_weight']);//
                    $i++;
                    $index++;
                }
                //发票
                $index = 11;
                $i = 1;
                foreach ($ASNDetail as $body) {
                    $fapiaoSheet->setCellValue('A' . $index, $i);//标记
                    $fapiaoSheet->setCellValue('B' . $index, $body['product_title']);//货物
                    //$zhuangxiangSheet->setCellValue('E' . $index, $body['goods_id']);//
                    $pu_code = $body['pu_code'];
                    $puRow = Service_ProductUom::getByField($pu_code, 'pu_code');
                    $pu_name = "";
                    if (!empty($puRow)) {
                        $pu_name = $puRow['pu_name'];
                    }
                    $fapiaoSheet->setCellValueExplicit('E' . $index, $body['quantity'] . $pu_name, PHPExcel_Cell_DataType::TYPE_STRING);//数量(必填)
                    $fapiaoSheet->setCellValue('H' . $index, $body['product_unit_price']);//
                    $fapiaoSheet->setCellValue('I' . $index, $body['declared_value']);//
                    $i++;
                    $index++;
                }
                //合同
                $index = 18;
                $i = 1;
                foreach ($ASNDetail as $body) {
                    $hetongSheet->setCellValue('A' . $index, $body['product_title']);//货物
                    $pu_code = $body['pu_code'];
                    $puRow = Service_ProductUom::getByField($pu_code, 'pu_code');
                    $pu_name = "";
                    if (!empty($puRow)) {
                        $pu_name = $puRow['pu_name'];
                    }
                    $hetongSheet->setCellValueExplicit('F' . $index, $body['quantity'] . $pu_name, PHPExcel_Cell_DataType::TYPE_STRING);//数量(必填)
                    $hetongSheet->setCellValue('G' . $index, $body['product_unit_price']);//
                    $hetongSheet->setCellValue('I' . $index, $body['declared_value']);//
                    $i++;
                    $index++;
                }
                $filename = $asnRow['receiving_code'] . '.xls';
                $filename = mb_convert_encoding($filename, 'gbk');
                $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Type: application/force-download');
                header("Content-Disposition: attachment;filename=\"$filename\"");
                header("Content-Transfer-Encoding: binary");
                header('Cache-Control: max-age=0');
                $writer->save('php://output');

            }
            //var_dump($return);
        }

    }

    /**
     * @todo 下载客户已经上传的已经生成的报关单
     */
    public function downbgAction()
    {
        $receiving_code = $this->_request->getParam("receiving_code");
        if (!empty($receiving_code)) {
            $receive = Service_Receiving::getByField($receiving_code, 'receiving_code');
            if ($receive['baoguan_file'] != '') {
                if (file_exists($receive['baoguan_file'])) {
                    $fullPath = $receive['baoguan_file'];
                    $filename = basename($fullPath);
                    $filearr = pathinfo($filename);
                    $name = $receive['receiving_code'] . '-BG.' . $filearr['extension'];
                    Common_Common::downloadFile($fullPath, $name);
                } else {
                    echo "报关单数据未上传或者不存在";
                    exit;
                }
            }
        } else {
            die("参数错误!");
        }
        exit;
    }

    /**
     * @todo 报关单上传功能
     */
    public function uploadbaoguanImportAction()
    {
        if ($this->_request->isPost()) {
            $res = array(
                'state' => 0,
                'message' => '',
                'error' => [],
                'data' => [],
            );
            try {
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                //var_dump($this->_request->getParams());
                $mergerbygoods = $this->_request->getParam('merge', '1'); //按料号合并，默认合并
                $receiving_code = $this->_request->getParam('receiving_code');
                if (empty($receiving_code)) {
                    throw new Exception('入库单号为空');
                }
                $receiving = Service_Receiving::getByField($receiving_code, 'receiving_code');
                if (empty($receiving)) {
                    throw new Exception('入库单不存在:' . $receiving_code);
                }
                $upload = new Process_Upload();
                $savePath = APPLICATION_PATH . '/../data/baoguanTemp/';
                $savePath .= date("Y/m", time());
                $uploadInfo = $upload->uploadXls($savePath, 'baoguan_temp_file');
                if ($uploadInfo['state'] != 1) {
                    throw new Exception($uploadInfo['message']);
                }
                $filePath = $uploadInfo['path'];
                $uploadProcess = new Process_BaoguanUpload();
                $uploadProcess->setFilePath($filePath);
                $headInfo = $uploadProcess->getBaseInfo();
                $bodyInfo = $uploadProcess->getBodyInfo();

                if (empty($headInfo) || empty($bodyInfo)) {
                    throw new Exception('上传报关单信息不存在');
                }
                $error = $uploadProcess->validateInfo($headInfo, $bodyInfo, $receiving_code);
                if (!empty($error)) {
                    $res['error'] = $error;
                } else {
                    //更新入库单报关单文件
                    $receiveRow = array(
                        'baoguan_file' => $filePath,
                        'receiving_update_time' => date("Y-m-d H:i:s", time()),
                    );
                    Service_Receiving::update($receiveRow, $receiving['receiving_id']);
                    $ASNLog = array(
                        'receiving_id' => $receiving['receiving_id'],
                        'receiving_code' => $receiving['receiving_code'],
                        'rl_type' => '0',
                        'user_id' => '-1',
                        'customer_code' => $receiving['customer_code'],
                        'rl_note' => "上传报关单",
                        'rl_status_from' => $receiving['receiving_status'],
                        'rl_status_to' => '2',    //方便测试暂时为4
                        'rl_add_time' => date('Y-m-d H:i:s', time()),
                        'rl_ip' => Common_Common::getIP(),
                        'extend_filed1' => $filePath,
                    );
                    Service_ReceivingLog::add($ASNLog);
                    $res['state'] = 1;
                    $res['message'] = "报关单上传成功";
                }
                //$db->rollBack();
                $db->commit();
            } catch (Exception $e) {
                $res['error'][] = $e->getMessage();
                $db->rollBack();
            }
            die(json_encode($res));
        }
    }


}