<?php
require_once 'PHPExcel.php';
require_once 'PHPExcel/IOFactory.php';

class Receiving_ReceivingController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "receiving/views/default/";
        $this->serviceClass = new Service_Receiving();
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $this->warehouse_id = $userAuth->warehouseId;
        $this->user_id = $userAuth->userId;
    }

    public function listAction()
    {
        $asnType = Common_Type::receivingType('auto');
        $asnStatus = Common_Status::receivingStatus('auto');

        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();
            $operationType = isset($params['operationType']) ? $params['operationType'] : '';
            $operationCode = isset($params['operationCode']) ? $params['operationCode'] : '';
            if (!empty($operationCode)) {
                $params[$operationType] = $operationCode;
            }
            $condition = $this->serviceClass->getMatchFields($params);
            if ($operationType == 'E18') {
                unset($condition['receiving_id']);
                $receiving = Service_ReceivingOrderDetail::getByCondition(array('order_code' => $operationCode), array('receiving_id'));
                if ($receiving) {
                    foreach ($receiving as $value) {
                        $condition['receiving_id'][$value['
                        receiving_id']] = $value['receiving_id'];
                    }
                }
            }
            $condition['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
            $condition['dateTo'] = isset($params['dateTo']) ? $params['dateTo'] : '';
            $condition['customer_code'] = trim(isset($params['E8']) ? $params['E8'] : '');
            $condition['is_delivery'] = isset($params['E41']) ? $params['E41'] : "";
            if (empty($condition['customer_code'])) {
                $condition['customer_code'] = trim(isset($params['cu']) ? $params['cu'] : '');
            }
            // if ($condition['is_delivery']=='') {
            //     $condition['is_delivery'] = trim(isset($params['de'])?$params['de']:'');
            // }
            $condition['receiving_status_arr'] = isset($params['receiving_status_arr']) ? trim($params['receiving_status_arr']) : '';
            unset($params);
            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields = array(
                    'receiving_code',
                    'reference_no',
                    'warehouse_id',
                    'customer_code',
                    'receiving_type',
                    'receiving_status',
                    'receiving_description',
                    'receiving_add_time',
                    'receiving_id',
                    'refercence_form_id',
                    'eda_date',
                    'receive_model_type',
                    'is_delivery',
                    'netweight',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition, $showFields, $pageSize, $page, array('receiving_id desc'));
                //print_r($rows);
                $wh = Common_DataCache::getWarehouseSimple();
                $userRight = Service_UserRight::getByField("/receiving/receiving/shenhe", "ur_url", "*");
                $urmCondition = array(
                    'ur_id' => $userRight['ur_id'],
                    'user_id' => $this->user_id
                );
                $userRightMap = Service_UserRightMap::getByCondition($urmCondition, "count(*)");
                if ($userRightMap) {
                    $return['shenheAuth'] = 1;
                } else {
                    $return['shenheAuth'] = 0;
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['type'] = $asnType;
                $return['status'] = $asnStatus;
                $return['warehouse'] = $wh;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        //$this->view->asnType = $asnType;
        // $this->view->asnStatus = $asnStatus;
        echo Ec::renderTpl($this->tplDirectory . "receiving_index.tpl", 'layout');
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'receiving_id')) {
            $rows = $this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    public function printListAction()
    {
        $Code = $this->_request->getParam('code', '');
        if (!empty($Code)) {
            $result = Service_ReceivingProcess::getAsnDetail($Code);
            if (isset($result['state']) && $result['state'] == '1') {
                $this->view->data = $result['data'];
            }
        }
        echo Ec::renderTpl($this->tplDirectory . "print_list.tpl", 'layout');
    }

    /*详细*/
    public function viewDetailAction()
    {
        $code = $this->_request->getParam('code', "");
        /*if(!empty($code)){
            $result= Service_ReceivingProcess::getAsnDetail($code);
            if(isset($result['state']) && $result['state']=='1'){
                $this->view->data=$result['data'];
            }
        }*/
        /*$QC = new Service_QualityControl();
        $QCList = $QC->getByCondition(array('receiving_code'=>$code),"*");
        $QCCodeArr = array();
        foreach($QCList as $key=>$value){
            if(!in_array($value['qc_code'],$QCCodeArr)){
                $QCCodeArr[] = $value['qc_code'];
            }
        }
        $result = array();
        foreach($QCCodeArr as $val){
            $qcObj= new Service_QualityControlProcess();
            $ret = $qcObj->getQcOrder($val);
            if($ret['state']){
                $qcData=$ret['data'];
                $customerId=isset($qcData['order']['customer_id'])?$qcData['order']['customer_id']:'-1';
                // print_r($qcData);
                //$this->view->data=$qcData;
                $qcData['package']=Service_ProductPackage::getByCondition(array('pp_status'=>1,'customer_id_arr'=>array(0,$customerId)),array('pp_id','pp_barcode','pp_name'));
                //$this->view->category=$category;
                //$qcData['category'] = $category;
                $result[] = $qcData;
            }
        }
        $this->view->result = $result;*/
        $this->view->category = Service_ProductCategoryEbay::getByCondition(array('pce_parent_id' => 1, 'pce_status' => 1), array('pce_id', 'pce_ebay_cid', 'pce_title'));
        $logService = new Service_ReceivingLog();
        $logs = $logService->getByCondition(array('receiving_code' => $code), "*", 0, 1, 'rl_id desc');
        if ($logs) {
            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'];
                }
            }
        }
        $this->view->logs = $logs;
        $batchService = new Service_ReceivingDetailBatch();
        $this->view->batch = $batchService->getByCondition(array('receiving_code' => $code), "*", 0, 1, "rdb_id desc");
        $this->view->code = $code;

        $qualitycontrol = Service_QualityControl::getByCondition(array('receiving_code' => $code), "*");
        foreach ($qualitycontrol as $key => $value) {
            $warehouse = Service_Warehouse::getByField($value['warehouse_id'], 'warehouse_id', "*");
            $qualitycontrol[$key]['warehouse_code'] = $warehouse['warehouse_code'];
        }
        $this->view->qualitycontrol = $qualitycontrol;

        $this->view->qcType = Common_Type::qcType();
        $this->view->qcStatus = Common_Type::qcStatus();

        $receivingRow = Service_Receiving::getByField($code, 'receiving_code', "*");

        $receiving_update_user = Service_User::getByField($receivingRow['receiving_update_user'], "user_id", "*");
        $receivingRow['receiving_update_user'] = $receiving_update_user['user_code'];

        $receiving_add_user = Service_User::getByField($receivingRow['receiving_add_user'], "user_id", "*");
        $receivingRow['receiving_add_user'] = $receiving_add_user['user_code'];

        $warehouse = Service_Warehouse::getByField($receivingRow['warehouse_id'], "warehouse_id", "*");
        $receivingRow['warehouse_code'] = $warehouse['warehouse_code'];

        $wrapType = Service_WrapType::getByField($receivingRow['wrap_type'], "wrap_type", "*");
        $IePort = Service_IePort::getByField($receivingRow['ie_port'], "ie_port", "*");
        $fromType = Service_FormType::getByField($receivingRow['form_type'], "form_type", "*");
        $tradeMode = Service_TradeMode::getByField($receivingRow['trade_mode'], "trade_mode", "*");
        $transMode = Service_TransMode::getByField($receivingRow['trans_mode'], "trans_mode", "*");
        $trafMode = Service_TrafMode::getByField($receivingRow['traf_mode'], "traf_mode", "*");
        $receivingRow['ie_port'] = $IePort['ie_port_name'];
        $receivingRow['wrap_type'] = $wrapType['wrap_type_name'];
        $receivingRow['form_type'] = $fromType['form_type_name'];
        $receivingRow['trade_mode'] = $tradeMode['trade_mode_name'];
        $receivingRow['trans_mode'] = $transMode['trans_mode_name'];
        $receivingRow['traf_mode'] = $trafMode['traf_mode_name'];
        if ($receivingRow['receive_model_type'] == 1) {

            $receivingOrderDetail = Service_ReceivingOrderDetail::getByCondition(array('receiving_code' => $code), "*");
            if ($receivingOrderDetail) {
                foreach ($receivingOrderDetail as &$row) {
                    $order_array = Service_Orders::getByField($row['order_code'], 'order_code');
                    if (!$order_array) {
                        continue;
                    }
                    $row['order_status'] = Service_Orders::getStatusText($order_array['order_status']);


                }
            }
            $this->view->receivingOrderDetail = $receivingOrderDetail;
        }
        $receivingDetail = Service_ReceivingDetail::getLeftJoinProductByCondition(array('receiving_code' => $code), "*");
        $ReceivingXml = Service_ReceivingXml::getByCondition(array('receiving_code' => $code), "*");
        $this->view->ReceivingXml = $ReceivingXml;
        $this->view->receivingDetail = $receivingDetail;

        $this->view->receivingRow = $receivingRow;

        $this->view->receivingType = Common_Type::receivingType();

        $this->view->receivingStatus = Common_Status::receivingStatus();

        echo Ec::renderTpl($this->tplDirectory . "view-detail.tpl", 'layout');
    }

    /**
     * @author william-fan
     * @todo 用于审核asn
     */
    public function shenheAction()
    {
        $rec_id = $this->_request->getParam('rec_id', '');
        if (!empty($rec_id)) {
            //$re  rec_id=R1306280001&expected=s
            $rec_id = $this->_request->getParam('rec_id', '');
            //$expected	= $this->_request->getParam('expected','');
            $paragram['receiving_code'] = $rec_id;
            //$paragram['expected']		= $expected;

            $result = Service_ReceivingProcess::shenhe($paragram);
            die(json_encode($result));
        }
    }

    public function readyReceiptAction()
    {//集货模式的收货
        $this->view->url = 'http://' . $_SERVER['HTTP_HOST'] . '/pdf-plugin/web/viewer.html?file=http://' . $_SERVER['HTTP_HOST'] . '/shipment/print/get-pdf-label/orderCode/';
        echo Ec::renderTpl($this->tplDirectory . "ready-receipt.tpl", 'layout');
    }

    public function totalWeightAction()
    {
        $receiving_code = $this->_request->getParam('receiving_code', "");
        $condition = array(
            'receiving_code' => $receiving_code
        );
        $result = array();
        $result['ask'] = "0";
        $receivingRow = Service_Receiving::getByField($receiving_code, 'receiving_code', "*");
        if (!empty($receivingRow)) {
            $result['asnRow'] = $receivingRow;
        }
        if (empty($receivingRow)) {
            $result['errorMsg'] = "Asn单 " . $receiving_code . " 不存在!";
            die(json_encode($result));
        }
        $session = new Zend_Session_Namespace('userAuthorization');
        $warehouseId = $session->warehouseId;
        if ($receivingRow['warehouse_id'] != $warehouseId) {
            $result['errorMsg'] = "ASN " . $receiving_code . " 不属于当前仓库";
            die(json_encode($result));
        }
        $receivingOrder = Service_ReceivingOrderDetail::getByCondition($condition, "*");
        $orderList = array();
        $sum = 0;
        foreach ($receivingOrder as $key => $v) {
            $order = Service_Orders::getByField($v['order_code'], "order_code", "*");
            $shipOrders = Service_ShipOrder::getByField($v['order_code'], "order_code", "*");
            $sum += $shipOrders['so_weight'];

            if ($order['order_status'] < 8) {
                $orderList[] = $order;
            }

        }
        $result['weight'] = $sum;
        $result['ask'] = 1;
        $result['data'] = $orderList;

        //print_r($result);exit;
        // return $result;
        die(json_encode($result));

    }

    public function getUnReceiptAction()
    {
        $receiving_code = $this->_request->getParam('receiving_code', "");
        $condition = array(
            'receiving_code' => $receiving_code,
            'rd_status' => '0'
        );
        $result = array();
        $result['ask'] = "0";
        $receivingRow = Service_Receiving::getByField($receiving_code, 'receiving_code', "*");
        if (!empty($receivingRow)) {
            $result['asnRow'] = $receivingRow;
        }
        if (empty($receivingRow)) {
            $result['errorMsg'] = "Asn单 " . $receiving_code . " 不存在!";
            die(json_encode($result));
        }
        if ($receivingRow['receiving_status'] == '7') {
            $result['errorMsg'] = "Asn单 " . $receiving_code . " 已收货完成!";
            die(json_encode($result));
        }
        if (!in_array($receivingRow['receiving_status'], array('5', '6'))) {
            $status = Service_ReceivingProcess::getStatus();
            $result['errorMsg'] = "Asn单 " . $status[$receivingRow['receiving_status']] . " 不是在途或是收货中状态,不能收货!";
            die(json_encode($result));
        }
        if ($receivingRow['receive_model_type'] != "1") {
            $result['errorMsg'] = "Asn单 " . $receiving_code . " 不是集货模式,不能收货!";
            die(json_encode($result));
        }
        $session = new Zend_Session_Namespace('userAuthorization');
        $warehouseId = $session->warehouseId;
        if ($receivingRow['warehouse_id'] != $warehouseId) {
            $result['errorMsg'] = "ASN " . $receiving_code . " 不属于当前仓库";
            die(json_encode($result));
        }

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if ($receivingRow['receiving_status'] == "5") {
                $updateReceiving = array(
                    'receiving_status' => '6',
                    'receiving_update_time' => date("Y-m-d H:i:s"),
                );
                Service_Receiving::update($updateReceiving, $receiving_code, 'receiving_code');
                $ASNLog = array(
                    'receiving_id' => $receivingRow['receiving_id'],
                    'receiving_code' => $receiving_code,
                    'user_id' => $this->user_id,
                    'customer_code' => $receivingRow['customer_code'],
                    'rl_note' => "收货中",
                    'rl_status_from' => $receivingRow['receiving_status'],
                    'rl_status_to' => "6",
                    'rl_add_time' => date("Y-m-d H:i:s"),
                    'rl_ip' => Common_Common::getIP()
                );
                //print_r($ASNLog);
                Service_ReceivingLog::add($ASNLog);
                $updateReceivingAttribute = array(
                    'receiving_time' => date("Y-m-d H:i:s"),
                );
                Service_ReceivingAttribute::update($updateReceivingAttribute, $receiving_code, 'receiving_code');
            }
            $db->commit();
        } catch (Exception $e) {
            $db->rollBack();
            $result['ask'] = "-1";
            $result['errorMsg'] = "收货失败!";
            die(json_encode($result));
        }

        $receivingOrder = Service_ReceivingOrderDetail::getByCondition($condition, "*");
        $orderList = array();
        foreach ($receivingOrder as $key => $v) {
            $order = Service_Orders::getByField($v['order_code'], "order_code", "*");
            $shipOrder = Service_ShipOrder::getByField($v['order_code'], "order_code", "*");
            $order['tracking_number'] = isset($shipOrder['tracking_number']) ? $shipOrder['tracking_number'] : "";
            $orderList[] = $order;
        }
        $result['ask'] = 1;
        $result['data'] = $orderList;
        die(json_encode($result));
    }

    /**
     * @todo 扫描订单
     * @updateDate 2013-11-20 如果挂号的换单的情况下就从系统分配一个服务商单号给订单，并且打印出label
     */
    public function receiptAction()
    {
        $receiving_code = $this->_request->getParam("receiving_code", "");
        $order_code = $this->_request->getParam("order_code", "");
        $sm_code = $this->_request->getParam('sm_code', "");
        $orderRow = Service_Orders::getByField($order_code, "order_code", "*");
        $str = "订单";
        if (empty($orderRow)) {
            //$orderRow = Service_Orders::getByField($order_code,"ref_tracking_number","*");
            //$orderRow = array();
            $orderList = Service_Orders::getByCondition(array('ref_tracking_number' => $order_code, 'sm_code' => $sm_code, 'order_status_neq' => 0), "*");
            if (!empty($orderList)) $orderRow = $orderList[0];
            $str = "服务商单号";
        }
        $result = array();
        $result['ask'] = "0";
        $result['isPrint'] = '0'; //是否答应label

        if (empty($orderRow)) {
            $result['errorMsg'] = "订单号或服务单号 " . $order_code . " 不存在";
            die(json_encode($result));
        }

        // 不是集货模式且订单不是已提交状态，扫描失败
        if (1 !== (int)$orderRow['order_mode_type'] || 4 !== (int)$orderRow['order_status']) {
            $result['errorMsg'] = $str . '【' . $order_code . '】不是';
            $result['errorMsg'] .= (1 !== (int)$orderRow['order_mode_type']) ? '集货模式' : '已提交状态';
            exit(json_encode($result));
        }
        $smCodePrintWhile = array('SZY-EUB', 'UKTL', 'SZY-ETK', 'BH-USPS', 'SZY-EMS', 'BH-DPD', 'SF-RUPR', 'SF-RUPT', 'Rumall-RU-EP', 'Rumall-RU-G', 'CJ-DGMG', 'CJ-DGMP', 'BH-DHL-HKDELIVERY', 'DGM-US');
        $result['smCode'] = $orderRow['sm_code'];
        if (in_array($orderRow['sm_code'], $smCodePrintWhile)) {
            $result['isPrint'] = '1'; //是否答应label
        }

        $smCodeWhile = array('SZY-EUB', 'UKTL', 'SZY-ETK', 'BH-USPS', 'BH-DPD', 'SF-RUPR', 'SF-RUPT', 'Rumall-RU-EP', 'Rumall-RU-G', '4PX-LYT_GH', '4PX-EU_PACKET', '4PX-RU_POST-LINK_RMAIL', '4PX-HKDHL', '4PX-YX', '4PX-SG_ordinary_mail+', 'CJ-DGMG', 'CJ-DGMP', 'DGM-US');
        if (in_array($orderRow['sm_code'], $smCodeWhile) && $orderRow['ref_tracking_number'] == "") {
            $result['errorMsg'] = $orderRow['sm_code'] . "订单未获取运单号不可扫描";
            die(json_encode($result));
        }

        // 传回订单信息，以便自动打印
        $result['orderData']['order'] = $orderRow;
        $orderAddress = Service_OrderAddressBook::getByField($orderRow['order_code'], 'order_code');
        $orderCountry = $orderAddress ? Service_Country::getByField($orderAddress['oab_country_id'], 'country_id') : FALSE;
        $result['countryCode'] = $orderCountry ? $orderCountry['country_code'] : '';

        $receivingOrder = Service_ReceivingOrderDetail::getByField($orderRow['order_code'], "order_code", "*");
        //die($receivingOrder['receiving_code']."&".$receiving_code);
        if ($receivingOrder['receiving_code'] != $receiving_code) {
            $result['errorMsg'] = $str . " " . $order_code . " 不在ASN单" . $receiving_code;
            die(json_encode($result));
        }
        if ($receivingOrder['rd_status'] != "0") {
            $result['errorMsg'] = $str . " " . $order_code . " 已收货";
            die(json_encode($result));
        }
        $session = new Zend_Session_Namespace('userAuthorization');
        $warehouseId = $session->warehouseId;
        if ($orderRow['warehouse_id'] != $warehouseId) {
            $result['errorMsg'] = $str . " " . $order_code . " 的交货仓储不是当前仓储!";
            die(json_encode($result));
        }
        //die("XXXXXXXX");
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            //运输方式是挂号的  从系统分配一个服务商单号
            $shipMethodCondition = array(
                //'warehouse_id_arr'=>array('0',$warehouseId),
                'sm_code' => $orderRow['sm_code'],
                'sm_status' => '1',
            );
            $shipMethodArr = Service_ShippingMethod::getByCondition($shipMethodCondition, '*', 1, 1);
            if (empty($shipMethodArr)) {
                throw new Exception("该仓库下不存在{$orderRow['sm_code']}或者{$orderRow['sm_code']}不可用");
            } else {
                $shipMethod = $shipMethodArr[0];
            }
            /*$serviceTracking = Service_ServiceTrackingNumber::getByField($orderRow['order_code'],'order_code');
            if(!empty($serviceTracking)){
                throw new Exception('该订单号已经分配过服务商单号');
            }*/
            $dateTime = date("Y-m-d H:i:s", time());

            $dateTime = date("Y-m-d H:i:s", time());
            $ref_trackingNumber = $orderRow['ref_tracking_number'];
            $shipOrder = Service_ShipOrder::getByField($orderRow['order_code'], 'order_code');
            if ($ref_trackingNumber != '') {
                if (!empty($shipOrder)) {
                    //在Ship_Order表插入一条数据，Tracking_No为订单号
                    //存在就更新数据
                    $shipOrderRow = array(
                        'tracking_number' => $ref_trackingNumber,
                        'so_update_time' => date("Y-m-d H:i:s", time()),
                    );
                    Service_ShipOrder::update($shipOrderRow, $orderRow['order_code']);
                } else {
                    $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $orderRow['customer_code'], 'SP');
                    //不存在就插入数据
                    $shipOrderRow = array(
                        'so_code' => $soCode,
                        'order_id' => $orderRow['order_id'],
                        'order_code' => $orderRow['order_code'],
                        'tracking_number' => $ref_trackingNumber,
                        'warehouse_id' => $warehouseId,
                        'pp_barcode' => '',
                        'sm_code' => $orderRow['sm_code'],
                        'so_status' => '0',
                        'so_weight' => '',
                        'so_vol_weight' => '',
                        'so_length' => '',
                        'so_width' => '',
                        'so_height' => '',
                        'so_declared_value' => '',
                        'so_shipping_fee' => '',
                        'currency_code' => '',
                        'so_add_time' => $dateTime,
                        'so_ship_time' => $dateTime,
                        'so_update_time' => $dateTime,
                    );
                    Service_ShipOrder::add($shipOrderRow);
                }
            } else {
                //订单里面的跟踪号为空
                switch ($shipMethod['sm_class_code']) {
                    //CRE:快递;CRP:挂号;CPS:平邮'
                    case "CRE":
                        //快递的程序
                        if (!empty($shipOrder)) {
                            //在Ship_Order表插入一条数据，Tracking_No为订单号
                            //存在就更新数据
                            $shipOrderRow = array(
                                'tracking_number' => $orderRow['order_code'],
                                'so_update_time' => date("Y-m-d H:i:s", time()),
                            );
                            Service_ShipOrder::update($shipOrderRow, $orderRow['order_code']);
                        } else {
                            $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $orderRow['customer_code'], 'SP');
                            //不存在就插入数据
                            $shipOrderRow = array(
                                'so_code' => $soCode,
                                'order_id' => $orderRow['order_id'],
                                'order_code' => $orderRow['order_code'],
                                'tracking_number' => $orderRow['order_code'],
                                'warehouse_id' => $warehouseId,
                                'pp_barcode' => '',
                                'sm_code' => $orderRow['sm_code'],
                                'so_status' => '0',
                                'so_weight' => '',
                                'so_vol_weight' => '',
                                'so_length' => '',
                                'so_width' => '',
                                'so_height' => '',
                                'so_declared_value' => '',
                                'so_shipping_fee' => '',
                                'currency_code' => '',
                                'so_add_time' => $dateTime,
                                'so_ship_time' => $dateTime,
                                'so_update_time' => $dateTime,
                            );
                            Service_ShipOrder::add($shipOrderRow);
                        }
                        break;
                    case "CRP":
                        //挂号的程序
                        /*在Ship_Order表插入一条数据，Tracking_No为表service_tracking_numbe
                         中未分配的且运输方式匹配的任意一条数据*/
                        $conditionTrackinNumber = array(
                            'warehouse_id' => $this->warehouse_id,
                            'sm_code' => $orderRow['sm_code'],
                            'stn_status' => '0',
                        );
                        $trackingNumber = Service_ServiceTrackingNumber::getByConditionLock($conditionTrackinNumber, '*', 1, 1);
                        $trackingNumberDate = $trackingNumber[0];
                        /*if(!empty($trackingNumber)){
                         $trackingNumberDate = $trackingNumber[0];
                        $serviceTrackingNumberRow = array(
                                'order_code'=>$orderRow['order_code'],
                                'stn_status'=>'1',
                                'stn_update_time'=>date('Y-m-d H:i:s',time()),
                        );
                        Service_ServiceTrackingNumber::update($serviceTrackingNumberRow, $trackingNumberDate['stn_id']);
                        //$change_tracking = Service_ServiceTrackingNumber::getTrackingNumber($orderRow['sm_code'], $trackingNumberDate['stn_code']);
                        $change_tracking = $trackingNumberDate['stn_code'];
                        $orderRow['tracking_number'] = $change_tracking;
                        $result['isPrint'] = '1';
                        $result['orderDate']['order'] = $orderRow;
                        }else{
                        //没有服务商单号
                        throw new Exception('没有该运输方式的服务商单号,无法分配');
                        }*/
                        //oms已经分配了跟踪号 若为空 证明数据异常
                        throw new Exception('挂号在OMS分配服务商单号数据异常');

                        /* if(!empty($shipOrder)){
                         //在Ship_Order表插入一条数据，Tracking_No为订单号
                        //存在就更新数据
                        $shipOrderRow = array(
                                'tracking_number'=>$trackingNumberDate['ref_tracking_number'],
                                'so_update_time'=>date("Y-m-d H:i:s",time()),
                        );
                        Service_ShipOrder::update($shipOrderRow, $orderRow['order_code']);
                        }else{
                        $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $orderRow['customer_code'], 'SP');
                        //不存在就插入数据
                        $shipOrderRow = array(
                                'so_code'=>$soCode,
                                'order_id'=>$orderRow['order_id'],
                                'order_code'=>$orderRow['order_code'],
                                'tracking_number'=>$orderRow['ref_tracking_number'],
                                'warehouse_id'=>$warehouseId,
                                'pp_barcode'=>'',
                                'sm_code'=>$orderRow['sm_code'],
                                'so_status'=>'0',
                                'so_weight'=>'',
                                'so_vol_weight'=>'',
                                'so_length'=>'',
                                'so_width'=>'',
                                'so_height'=>'',
                                'so_declared_value'=>'',
                                'so_shipping_fee'=>'',
                                'currency_code'=>'',
                                'so_add_time'=>$dateTime,
                                'so_ship_time'=>$dateTime,
                                'so_update_time'=>$dateTime,
                        );
                        Service_ShipOrder::add($shipOrderRow);
                        } */
                        break;
                    case "CPS":
                        //平邮的程序
                        if (!empty($shipOrder)) {
                            //在Ship_Order表插入一条数据，Tracking_No为订单号
                            //存在就更新数据
                            $shipOrderRow = array(
                                'tracking_number' => $orderRow['order_code'],
                                'so_update_time' => date("Y-m-d H:i:s", time()),
                            );
                            Service_ShipOrder::update($shipOrderRow, $orderRow['order_code']);
                        } else {
                            $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $orderRow['customer_code'], 'SP');
                            //不存在就插入数据
                            $shipOrderRow = array(
                                'so_code' => $soCode,
                                'order_id' => $orderRow['order_id'],
                                'order_code' => $orderRow['order_code'],
                                'tracking_number' => $orderRow['order_code'],
                                'warehouse_id' => $warehouseId,
                                'pp_barcode' => '',
                                'sm_code' => $orderRow['sm_code'],
                                'so_status' => '0',
                                'so_weight' => '',
                                'so_vol_weight' => '',
                                'so_length' => '',
                                'so_width' => '',
                                'so_height' => '',
                                'so_declared_value' => '',
                                'so_shipping_fee' => '',
                                'currency_code' => '',
                                'so_add_time' => $dateTime,
                                'so_ship_time' => $dateTime,
                                'so_update_time' => $dateTime,
                            );
                            Service_ShipOrder::add($shipOrderRow);
                        }
                        break;
                    default :
                        if (!empty($shipOrder)) {
                            //在Ship_Order表插入一条数据，Tracking_No为订单号
                            //存在就更新数据
                            $shipOrderRow = array(
                                'tracking_number' => $orderRow['order_code'],
                                'so_update_time' => date("Y-m-d H:i:s", time()),
                            );
                            Service_ShipOrder::update($shipOrderRow, $orderRow['order_code']);
                        } else {
                            $soCode = $soCode = Common_GetNumbers::getCode('shiporder', $orderRow['customer_code'], 'SP');
                            //不存在就插入数据
                            $shipOrderRow = array(
                                'so_code' => $soCode,
                                'order_id' => $orderRow['order_id'],
                                'order_code' => $orderRow['order_code'],
                                'tracking_number' => $orderRow['order_code'],
                                'warehouse_id' => $warehouseId,
                                'pp_barcode' => '',
                                'sm_code' => $orderRow['sm_code'],
                                'so_status' => '0',
                                'so_weight' => '',
                                'so_vol_weight' => '',
                                'so_length' => '',
                                'so_width' => '',
                                'so_height' => '',
                                'so_declared_value' => '',
                                'so_shipping_fee' => '',
                                'currency_code' => '',
                                'so_add_time' => $dateTime,
                                'so_ship_time' => $dateTime,
                                'so_update_time' => $dateTime,
                            );
                            Service_ShipOrder::add($shipOrderRow);
                        }
                }
            }
            $order_status = '7'; //已录单
            //CRE:快递;CRP:挂号;CPS:平邮'
            if ($shipMethod['sm_class_code'] == 'CRE') {
                $order_status = '7';
            }
            $updateOrderRow = array(
                'order_status' => '7',
                //'change_order'=>'0',
                'time_of_receipt' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            );
            $oid = Service_Orders::update($updateOrderRow, $orderRow['order_id'], "order_id");
            $orderLog = array(
                'order_id' => $orderRow['order_id'],
                'order_code' => $orderRow['order_code'],
                'ol_type' => '1',
                'order_status_from' => $orderRow['order_status'],
                'order_status_to' => $order_status,
                'ol_add_time' => date("Y-m-d H:i:s"),
                'user_id' => $this->user_id,
                'ol_ip' => Common_Common::getIP()
            );
            Service_OrderLog::add($orderLog);

            $w = Service_Warehouse::getByField($orderRow['warehouse_id'], 'warehouse_id', '*');
            $shipOrderTracking = array(
                'order_code' => $orderRow['order_code'],
                'sot_location' => $w['warehouse_desc'],
                'sot_add_time' => date("Y-m-d H:i:s"),
                'warehouse_id' => $orderRow['warehouse_id'],
                'sot_description' => '集货ASN仓库收货中',
                'sot_type' => '0',
                'sot_time_offset' => '',
                'tracking_number' => $orderRow['order_code'],
                'ref_tracking_number' => '',
                'status_desc' => '已打包',
                'user_id' => $this->user_id
            );
            Service_ShipOrderTracking::add($shipOrderTracking);

            $updateROD = array(
                'rd_status' => '1',
                'rd_update_time' => date("Y-m-d H:i:s")
            );
            $rodid = Service_ReceivingOrderDetail::update($updateROD, $receivingOrder['rod_id'], "rod_id");
            $orderOperationTime = array(
                'pack_time' => date("Y-m-d H:i:s"),
                'pack_user_id' => $this->user_id,
            );
            Service_OrderOperationTime::update($orderOperationTime, $orderRow['order_code'], 'order_code');
            $db->commit();
            //$db->rollBack();
            $result['ask'] = "1";
            $result['successMsg'] = $str . " " . $order_code . " 扫描成功!";
            $result['orderData']['ship']['ref_tracking_number'] = isset($shipOrderRow) ? $shipOrderRow['tracking_number'] : $shipOrder['tracking_number'];
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code' => $order_code), "*");
            $op = 0;  //订单的总目的海关申报价值
            $batterType = 0; //订单内带电池类型
            foreach ($orderProduct as $k => $v) {
                $p = Service_Product::getByField($v['product_id'], "product_id", "*");
                $order = Service_Orders::getByField($v['order_id'], "order_id", "*");
                $orderProduct[$k]['product_sku'] = $p['product_sku'];
                $orderProduct[$k]['product_barcode'] = $p['product_barcode'];
                if ($order['sm_code'] == 'BH-DPD') {
                    $op += $v['op_purpose_declared_value'] * $v['op_quantity'];
                }
                if ($p['battery_type'] == '1') {
                    $batterType = '1';
                }
            }
            $op = Service_Currency::converByCode('USD', 'EUR', $op);
            $result['product'] = $orderProduct;
            $result['battery_type'] = $batterType;
            if ($op > 300) {
                $result['op'] = $op;
            }
        } catch (Exception $e) {
            $db->rollBack();
            $result['errorMsg'][] = $e->getMessage();
        }
        die(json_encode($result));
    }

    public function completeAction()
    {
        $receivingCode = $this->_request->getParam('receiving_code', "");
        $receivingRow = Service_Receiving::getByField($receivingCode, "receiving_code", "*");
        $weight = $this->_request->getParam('weight', '');
        $_otherfee_mix_arr = Process_BillConfig::getOtherFeeArr();
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        $fee_cost_detail = array(); /* 费用及成本明细 */
        $spArr = array();
        $date = date('Y-m-d H:i:s');
        $remote_ip = Common_Common::getIP();
        if (empty($receivingRow)) {
            $result['ask'] = "0";
            $result['errorMsg'] = "Asn单 " . $receivingCode . " 不存在!";
            die(json_encode($result));
        }
        $result = array();
        if ($receivingRow['receiving_status'] == "7") {
            $result['ask'] = "0";
            $result['errorMsg'] = "Asn单 " . $receivingCode . " 已收货完成!";
            die(json_encode($result));
        }
        $condition = array(
            'receiving_code' => $receivingCode
        );
        $RODList = Service_ReceivingOrderDetail::getByCondition($condition, "*");
        //总件数
        $pieces = count($RODList);
        //$pieces=$receivingRow['pack_no'];
        $umcomplete = false;
        $errorMsg = "";

        foreach ($RODList as $k => $v) {
            if ($v['rd_status'] == "0") {
                $umcomplete = true;
                $errorMsg .= $v['order_code'] . " ";
            }
        }
        if ($umcomplete) {
            $result['ask'] = 0;
            $result['errorMsg'] = $errorMsg . "未扫描!";
            die(json_encode($result));
        }

        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if (!($weight > 0)) {
                throw new Exception('ASN重量必须填写,且重量必须大于0');
            }
            $ROD = array(
                'rd_status' => '2'
            );
            Service_ReceivingOrderDetail::update($ROD, $receivingCode, "receiving_code");
            foreach ($RODList as $k => $v) {
                /*$row = array(
                    'order_status'=>'7'
                );
                Service_Orders::update($row,$v['order_code'],"order_code");*/
                $order = Service_Orders::getByField($v['order_code'], "order_code", "*");
                $packObj = new Service_PackProcess();
                $return = $packObj->jhpack($v['order_code'], $packingCode = "", $order['order_pick_type'], null);
            }

            $rec = array(
                'receiving_status' => '7',
                'receiving_update_time' => date("Y-m-d H:i:s"),
                'netweight' => $weight,
            );

            Service_Receiving::update($rec, $receivingCode, "receiving_code");
            $ASNLog = array(
                'receiving_id' => $receivingRow['receiving_id'],
                'receiving_code' => $receivingCode,
                'user_id' => $this->user_id,
                'customer_code' => $receivingRow['customer_code'],
                'rl_note' => "收货中->收货完成",
                'rl_status_from' => $receivingRow['receiving_status'],
                'rl_status_to' => "7",
                'rl_add_time' => date("Y-m-d H:i:s"),
                'rl_ip' => Common_Common::getIP()
            );
            //print_r($ASNLog);
            Service_ReceivingLog::add($ASNLog);
            $ura = array(
                'complete_received_time' => date("Y-m-d H:i:s"),
            );
            Service_ReceivingAttribute::update($ura, $receivingCode, "receiving_code");
            if ($receivingRow['is_delivery'] == '1') {
                //$receinvRow['netweight'] = $weight;
                $incomeArr = $paymentArr = array();
                $objOtherCalculte = new Common_CalculateOtherFee();

                $keys = array(
                    'warehouseId' => $receivingRow['warehouse_id'],
                    'receiving_weight' => $weight,
                    'receiving_code' => $receivingCode,
                );
                $objOtherCalculte->setParams($keys);
                $otherfeeArr = $objOtherCalculte->getOtherFee('TIHUO');
                $otherfee_tihuo = $otherfeeArr['data']['otherFee']['tihuo'];
                //print_r($otherfee_tihuo);
                $asnOrder = $receivingRow;
                $asnOrder['order_code'] = $asnOrder['receiving_code'];
                $customerArr = Service_Customer::getByField($receivingRow['customer_code'], 'customer_code', array('customer_saler_user_id', 'customer_currency'));
                $fee_detail = $cost_detail = array();
                if ($otherfee_tihuo['price'] > 0) {
                    $tihuoOtherFee = Service_OtherFee::getByField('TIHUO', 'fee_code');
                    if (!empty($tihuoOtherFee)) {
                        Service_ReceivingProcess::unfreezeFee($asnOrder, $objOtherCalculte, 'TIHUO', 'ASN收货，解冻');
                        //Service_CustomerBalanceProcess::unfreezeOtherFeeById($asnOrder,$tihuoOtherFee['fee_id'],'ASN收货,解冻提货费');
                    }
                    $result = Service_CustomerBalanceProcess::deductFee($receivingRow['customer_id'], $otherfee_tihuo, 'ASN收货，扣提货费', $receivingCode, 'TIHUO', $otherfee_tihuo['fee_id']);

                    //转为客户币种
                    $convert_fee = Service_Currency::converByCode($otherfee_tihuo['currency_code'], $customerArr['customer_currency'], $otherfee_tihuo['price']);
                    //应收
                    $incomeArr[] = array(
                        'customer_code' => $asnOrder['customer_code'],
                        'ft_code' => 'TIHUO',
                        'ut_code' => 'PCE',
                        'sm_code' => '',
                        'bi_amount' => $convert_fee,
                        'bi_org_amount' => $otherfee_tihuo['price'],
                        'currency_code' => $otherfee_tihuo['currency_code'],
                        'currency_rate' => '',
                        'bi_chargeable_time' => date("Y-m-d H:i:s"),
                        'bi_note' => '提货费',
                    );

                    $fee_detail = array(
                        'fee_amount_customer' => $convert_fee,                        //费用金额（客户）
                        'fee_currency_code_customer' => $customerArr['customer_currency'],   //费用币种（客户）
                        'discount_customer' => $otherfee_tihuo['discount'],         //折扣率（客户）（1=100%）
                    );
                }

                //应付费用  服务商不能为空
                if (isset($otherfee_tihuo['cost']) && $otherfee_tihuo['sp_code'] != '' && $otherfee_tihuo['cost'] > 0) {
                    $spRow = Service_ServiceProvider::getByField($otherfee_tihuo['sp_code'], 'sp_code');
                    $sp_currency_code = $spRow['currency_code'];
                    //转为服务商币种
                    $convert_fee = Service_Currency::converByCode($otherfee_tihuo['currency_code'], $sp_currency_code, $otherfee_tihuo['cost']);
                    $paymentArr[] = array(
                        'sp_code' => $otherfee_tihuo['sp_code'], //服务商代码
                        'ft_code' => 'TIHUO',
                        'ut_code' => 'PCE',
                        'sm_code' => '',
                        'bp_amount' => $convert_fee,
                        'bp_org_amount' => $otherfee_tihuo['cost'],
                        'currency_code' => $otherfee_tihuo['currency_code'],
                        'currency_rate' => '',
                        'bp_chargeable_time' => date("Y-m-d H:i:s"),
                    );

                    $cost_detail = array(
                        'cost_amount_org' => $otherfee_tihuo['cost'],             //成本金额（原始）
                        'cost_currency_code_org' => $otherfee_tihuo['currency_code'],    //成本币种（原始）
                        'cost_amount_sp' => $convert_fee,                        //成本金额（服务商）
                        'cost_currency_code_sp' => $sp_currency_code,                   //成本币种（服务商）
                        'sp_code' => $otherfee_tihuo['sp_code'],           //服务商代码
                    );
                }
                //判断是否存在应收、应付
                if (!empty($incomeArr) || !empty($paymentArr)) {
                    //写入业务表
                    $businessArr = array(
                        'ds_code' => 'asn',
                        'customer_code' => $receivingRow['customer_code'],
                        'warehouse_id' => $receivingRow['warehouse_id'],
                        'sm_code' => '',
                        'bb_volume_weight' => $weight,
                        'bb_charge_weight' => $weight,
                        'bb_delivered_weight' => $weight,
                        'bb_pieces' => $pieces,
                        'bb_declared_value' => 0,
                        'bb_declared_currency_code' => 'USD',
                        'country_code' => '',
                        'bb_postcode' => '',
                        'bb_charge_time' => date("Y-m-d H:i:s"),
                        'bb_declared_time' => date('Y-m-d H:i:s'), //发货时间 此时间与服务商对接
                        'bb_sales_id' => $customerArr['customer_saler_user_id'],

                        'bb_refer_code' => $asnOrder['receiving_code'],
                        'bb_service_number' => '',//ref_tracking_number
                        'bb_reference_no' => '',
                    );
                    $bsObj = new Process_Business();
                    $businessResult = $bsObj->businessFee($businessArr, $incomeArr, $paymentArr);
                    if ($businessResult['state'] != '1') {
                        throw new Exception($businessResult['message']);
                    }
                }

                if (!empty($fee_detail) || !empty($cost_detail)) {
                    $fee_cost_common = array(
                        'code_number' => $receivingCode,                          //单号
                        'code_type' => 3,                                       //单号类型（1:区内单 2：区外单 3：ASN单）
                        'customer_code' => $receivingRow['customer_code'],          //客户代码
                        'reference_no' => $receivingRow['reference_no'],           //客户参考号
                        'tracking_number' => '',                                      //服务商单号（跟踪号）
                        'sm_code' => '',                                      //运输方式代码
                        'country_code' => '',                                      //国际简称（二字码）
                        'fee_code' => 'TIHUO',                                 //费用编号
                        'fee_name' => $_otherfee_mix_arr['tihuo']['binote'],   //费用名称
                        'fee_amount_org' => $otherfee_tihuo['price'],                //费用金额（原始）
                        'fee_currency_code_org' => $otherfee_tihuo['currency_code'],        //费用币种（原始）
                        'price_batch_number' => '',                                      //运输价格编号
                        'currency_batch_number' => '',                                      //货币汇率编号
                        'fee_time' => $date,                                   //扣费时间
                        'fee_time_recalculate' => $date,                                   //重新扣费时间
                        'ip' => $remote_ip,                              //扣费操作IP
                        'ip_recalculate' => $remote_ip,                              //重新扣费操作IP
                        'operator' => $userAuth->user['user_name'],            //扣费操作人
                        'operator_recalculate' => $userAuth->user['user_name'],            //重新扣费操作人
                    );
                    $fee_cost_detail = array_merge($fee_detail, $cost_detail, $fee_cost_common);
                    $feecostdetailResult = Service_FeeCostDetail::add($fee_cost_detail);
                }

            }
            $db->commit();
            //$db->rollBack();
            $result['ask'] = 1;
            $result['successMsg'] = "Asn单" . $receivingCode . "收货完成!";
        } catch (Exception $e) {
            $db->rollBack();
            $result['ask'] = "0";
            $result['errorMsg'] = $e->getMessage();
            //$result['errorMsg'][] = $e->getMessage();
        }
        die(json_encode($result));
    }


    // 打印入区入库派车单收货单验证
    public function printCscmEcoValidateAction()
    {
        $response = array('status' => 0, 'message' => '非法请求');

        if ($this->getRequest()->isPost()) {
            $receivingCode = $this->getRequest()->getPost('selectedCode', NULL);
            $filterCode = array();
            $error = array();

            if (is_array($receivingCode)) {
                foreach ($receivingCode as $code) {
                    if ('' !== trim($code)) {
                        $filterCode[trim($code)] = trim($code);
                    }
                }
            }

            if (!empty($filterCode)) {
                foreach ($filterCode as $key => $value) {
                    $receiving = Service_Receiving::getByField($value, 'receiving_code');

                    if (!empty($receiving)) {
                        if (!in_array((int)$receiving['receiving_status'], array(3, 4, 5), TRUE)) {
                            $error[] = '收货单【' . $value . '】不是已审核或在途状态';
                        }
                    } else {
                        $error[] = '收货单【' . $value . '】不存在';
                    }
                }
            }

            if (!empty($error)) {
                $response['message'] = '打印入区入库派车单失败，原因：<br />' . join($error, '<br />');
            } else {
                $response['status'] = 1;
                $response['message'] = '__IT_IS_VALID_DATA__';
            }
        }

        exit(Zend_Json::encode($response));
    }

    // 打印入区入库派车单
    public function printCscmEcoAction()
    {
        $receivingCode = $this->getRequest()->getParam('selectedCode', NULL);
        $car = trim($this->getRequest()->getParam('car', ''));
        $filterCode = array();
        $error = array();
        $this->view->isError = FALSE;

        if (is_array($receivingCode)) {
            foreach ($receivingCode as $code) {
                if ('' !== trim($code)) {
                    $filterCode[trim($code)] = trim($code);
                }
            }
        }

        if (!empty($filterCode)) {
            foreach ($filterCode as $key => $value) {
                $receiving = Service_Receiving::getByField($value, 'receiving_code');

                if (!empty($receiving)) {
                    if (!in_array((int)$receiving['receiving_status'], array(3, 4, 5), TRUE)) {
                        $error[] = '收货单【' . $value . '】不是已审核或在途状态';
                    } else {
                        $filterCode[$key] = $receiving;
                    }
                } else {
                    $error[] = '收货单【' . $value . '】不存在';
                }
            }

            if ('' === $car) {
                $error[] = '缺乏车牌信息';
            }
        } else {
            $error[] = '非法请求';
        }

        if (!empty($error)) {
            $this->view->isError = TRUE;
            $this->view->errorContent = join($error, '<br />');
        } else {
            $car = preg_replace('/([a-zA-Z0-9]+)/', '<span class="english">\1</span>', $car);

            $this->view->carNumber = $car;
            $this->view->receiving = $filterCode;
            $this->view->totalReceiving = count($filterCode);
        }

        echo $this->view->render($this->tplDirectory . 'cscm-eco.tpl');
    }

    public function printAction()
    {
        $ASNCode = $this->_request->getParam('ASNCode', '');
        if (!empty($ASNCode)) {
            $aFtpMessageType = Service_FtpMessageType::getByField('MRK', 'fmt_code');
            $receivingRow = Service_Receiving::getByField($ASNCode, 'receiving_code', "*");
            $result = Service_AsnProccess::getAsnInfo($ASNCode, $receivingRow['customer_id']);
            $receivingInfo = $result['result'];
            if ($receivingInfo['asnRow']['receiving_status'] != '4') {
                //$this->_redirect('');
                exit('状态不对不允许重新打印');
            }
            $customerRow = Service_Customer::getByField($receivingInfo['asnRow']['customer_id']);
            $customerinfo = $customerRow;

            //申报海关
            $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, $receivingRow['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']);
            }
        }
    }

    /**
     * [returnReceivingAction 退回草稿]
     * @return [type] [description]
     */
    public function returnDeleteAction()
    {
        $asnStatus = Common_Status::receivingStatus('auto');
        $result = array(
            "state" => 0,
            "message" => "Fail.",
        );
        if ($this->_request->isPost()) {

            $reason = $this->_request->getPost('reasonData');
            //$action = $this->_request->getPost('action');
            if (empty($reason)) {
                $result = array(
                    "state" => 0,
                    "message" => "请填写备注.",
                );

                die(Zend_Json::encode($result));
            }
            $recCode = trim($this->_request->getPost('recCode'));
            if (!empty($recCode)) {
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                try {
                    $receivingData = Service_Receiving::getByField($recCode, 'receiving_code');
                    if (empty($receivingData)) {
                        throw new Exception("入库单不存在！");
                    } else {
                        if ($receivingData['customer_code'] == 'E8888' || $receivingData['customer_code'] == 'E0555') {
                            throw new Exception("ASN所属客户不允许回退");
                        }
                        if (!in_array($receivingData['receiving_status'], array('2', '3', '4'))) {
                            throw new Exception('入库单状态为[' . $asnStatus[$receivingData['receiving_status']] . '],不能操作！');
                        }
                    }
                    $update = array(
                        'receiving_status' => 1,
                    );
                    /*if($action == 'delete'){
                        $update['receiving_status'] = 0;
                    }*/

                    $res = $this->serviceClass->update($update, $recCode, 'receiving_code');

                    $subReceivingCodes = Service_ReceivingXml::getByCondition(array('receiving_code' => $recCode), 'sub_receiving_code');
                    if (empty($subReceivingCodes)) {
                        Service_FtpMessageSendlist::delete($recCode, 'refercence_no');
                        Service_FtpMessageSendlog::delete($recCode, 'refercence_no');
                    } else {
                        //拆单后的子单删除
                        foreach ($subReceivingCodes as $key => $value) {
                            Service_FtpMessageSendlist::delete($value['sub_receiving_code'], 'refercence_no');
                            Service_FtpMessageSendlog::delete($value['sub_receiving_code'], 'refercence_no');
                            Service_ReceivingXml::delete($value['sub_receiving_code'], 'sub_receiving_code');
                            Service_ReceivingXmlDetail::delete($value['sub_receiving_code'], 'sub_receiving_code');
                        }
                    }
                    $addRow = array(
                        'receiving_id' => $receivingData['receiving_id'],
                        'receiving_code' => $receivingData['receiving_code'],
                        'user_id' => $this->user_id,
                        'customer_code' => $receivingData['customer_code'],
                        'rl_note' => $reason,
                        'rl_status_from' => $receivingData['receiving_status'],
                        'rl_status_to' => "1",
                        'rl_add_time' => date("Y-m-d H:i:s"),
                        'rl_ip' => Common_Common::getIP()
                    );
                    /*if($action == 'delete'){
                        $addRow['rl_status_to'] = 0;
                    }*/
                    Service_ReceivingLog::add($addRow);

                    $keys = array(
                        'warehouseId' => (int)$receivingData['warehouse_id'],
                        'receiving_weight' => $receivingData['roughweight'],
                        'receiving_code' => $receivingData['receiving_code'],
                    );
                    $otherFeeObj = new Common_CalculateOtherFee();
                    $otherFeeObj->setParams($keys);
                    //解冻提货费
                    if ($receivingData['is_delivery'] == 1) {
                        Service_ReceivingProcess::unfreezeFee($receivingData, $otherFeeObj, 'TIHUO');
                    }
                    //解冻入库费
                    Service_ReceivingProcess::unfreezeFee($receivingData, $otherFeeObj, 'RUKU');
                    //解冻散租费
                    Service_ReceivingProcess::unfreezeFee($receivingData, $otherFeeObj, 'SANZU');
                    //解冻操作费-M
                    Service_ReceivingProcess::unfreezeFee($receivingData, $otherFeeObj, 'CZF-M');
                    //$db->rollBack();
                    $db->commit();
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                } catch (Exception $e) {
                    $db->rollBack();
                    $result['message'] = $e->getMessage();
                }
            } else {
                $result["message"] = '请填写入库单号！';
            }
            die(Zend_Json::encode($result));
        }
        echo Ec::renderTpl($this->tplDirectory . "return_index.tpl", 'layout');
    }

    //修改ASN是否提货    
    public function batchModifyDeliveryAction()
    {
        if ($_FILES) {
            $error_msg = "";
            $status = true;
            $xlsData = Service_Orders::getXLSData($_FILES, 'uploadfilename');
            if (count($xlsData[0]) != 2 || $xlsData[0][0] != "ASN单号" || $xlsData[0][1] != "是否提货") {
                $status = false;
                $error_msg = "文件格式错误，首行不是按照ASN单号,是否提货排列!!";
            }
            if (count($xlsData) <= 1) {
                $status = false;
                $error_msg = "Excel表内无数据!";
            }

            if ($status === true) {
                $response = array(
                    'status' => 0,
                );
                foreach ($xlsData as $key => $value) {
                    if ($key === 0) {
                        continue;
                    }
                    $code = trim($value[0]);
                    $ordermark = trim($value[1]);
                    $chepai = trim($value[2]);
                    $guihao = trim($value[3]);
                    $guixing = trim($value[4]);


                    $row = array(
                        "code" => $code,
                        "ordermark" => $ordermark,
                        "chepai" => $chepai,
                        "guihao" => $guihao,
                        "guixing" => $guixing,
                    );


                    $response['status'] = 1;
                    $response['data'][$code] = $this->modifyDelivery($row);
                }

                $this->view->response = $response;
            } else {
                $this->view->errormsg = $error_msg;
            }

        }

        echo Ec::renderTpl($this->tplDirectory . "modify_index.tpl", 'layout');
    }

    public function modifyDelivery($ASNCode, $deliveryStatus)
    {
        $arr = array('是', '否');
        $status = 0;
        $msg = array();
        $msg['status'] = 0;
        $msg['asn_code'] = $ASNCode;
        $msg['info'] = '';

        if (!in_array($deliveryStatus, $arr)) {
            $msg['info'] = '“是否提货”只能填写“是”和“否”';
            return $msg;
        }
        if (empty($ASNCode)) {
            $msg['info'] = 'ASN单号不能为空';
            return $msg;
        }

        $receivingInfo = Service_Receiving::getByField($ASNCode, 'receiving_code', array('receiving_code', 'receiving_id', 'customer_code', 'receiving_status', 'receive_model_type', 'is_delivery'));
        if (empty($receivingInfo)) {
            $msg['info'] = '错误的ASN单号[' . $ASNCode . ']';
            return $msg;
        }
        if ($receivingInfo['receiving_status'] !== '4') {
            $msg['info'] = '此ASN不是审核状态，不能修改';
            return $msg;
        }

        if ($deliveryStatus == '是') {
            $status = 1;
        }
        if ($receivingInfo['is_delivery'] == '1') {
            $statusStr = '是';
        } else {
            $statusStr = '否';
        }
        if ($receivingInfo['is_delivery'] == $status) {
            $msg['info'] = '当前ASN单号的提货状态为[' . $statusStr . '],要修改的提货状态与当前状态相同';
            return $msg;
        }
        $params = array('is_delivery' => $status);
        $result = Service_Receiving::update($params, $ASNCode, 'receiving_code');
        if (!$result) {
            $msg['info'] = 'ASN提货状态修改失败';
            return $msg;
        }
        $msg['status'] = 1;
        $msg['info'] = 'ASN提货状态修改成功，提货状态由[' . $statusStr . ']改为[' . $deliveryStatus . ']';
        $info = ',提货状态由[' . $statusStr . ']改为[' . $deliveryStatus . ']';
        $ASNLog = array(
            'receiving_id' => $receivingInfo['receiving_id'],
            'receiving_code' => $ASNCode,
            'user_id' => $this->user_id,
            'rl_type' => 1,
            'customer_code' => $receivingInfo['customer_code'],
            'rl_note' => "修改ASN是否提货" . $info,
            'rl_status_from' => $receivingInfo['receiving_status'],
            'rl_status_to' => $receivingInfo['receiving_status'],
            'rl_add_time' => date("Y-m-d H:i:s"),
            'rl_ip' => Common_Common::getIP()
        );
        Service_ReceivingLog::add($ASNLog);

        return $msg;
    }

    //修改提货模板下载    
    public function downloadTemplatAction()
    {
        $fullPath = APPLICATION_PATH . "/../data/xls" . '/modify_asn_delivery_status.xls';
        Common_Common::downloadFile($fullPath);
    }

    //入库单数据导出
    public function exportDataAction()
    {
        $ASNCode = $this->_request->getParam('ASNCode', '');
        if (empty($ASNCode)) {
            return false;
        }
        $filename = "receiving_data" . date('YmdHis') . ".xls";

        $oExcel = new PHPExcel();
        $oExcel->setActiveSheetIndex(0);
        $oActiveSheet = $oExcel->getActiveSheet();
        $oExcel->getDefaultStyle()->getFont()->setName('宋体');
        $oExcel->getDefaultStyle()->getFont()->setSize(12);
        $oActiveSheet->setCellValue('A1', '收货单号');
        $oActiveSheet->setCellValue('B1', '订单号');
        $oActiveSheet->setCellValue('C1', '服务商单号');
        $oActiveSheet->setCellValue('D1', '产品名称');
        $oActiveSheet->setCellValue('E1', '件数');
        $oActiveSheet->setCellValue('F1', '重量（毛重）');
        $oActiveSheet->setCellValue('G1', '香港派送地址');


        $orderCodes = Service_ReceivingOrderDetail::getOrderCodes($ASNCode);
        $i = 1;
        if ($orderCodes) {
            foreach ($orderCodes as $value) {
                $i++;
                $weight = 0;
                $num = 0;
                $productTitle = '';
                $orderRet = Service_Orders::getByField($value, 'order_code', array('delivery_address', 'ref_tracking_number'));
                $deliveryAddress = isset($orderRet['delivery_address']) ? $orderRet['delivery_address'] : "";
                // $shipOrder = Service_ShipOrder::getByField($value,"order_code","tracking_number");
                //服务商单号
                $trackingNumber = isset($orderRet['ref_tracking_number']) ? $orderRet['ref_tracking_number'] : "";

                $orderProduct = Service_OrderProduct::getByCondition(array("order_code" => $value));
                if ($orderProduct) {
                    foreach ($orderProduct as $key => $orderP) {
                        $product = Service_Product::getByField($orderP['product_id'], 'product_id');
                        if ($key == 0) {
                            $productTitle = $product['product_title'];
                        }
                        $num += $orderP['op_quantity'];
                        $weight += $orderP['op_quantity'] * $product['product_weight'];
                    }

                }
                $weight += 0.1;
                $oActiveSheet->setCellValueExplicit('A' . $i, $ASNCode, PHPExcel_Cell_DataType::TYPE_STRING);
                $oActiveSheet->setCellValueExplicit('B' . $i, $value, PHPExcel_Cell_DataType::TYPE_STRING);
                $oActiveSheet->setCellValueExplicit('C' . $i, $trackingNumber, PHPExcel_Cell_DataType::TYPE_STRING);
                $oActiveSheet->setCellValueExplicit('D' . $i, $productTitle, PHPExcel_Cell_DataType::TYPE_STRING);
                $oActiveSheet->setCellValueExplicit('E' . $i, $num, PHPExcel_Cell_DataType::TYPE_STRING);
                $oActiveSheet->setCellValueExplicit('F' . $i, sprintf("%.4f", $weight), PHPExcel_Cell_DataType::TYPE_STRING);
                $oActiveSheet->setCellValueExplicit('G' . $i, $deliveryAddress, PHPExcel_Cell_DataType::TYPE_STRING);

            }
        }

        //下载输出
        $oWriter = PHPExcel_IOFactory::createWriter($oExcel, 'Excel5');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");

        header('Content-Disposition:attachment;filename="' . $filename . '"');

        header("Content-Transfer-Encoding:binary");
        $oWriter->save('php://output');

    }

    public function allCompleteAction()
    {
        error_reporting(0);
        $receivingCode = $this->_request->getParam("receiving_code", "");
        $lc_code = $this->_request->getParam("lc_code", "");
        $result = array(
            'ask' => '0',
            'message' => '操作结果如下:',
            'error' => array(),
        );
        /*$customerLccodeArr = array(
            'E1033'=>'CH-A001',
            'E0851'=>'SH-A001',
            'E0909'=>'MC-A001',
            'E0693'=>'HQ-A001',
            'E0750'=>'TT-A001',
            //'E0174'=>'QWE003',
        );*/
        $receivingRow = Service_Receiving::getByField($receivingCode, 'receiving_code', "*");
        if (empty($receivingRow)) {
            $result['message'] = "入库单[" . $receivingCode . "]不存在";
            exit(Zend_Json::encode($result));
        }
        if ($receivingRow['receive_model_type'] != "0") {
            $result['message'] = "入库单[" . $receivingCode . "]不是备货模式";
            exit(Zend_Json::encode($result));
        }
        if ($receivingRow['receiving_status'] == 7) {
            $result['message'] = "入库单[" . $receivingCode . "]状态错误";
            exit(Zend_Json::encode($result));
        }

        $locationRow = Service_Location::getByField($lc_code, 'lc_code', array('lc_code', 'lc_status', 'warehouse_id', 'wa_code'));
        if (empty($locationRow)) {
            $result['message'] = Ec::Lang('ShelfNotExist');
            exit(Zend_Json::encode($result));
        } elseif ($locationRow['lc_status'] == '0') {
            $result['message'] = Ec::Lang('ShelfNotBeUsed');
            exit(Zend_Json::encode($result));
        } else {
            $warehouseAreaRow = Service_WarehouseArea::getByField($locationRow['wa_code'], 'wa_code', array('wa_type'));
            if (empty($warehouseAreaRow) || $warehouseAreaRow == false) {
                $result['message'] = Ec::Lang('WarehouseAreaIsNuLL');
                exit(Zend_Json::encode($result));
            } else if ($warehouseAreaRow['wa_type'] != 1) {
                $result['message'] = sprintf(Ec::Lang('WarehouseAreaTypeError'), $lc_code);
                exit(Zend_Json::encode($result));
            }
        }

        $controArr = array();
        if ($receivingRow['receiving_status'] == 1) {
            $ret0 = Service_AsnProccess::confirmASn($receivingCode);
            if (!empty($ret0) && $ret0['ask'] == '1') {
                $controArr[] = "入区单[" . $receivingCode . "]已提交至确认状态!";
            } else {
                $result['message'] = "入库单[" . $receivingCode . "]提交至确认状态:" . $ret0['message'];
                exit(Zend_Json::encode($result));
            }
        }
        if ($receivingRow['receiving_status'] == 1 || $receivingRow['receiving_status'] == 2) {
            $ret1 = Service_AsnProccess::PendingAsn($receivingCode);
            if (!empty($ret1) && $ret1['ask'] == '1') {
                $controArr[] = "入区单[" . $receivingCode . "]已提交至待审核";
            } else {
                $result['message'] = "入库单[" . $receivingCode . "]提交至待审核失败:" . $ret1['message'];
                exit(Zend_Json::encode($result));
            }
        }
        if ($receivingRow['receiving_status'] == 1 || $receivingRow['receiving_status'] == 2 || $receivingRow['receiving_status'] == 3) {
            /*$updateReceivingRow = array(
                'receiving_status'=>'4',
            );
            Service_Receiving::update($updateReceivingRow, $receivingCode,'receiving_code');*/
            $para['receiving_code'] = $receivingRow['receiving_code'];
            $shenheResult = Service_ReceivingProcess::shenhe($para);
            if ($shenheResult['state'] == 0) {
                $result['message'] = "入库单提交至审核失败:" . $shenheResult['message'];
                exit(Zend_Json::encode($result));
            }
        }

        if ($receivingRow['receiving_status'] == 1 || $receivingRow['receiving_status'] == 2 || $receivingRow['receiving_status'] == 3 || $receivingRow['receiving_status'] == 4) {
            $ret2 = Service_AsnProccess::printAsn($receivingCode, $receivingRow['customer_id']);
            if ($ret2['ask'] == '1') {
                $controArr[] = "入区单[" . $receivingCode . "]已提交至在途状态";
            } else {
                $result['message'] = "入库单[" . $receivingCode . "]提交至在途失败:" . $ret2['message'];
                exit(Zend_Json::encode($result));
            }
        }
        if (in_array($receivingRow['receiving_status'], array(1, 2, 3, 4, 5))) {
            $receivingDetail = Service_ReceivingDetail::getByCondition(array('receiving_code' => $receivingCode), "*");
            $rdArr = array();
            $weight = 0;
            $productList = array();
            foreach ($receivingDetail as $rd) {
                $rdArr[] = $rd['rd_id'];
                $p = Service_Product::getByField($rd['product_id'], "product_id", "*");
                $productList[$rd['product_id']] = $p;
                $weight += $rd['rd_receiving_qty'] * $p['product_weight'];
            }
            $obj = new Service_ReceivingProcess();
            $return = $obj->submitReceived($rdArr, $weight);
            if ($return['state'] != 1) {
                $result['ask'] = 0;
                $message = "";
                foreach ($return['error'] as $k => $v) {
                    $message .= $v['errorMsg'] . ";";
                }
                $result['message'] = "入库单[" . $receivingCode . "]收货失败:" . $message;
                //$result['error'] = $return['error'];
                exit(Zend_Json::encode($result));
            }
            $controArr[] = "入库单[" . $receivingCode . "]收货成功!\n";
            $qcList = Service_QualityControl::getByCondition(array('receiving_code' => $receivingCode), "*");
            foreach ($qcList as $qc) {
                $params = array(
                    'userId' => Service_User::getUserId(),
                    'qcId' => $qc['qc_id'],
                    'productId' => $qc['product_id'],
                    'productBarcode' => $qc['product_barcode'],
                    'customerCode' => $qc['customer_code'],
                    'productCategoryId' => 0,
                    'firstReceived' => 0,
                    'productBarcodeType' => $productList[$qc['product_id']]['product_barcode_type'],
                    'productWeight' => $productList[$qc['product_id']]['product_weight'],
                    'receivedQty' => $qc['qc_quantity'],
                    'problemQty' => 0,
                    'noLabelQty' => 0,
                    'shelf' => '',
                    'product' => array(
                        'category' => '1',
                        'package' => '1',
                        'declaredValue' => $productList[$qc['product_id']]['product_declared_value'],
                        'length' => $productList[$qc['product_id']]['product_length'] <= 0 ? 1 : $productList[$qc['product_id']]['product_length'],
                        'width' => $productList[$qc['product_id']]['product_width'] <= 0 ? 1 : $productList[$qc['product_id']]['product_width'],
                        'height' => $productList[$qc['product_id']]['product_height'] <= 0 ? 1 : $productList[$qc['product_id']]['product_height'],
                    ),
                    'remark' => '',
                );
                if ($qc['qc_status'] == "0") {
                    $qcObj = new Service_QualityControlProcess();
                    $return2 = $qcObj->submit($params);
                    if ($return2['state'] != "1") {
                        $result['ask'] = 0;
                        $message = "";
                        foreach ($return2['error'] as $k => $v) {
                            $message .= $v['errorMsg'] . ";";
                        }
                        $controArr[] = "质检单号[" . $qc['qc_code'] . "]质检失败:" . $message . "\n";
                        $result['error'] = $controArr;
                        exit(Zend_Json::encode($result));
                    } else {
                        $controArr[] = "质检单号[" . $qc['qc_code'] . "]质检成功!\n";
                    }
                }
            }
        }
        $result['error'] = $controArr;
        if (empty($qcList)) $qcList = Service_QualityControl::getByCondition(array('receiving_code' => $receivingCode), "*");
        $putaway = array();
        foreach ($qcList as $qc) {
            if ($qc['qc_status'] == 2) continue;
            if ($qc['qc_status'] == "0" && $receivingRow['receiving_status'] == 6) {
                $controArr[] = "不能一键操作上架：入库单[" . $receivingCode . "]是收货中状态,有质检未完成质检！\n";
                $result['error'] = $controArr;
                $result['error'] = $controArr;
                exit(Zend_Json::encode($result));
            }
            $pd = Service_PutawayDetail::getByField($qc['qc_code'], "qc_code", "*");
            $pdd = array(
                'pd_id' => $pd['pd_id'],
                'lc_code' => $lc_code,
                'product_barcode' => $pd['product_barcode'],
                'qc_code' => $qc['qc_code'],
            );
            $putaway[] = $pdd;
        }
        //var_dump($putaway);
        //exit;
        if (!empty($putaway)) {
            foreach ($putaway as $pta) {
                $param = array();
                $param[] = $pta;
                $sum = 0;
                $putawayObj = new Service_PutawayProcess();
                $ret = $putawayObj->submit($param);
                if ($ret['state'] == 1) {
                    foreach ($param as $key => $value) {
                        $putd = Service_PutawayDetail::getByField($value['pd_id'], 'pd_id');
                        $pd = Service_PutawayDetail::getByCondition(array('qc_code' => $putd['qc_code'], 'pd_type' => 2), '*');
                        $qc_code = $putd['qc_code'];
                        //print_r($pd);exit;
                        Service_Box::update(array('box_status' => 0, 'product_barcode' => '', 'product_id' => '', 'box_quantity' => '', 'receiving_code' => ''), $putd['box_code'], 'box_code');
                        Service_PutawayDetail::update(array('box_code' => ''), $putd['pd_id'], 'pd_id');
                        foreach ($pd as $k => $v) {
                            if ($v['pd_status'] == '0') {
                                $sum = 1;
                            }
                        }
                    }
                    // print_r($sum);exit;
                    if ($sum == 0) {
                        Service_QualityControl::update(array('qc_status' => 2), $pta['qc_code'], 'qc_code');
                    }
                    $controArr[] = "质检单号[" . $pta['qc_code'] . "]上架成功!\n";
                } else {
                    $result['ask'] = 0;
                    $message = "";
                    foreach ($ret['error'] as $k => $v) {
                        $message .= $v['errorMsg'] . ";";
                    }
                    $controArr[] = "质检单号[" . $pta['qc_code'] . "]上架失败:" . $message . "\n";
                    $result['error'] = $controArr;
                    exit(Zend_Json::encode($result));
                }
            }
        }
        $result['ask'] = 1;
        $result['message'] = "操作成功!\n";
        $result['error'] = $controArr;
        exit(Zend_Json::encode($result));
    }

    public function autoToFinishAction()
    {
        echo Ec::renderTpl($this->tplDirectory . "auto-to-finish.tpl", 'layout');
    }

    public function importHsSerialAction()
    {
        $result = array("ask" => 1, "message" => "", 'error' => array(), 'data' => array());
        $xlsData = Service_Product::getXLSData($_FILES, 'filename');
        //var_dump($xlsData);
        //exit;
        if (count($xlsData[0]) != 3 || ($xlsData[0][0] != "入库单号" || $xlsData[0][1] != "料件号" || $xlsData[0][2] != "海关备案序号")) {
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照入库单号,料件号,海关备案序号排列!";
            die(json_encode($result));
        }
        foreach ($xlsData as $key => $value) {
            if ($key == 0) continue;
            $existError = 0;
            $goodsId = $value[1];
            $hsSerialNo = $value[2];
            $receivingCode = $value[0];
            $resultData = array(
                'receiving_code' => $receivingCode,
                'goods_id' => $goodsId,
                'hs_serial_no' => $hsSerialNo,
                'ok' => 1
            );
            if ($receivingCode == "") {
                $existError = 1;
                $resultData['message'] .= "入库单号为空;";
            }
            if ($goodsId == "") {
                $existError = 1;
                $resultData['message'] .= "料件号为空;";
            }
            if ($hsSerialNo == "") {
                $existError = 1;
                $resultData['message'] .= "海关备案序号为空;";
            }
            $receivingRow = Service_Receiving::getByField($receivingCode, 'receiving_code', "*");
            if (empty($receivingRow)) {
                $existError = 1;
                $resultData['message'] .= "入库单号[" . $receivingCode . "]为空;";
            } else {
                if ($receivingRow['import_hsserialno']) {
                    $existError = 1;
                    $resultData['message'] .= "入库单号[" . $receivingCode . "]已经导入海关备案序号";
                }
            }
            if ($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $receivingDetail = Service_ReceivingDetail::getLeftJoinProductByCondition(array('receiving_code' => $receivingCode, 'goods_id' => $goodsId), "*");
                if (!empty($receivingDetail)) {
                    foreach ($receivingDetail as $rd) {
                        $updateRd = array(
                            'hs_serial_no' => $hsSerialNo
                        );
                        Service_ReceivingDetail::update($updateRd, $rd['rd_id'], "rd_id");
                    }
                } else {
                    throw new Exception("入库单号[" . $receivingCode . "]不存在料件号[" . $goodsId . "]的产品");
                }

                $NoAllImport = Service_ReceivingDetail::getLeftJoinProductByCondition(array('receiving_code' => $receivingCode, 'empty_hs_serial_no' => 1), "count(*)");
                if (!$NoAllImport) Service_Receiving::update(array('import_hsserialno' => 1), $receivingCode, 'receiving_code');
                $db->commit();
                $resultData['ok'] = 1;
                $resultData['message'] = "海关备案序号更新成功!";
            } catch (Exception $e) {
                $db->rollBack();
                $resultData['ok'] = '0';
                $resultData['message'] = "海关备案序号更新失败:" . $e->getMessage();
            }
            $result['data'][] = $resultData;
        }
        die(json_encode($result));
    }

    public function uploadTemplateAction()
    {
        $fullPath = APPLICATION_PATH . "/../data/file/importHsSerialNo.xls";
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header = "Content-Disposition: attachment; filename=" . $filename . ";";
        header($header);
        //  header("Content-Transfer-Encoding: binary");
        //  header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }
    /**
     * @todo 下载报关单
     */
    public function downBaoguanAction(){
        $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'];
                    Common_Common::downloadFile($fullPath);
                }else{
                    echo "报关单数据未上传或者不存在";
                    exit;
                }
            }else{
                echo "报关单数据未上传或者不存在";
                exit;
            }
        }else{
            die("参数错误!");
        }
    }
}