<?php

class Shipment_ShipBatchController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "shipment/views/order/";
        $this->serviceClass = new Service_ShipBatch();
        $this->sendMessage = true;
    }

    public function listAction()
    {

        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);
            $condition['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
            $condition['dateTo'] = isset($params['dateTo']) ? $params['dateTo'] : '';
            $condition['ship_time_start'] = isset($params['sb_ship_time_start']) ? $params['sb_ship_time_start'] : "";
            $condition['ship_time_end'] = isset($params['sb_ship_time_end']) ? $params['sb_ship_time_end'] : "";
            $condition['project_type'] = empty($params['E23']) ? '' : $params['E23'];
            $condition['sb_status_arr'] = isset($params['sb_status_arr']) ? trim($params['sb_status_arr']) : '';
            $condition['out_area'] = isset($params['out_area']) ? $params['out_area'] : '';
            $condition['ob_no'] = isset($params['ob_no']) ? trim($params['ob_no']) : '';
            /*if(!empty($condition['dateFor'])){
                $condition['dateFor']=date('Y-m-d H:i:s',strtotime($condition['dateFor'].' 00:00:00'));
            }
            if(!empty($condition['dateTo'])){
                $condition['dateTo']=date('Y-m-d H:i:s',strtotime($condition['dateTo'].' 23:59:59'));
            }*/
            //echo "<pre>";
            //var_dump($condition);
            //echo "</pre>";
            //die("XXX");
            //getJoinOrderByCondition

            //$count = $this->serviceClass->getLeftJoinUserByCondition($condition, 'count(*)');
            $count = $this->serviceClass->getJoinOrderByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $projectType = Service_ShipBatch::$projectType;
                $showFields = array(
                    'sb_code',
                    'sm_code',
                    'warehouse_id',
                    'creater_id',
                    'sb_status',
                    'reference_no',
                    'sb_truck_no',
                    'sb_ship_time',
                    'sb_add_time',
                    'sb_update_time',
                    'sb_id',
                    'project_type'
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);

                //$rows = $this->serviceClass->getLeftJoinUserByCondition($condition,$showFields, $pageSize, $page, array('sb_id desc'));
                $rows = $this->serviceClass->getJoinOrderByCondition($condition, $showFields, $pageSize, $page, array('sb_id desc'));
                foreach ($rows as $key => $value) {
                    $rows[$key]['project_name'] = $projectType[$value['E11']];
                    $sbAttr = Service_ShipBatchAttribute::getLeftJoinSHCondition(array('sb_code' => @$value['E1'], 'sb_status' => '0'), '*');
                    if (!empty($sbAttr)) {
                        $formtype = Service_FormType::getByField($sbAttr[0]['form_type'], 'form_type');
                        $rows[$key]['form_type'] = $formtype['form_type_name'];

                        $sb = Service_ShipBatchAttribute::getByCondition(array('sb_code' => $value['E1']));
                        $rows[$key]['trade_mode'] = $sb[0]['trade_mode'];
                        $trade = [];
                        if ($sb[0]['trade_mode']) {
                            $trade = Service_TradeMode::getByField($sb[0]['trade_mode'], 'trade_mode');
                        }
                        if (!empty($trade)) {
                            $rows[$key]['trade_mode_name'] = $trade['trade_mode_name'];
                        } else {
                            $rows[$key]['trade_mode_name'] = '';
                        }
                        if ($sb[0]['ie_port']) {
                            $ie = Service_IePort::getByField($sb[0]['ie_port'], 'ie_port');
                            $rows[$key]['ie_port'] = $ie['ie_port_name'];
                            $rows[$key]['pack_no'] = $sb[0]['pack_no'];
                        }
                    }
                    $rows[$key]['ob_weight'] = 0;
                    $condition = array('sb_code' => $value['E1']);
                    $shipBatchDetail = Service_ShipBatchDetail::getByCondition($condition);
                    if ($shipBatchDetail) {
                        foreach ($shipBatchDetail as $val) {
                            $rows[$key]['ob_weight'] += $val['ob_weight'];
                        }
                    }

                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['status'] = Common_Status::shipBatchStatus('auto');
                $return['warehouse'] = Common_DataCache::getWarehouseSimple();
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->SM = Common_DataCache::getShippingMethodSimple();

        $condition = array(
            "report_page" => 'shipbatch',
        );
        $select = array("report_id", "report_name");
        $row = Service_Report::getByCondition($condition, $select);
        $this->view->report = $row;
        echo Ec::renderTpl($this->tplDirectory . "ship_batch_index.tpl", 'layout');
    }

    /**
     * 创建出货总单
     */
    public function addAction()
    {
        if ($this->_request->isPost()) {
            $return = array("state" => 0, "message" => '');
            $sm_code = $this->_request->getParam('sm_code');
            $sb_truck_no = $this->_request->getParam('sb_truck_no');
            //if(empty($sm_code)) $return['message'] = '请选择运输方式';
            if (empty($sb_truck_no)) $return['message'] = '请输入出货车号';
            else {
                $warehouseId = Service_User::getUserWarehouseId();
                $aWarehouse = Service_Warehouse::getByField($warehouseId, 'warehouse_id', 'warehouse_code');
                $sb_code = Common_GetNumbers::getCode('shipbatch', $warehouseId, $aWarehouse['warehouse_code']);
                $result = Service_ShipBatch::create($sb_code, $sm_code, $sb_truck_no);
                if ($result) $return['state'] = 1;
                else $return['message'] = '创建失败，请重试';
            }
            echo Zend_Json::encode($return);
        } else {
            $this->view->shippingMethod = Common_DataCache::getShippingMethodSimple();
            echo Ec::renderTpl($this->tplDirectory . "ship_batch_add.tpl", 'layout');
        }
    }

    /**
     * 创建海关出货总单
     */
    public function addQianhaiAction()
    {
        if ($this->_request->isPost()) {
            $return = array("state" => 0, "message" => '');
            $sbaService = new Service_ShipBatchAttribute();
            $params = $this->_request->getParams();
            $row = array(
                'sb_code' => '',
                'ie_port' => '',
                'form_type' => '',
                'traf_name' => '',
                'voyage_no' => '',
                'trans_mode' => '',
                'traf_mode' => '',
                //'wrap_type'=>'',
                'country_id' => '',
                'consignee' => '',
            );
            if (isset($params['is_conta']) && $params['is_conta'] == 1) {
                $row['conta_id'] = '';
                $row['conta_model'] = '';
                $row['conta_wt'] = '';
            }
            $tradeMode = $this->_request->getParam("E22", "");
            $projectType = empty($params['E23']) ? '' : trim($params['E23']);
            $row = $sbaService->getMatchEditFields($params, $row);
            $errorArr = $sbaService->validator($row);
            $validateArr[] = array("name" => '项目', "value" => $projectType, "regex" => array("require", 'positive'));
            $shipBatchError = Common_Validator::formValidator($validateArr);
            if (!empty($shipBatchError)) {
                $errorArr = array_merge($errorArr, $shipBatchError);
            }
            if (!empty($errorArr)) {
                $return['message'] = $errorArr;
                exit(Zend_Json::encode($return));
            }

            $warehouseId = Service_User::getUserWarehouseId();
            $aWarehouse = Service_Warehouse::getByField($warehouseId, 'warehouse_id', 'warehouse_code');
            $sb_code = Common_GetNumbers::getOnlyCode('shipbatchonly', 'BHC');

            if (!Service_ShipBatch::create($sb_code, "", $row['voyage_no'], array('project_type' => $projectType))) {
                $return['message'] = '创建出货总单失败，请重试';
                exit(Zend_Json::encode($return));
            }
            $row['sb_code'] = $sb_code;
            $row['trade_mode'] = $tradeMode == "" ? '1210' : $tradeMode;//1210保税区仓储转口
            if (!Service_ShipBatchAttribute::add($row)) {
                $return['message'] = '创建总单属性失败，请重试';
                exit(Zend_Json::encode($return));
            }
            $return['state'] = 1;
            exit(Zend_Json::encode($return));
        } else {
            $this->view->aIePort = Service_IePort::getAll();
            //$this->view->aFormType = Service_FormType::getAll();
            $aFormType = Service_FormType::getByCondition(['is_display'=>'1','ie_flag'=>'E']);
            $this->view->aFormType = $aFormType;
            /*$this->view->aFormType = array(
                '0'=> array('form_type' => 'E1234', 'form_type_name' => '分销一体化出境出区'),
                '1' => array('form_type' => 'E1', 'form_type_name' => '一线出区'),
                '2' => array('form_type' => 'ECD', 'form_type_name' => '一体化通关'),
                '3' => array('form_type' => 'E2F', 'form_type_name' => '分批出区返回国内'),
                '4' => array('form_type' => 'E2D', 'form_type_name' => '跨通-电商出境出区'),
                '5' => array('form_type' => 'E3D', 'form_type_name' => '跨通-分销出境出区'),
                '6' => array('form_type' => 'E2345', 'form_type_name' => '海运一体化出园'),
                '7' => array('form_type' => 'TCT-E', 'form_type_name' => '区内流转-出区'),
                '8' => array('form_type' => 'TFT-E', 'form_type_name' => '区间流转-出区'),
            );*/
            $this->view->aTransMode = Service_TransMode::getAll();
            $this->view->aTrafMode = Service_TrafMode::getAll();
            //$this->view->aWrapType = Service_WrapType::getAll();
            $this->view->aCountry = Service_Country::getAll();

            echo Ec::renderTpl($this->tplDirectory . "ship_batch_add_qh.tpl", 'layout');
        }
    }

    public function cancelMountAction()
    {
        if ($this->_request->isPost()) {
            $ob_no = trim($this->_request->getParam('ob_no'));
            if (empty($ob_no)) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '请输入包袋号')));
            }
            $aOutboundBag = Service_OutboundBag::getByField($ob_no, 'ob_no');
            if (empty($aOutboundBag)) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '包袋号不存在')));
            }
            $soProcess = new Service_ShipOrderProcess();
            $result = $soProcess->cancelMount($ob_no);
            if ($result !== true) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => $result)));
            }
            exit(Zend_Json::encode(array('state' => 1, 'message' => '')));

        }
    }

    /**
     * 加挂
     */
    public function mountAction()
    {
        if ($this->_request->isPost()) {
            //exit(Zend_Json::encode(array("state"=>1, "message"=>'')));
            $sb_code = trim($this->_request->getParam('sb_code'));
            $ob_no = trim($this->_request->getParam('ob_no'));
            if (empty($sb_code)) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '请提供出货总单号')));
            }
            if (empty($ob_no)) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '请输入包袋号')));
            }
            $aShipBatch = Service_ShipBatch::getByField($sb_code, 'sb_code');
            if (empty($aShipBatch)) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '出货总单号不存在')));
            }
            if (intval($aShipBatch['sb_status']) !== 0) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '出货总单不是草稿状态')));
            }
            $aOutboundBag = Service_OutboundBag::getByField($ob_no, 'ob_no');
            $sbAttribute = Service_ShipBatchAttribute::getByField($sb_code, "sb_code", "*");
            if (empty($aOutboundBag)) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '包袋号不存在')));
            }
            if (intval($aOutboundBag['ob_status']) !== 1) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '包袋不在已完成状态')));
            }
            if ($aShipBatch['sm_code'] && $aOutboundBag['sm_code'] != $aShipBatch['sm_code']) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => '包袋和出货总单的运输方式不一致')));
            }
            /*if($aOutboundBag['ob_trade_mode']==""){
                if($sbAttribute['trade_mode']!="1210"){
                    exit(Zend_Json::encode(array('state'=>0,'message'=>"包袋监管方式和出货总单的监管方式[{$sbAttribute['trade_mode']}]不一致")));
                }
            }else{
                if($sbAttribute['trade_mode']!=$aOutboundBag['ob_trade_mode']){
                    exit(Zend_Json::encode(array('state'=>0,'message'=>"包袋监管方式[{$aOutboundBag['ob_trade_mode']}]和出货总单的监管方式[{$sbAttribute['trade_mode']}]不一致")));
                }
            }*/
            $outboundBagDetail = Service_OutboundBagDetail::getByCondition(array('ob_no' => $ob_no), "*");
            if (!empty($outboundBagDetail)) {
                foreach ($outboundBagDetail as $key => $value) {
                    $rod = Service_ReceivingOrderDetail::getByField($value['order_code'], 'order_code');
                    if (!empty($rod)) {
                        $receiving = Service_Receiving::getByField($rod['receiving_code'], 'receiving_code');
                        if ($receiving['receiving_status'] != 7) {
                            exit(Zend_Json::encode(array('state' => 0, 'message' => '入库单' . $receiving['receiving_code'] . '状态不是收货完成状态不允许加挂')));
                        }
                    }
                }
            }
            $ShipBatchattr = Service_ShipBatchAttribute::getByField($sb_code, 'sb_code');
            if ($ShipBatchattr['form_type'] == 'E2F') {
                if ($aOutboundBag['sm_code'] !== 'ZCCQ') {
                    exit(Zend_Json::encode(array('state' => 0, 'message' => '出区暂存只能加挂运输代码为ZCCQ的袋子')));
                } else {

                    $shipbatch = Service_ShipBatchDetail::getByCondition(array('sb_code' => $sb_code), '*');
                    $batchdetail = Service_OutboundBagDetail::getByCondition(array('ob_no' => $ob_no), "*");
                    //判断是否已经加挂袋子
                    if (!empty($shipbatch)) {
                        $aoutboundBag = Service_OutboundBagDetail::getByField($shipbatch[0]['ob_no'], 'ob_no');
                        $customer = Service_Orders::getByField($aoutboundBag['order_code'], 'order_code');
                        if (!empty($batchdetail)) {
                            $order = array();
                            //判断已经加挂的袋子和要加挂的袋子是否是同一个客户的
                            foreach ($batchdetail as $key => $value) {
                                $order[$key] = Service_Orders::getByField($value['order_code'], 'order_code');
                                if ($order[$key]['customer_code'] !== $customer['customer_code']) {
                                    exit(Zend_Json::encode(array('state' => 0, 'message' => '袋子下的订单与已经加挂的袋子下的订单不是同一客户的')));
                                }


                            }
                        }
                    } else {
                        //第一次加挂袋子
                        if (!empty($batchdetail)) {
                            $order = array();
                            foreach ($batchdetail as $key => $value) {
                                $order[$key] = Service_Orders::getByField($value['order_code'], 'order_code');
                                if (count($order) > 1) {
                                    if ($order[$key - 1]['customer_code'] !== $order[$key]['customer_code']) {
                                        exit(Zend_Json::encode(array('state' => 0, 'message' => '袋子下的订单不是同一客户的')));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (false === Service_ShipOrderProcess::allowPutIntoBag($ob_no, $sb_code, 'gsPlateFormAtMount')) {
                die(json_encode(array('state' => 0, 'message' => "环球订单的袋子不能跟其他平台的订单袋子加挂到同一张出区单")));
            }
            $soProcess = new Service_ShipOrderProcess();
            $result = $soProcess->mount($ob_no, $sb_code, $aOutboundBag['ob_weight']);
            if ($result !== true) {
                exit(Zend_Json::encode(array('state' => 0, 'message' => $result)));
            }
            exit(Zend_Json::encode(array('state' => 1, 'message' => '')));
        } else {
            $sb_code = trim($this->_request->getParam('sb_code'));
            if (empty($sb_code)) exit('error param');
            $aShipBatch = Service_ShipBatch::getByField($sb_code, 'sb_code');
            if (empty($aShipBatch)) exit('order not exist');
            $this->view->sb_code = $sb_code;
            $this->view->sb_truck_no = $aShipBatch['sb_truck_no'];
            echo Ec::renderTpl($this->tplDirectory . "ship_batch_mount.tpl", 'layout');
        }
    }

    /**
     * 出货总单加挂完成
     */
    public function finishAction()
    {
        $return = array("state" => 0, "message" => '');
        $sb_code = trim($this->_request->getParam('sb_code'));
        $pack_no = trim($this->_request->getParam('pack_no', ''));
        if (empty($sb_code)) {
            $return['message'] = '请提供出货总单号';
        } else {
            $soProcess = new Service_ShipOrderProcess();
            $result = $soProcess->finishMount($sb_code, $pack_no);
            if ($result === true) {    //FTP相关操作
                /*if($this->sendMessage){
                    //$fmProcess = new Service_FtpMessageProcess();
                    //$fml_id = $fmProcess->addSendMessage($sb_code);
                  //  $fmProcess->ftpSendMessage($fml_id);  
                    $sbaRow=Service_ShipBatchAttribute::getByField($sb_code,'sb_code');
                    if($sbaRow['trade_mode']!="0110"){
                        if ($sbaRow['form_type']=='E2F') {
                            $aMessage['fmt_code'] = 'ZCCQ';
                        }else{
                            $aMessage['fmt_code'] = 'MCK';
                        }
                        $aMessage['fmt_type'] = 'BSG011';
                        $aMessage['refercence_no'] = $sb_code;
                        $aMessage['fml_status'] = 1;
                        $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
                        Service_FtpMessageSendlist::add($aMessage);
                    }
                }*/
                $return['state'] = 1;
            } else $return['message'] = $result;
        }
        exit(Zend_Json::encode($return));
    }

    /**
     * 打印出货总单
     */
    public function printAction()
    {
        $sb_code = trim($this->_request->getParam('sb_code'));
        $type = trim($this->_request->getParam('type', ""));
        if (empty($sb_code)) exit('Please input ship batch order code.');
        $sbaRow = Service_ShipBatchAttribute::getByField($sb_code, 'sb_code');
        if (empty($sbaRow)) exit('The ship batch order code is not exist.');
        if ($type == "") {
            $userAuth = new Zend_Session_Namespace('userAuthorization');
            $user_id = $userAuth->userId;
            $shipBatchRow = Service_ShipBatch::getByField($sb_code, 'sb_code', "*");

            $updateShipBatch = array(
                'sb_status' => '3',
                'sb_update_time' => date("Y-m-d H:i:s")
            );
            Service_ShipBatch::update($updateShipBatch, $sb_code, "sb_code");
            $sbLog = array(
                'sb_id' => $shipBatchRow['sb_id'],
                'sb_code' => $shipBatchRow['sb_code'],
                'sbl_type' => 1,
                'user_id' => $user_id,
                'sbl_status_from' => $shipBatchRow['sb_status'],
                'sbl_status_to' => '3',
                'sbl_note' => '已出货',
                'sbl_add_time' => date("Y-m-d H:i:s"),
                'sbl_ip' => Common_Common::getIP()
            );
            Service_ShipBatchLog::add($sbLog);
            $sbd = Service_ShipBatchDetail::getByCondition(array('sb_code' => $sb_code), "*");

            foreach ($sbd as $key => $value) {
                $obd = Service_OutboundBagDetail::getByCondition(array('ob_no' => $value['ob_no']), "*");
                foreach ($obd as $k => $v) {
                    $orderRow = Service_Orders::getByField($v['order_code'], "order_code", "*");
                    //订单 到 物流完成
                    $updateOrder = array(
                        'order_status' => 11,
                        'update_time' => date("Y-m-d H:i:s"),
                    );
                    Service_Orders::update($updateOrder, $orderRow['order_code'], "order_code");
                    $orderLog = array(
                        'order_id' => $orderRow['order_id'],
                        'order_code' => $orderRow['order_code'],
                        'ol_type' => '0',
                        'order_status_from' => $orderRow['order_status'],
                        'order_status_to' => '12',
                        'ol_add_time' => date('Y-m-d H:i:s', time()),
                        'user_id' => $user_id,
                        'ol_ip' => Common_Common::getIP()
                    );
                    Service_OrderLog::add($orderLog);
                }
            }
        }
        $this->view->sbaRow = $sbaRow;
        $this->view->fmtRow = Service_FtpMessageType::getByField('MCK', 'fmt_code');
        $aOrderCode = Service_ShipBatch::getOrderCodes($sb_code);
        $productList = Service_OrderProduct::getOutBillProducts($aOrderCode);
        $totalPrice = $productList['total'];
        unset($productList['total']);
        $firstRow = current($productList);
        $this->view->customerRow = Service_Customer::getByField($firstRow['customer_id']);
        $productResult = array();
        foreach ($productList as &$productRow) {
            $productRow['quantity_law'] = round($productRow['hum_quantity_law'] * $productRow['quantity'], 3);
            if ($productRow['hum_quantity_second'] === '0') $productRow['hum_quantity_second'] = '';
            else $productRow['hum_quantity_second'] = round($productRow['hum_quantity_second'], 3);
            $product_total_price = sprintf("%.2f", $productRow['total_price']);
            $productRow['product_unit_price'] = sprintf("%.4f", $product_total_price / $productRow['quantity_law']);
            $productRow['product_total_price'] = $product_total_price;
            //$totalPrice += $product_total_price;
            //申报要素
            $hemList = Service_HsElementMap::getByCondition(array('product_id' => $productRow['product_id']), 'hem_detail');
            $elements = array();
            foreach ($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
            $productRow['product_model'] = implode('|', $elements);
            $productResult[] = $productRow;
        }
        /*foreach($productList as $key=>$productRow) {
            $productList[$key]['product_unit_price'] = sprintf("%.4f", $productRow['product_declared_value']/$productRow['hum_quantity_law']);
            $productList[$key]['product_total_price'] = sprintf("%.2f", $productRow['product_declared_value'] * $productRow['quantity']);
            $totalPrice += $productList[$key]['product_total_price'];
            $productList[$key]['quantity_law'] = round($productRow['hum_quantity_law'] * $productRow['quantity'], 3);
            if($productRow['hum_quantity_second']==='0') $productList[$key]['hum_quantity_second'] = '';
            else $productList[$key]['hum_quantity_second'] = round($productList[$key]['hum_quantity_second'], 3);
            //申报要素
            $hemList = Service_HsElementMap::getByCondition(array('product_id'=>$productRow['product_id']), 'hem_detail');
            $elements = array();
            foreach($hemList as $hemRow) $elements[] = $hemRow['hem_detail'];
            $productList[$key]['product_model'] = implode('|',$elements);
        }*/

        $this->view->productList = $productResult;
        $this->view->totalPrice = $totalPrice;
        //$this->view->aStat = Service_ShipBatchDetail::stat($sb_code);
        //$this->view->kvHsUom = Service_HsUom::getKeyArr();
        $this->view->kvProductUom = Service_ProductUom::getKeyVal();
        $this->view->kvIePort = Service_IePort::getKeyVal();
        $this->view->kvTradeMode = Service_TradeMode::getKeyVal();
        $this->view->kvTransMode = Service_TransMode::getKeyVal();
        $this->view->kvTrafMode = Service_TrafMode::getKeyVal();
        $this->view->kvCountry = Service_Country::getCodeVal();
        $this->view->kvFormType = Service_FormType::getKeyVal();
        $this->view->kvWrapType = Service_WrapType::getKeyVal();
        $this->view->kvCurrency = Service_Currency::getKeyVal();
        $this->view->gross_weight = Service_ShipBatchDetail::sumGrossWeight($sb_code);
        $this->view->net_weight = number_format(Service_ShipBatchDetail::sumNetWeight($sb_code), 2, '.', '');
        echo Ec::renderTpl($this->tplDirectory . 'ship_batch_print.tpl', 'layout');
    }

    /**
     * @desc 导出出货总单
     */
    public function exportAction()
    {
        if ($this->_request->isPost()) {
            $sbCodes = $this->_request->getParam('sbCodes', array());
            if (!empty($sbCodes) && is_array($sbCodes)) {
            } else {
                die('请选择出货总单号');
            }
            $filename = "shipBatch" . date("YmdHis");
            require_once("PHPExcel.php");
            require_once("PHPExcel/Reader/Excel2007.php");
            require_once("PHPExcel/Reader/Excel5.php");
            require_once('PHPExcel/IOFactory.php');

            $objExcel = new PHPExcel();
            $objProps = $objExcel->getProperties();
            $objProps->setCreator('EC');
            $objProps->setTitle('Template');
            $objExcel->setActiveSheetIndex(0);

            $objActSheet = $objExcel->getActiveSheet();

            $width = array(25, 20, 20, 20, 25, 10, 10, 10, 25, 20, 20, 20, 20);
            $title = array('出货总单号', '包袋号', '订单号', '运单号', '品名（中文）', '申报价值(USD)', '目的海关申报价（USD）', '件数', '重量', '渠道', '出货时间', '目的地国家', '客户名称', '派送地址');
            $length = count($title);
            for ($i = 0; $i < $length; ++$i) {
                $column = Common_Common::getColumnName($i);
                $objActSheet->getColumnDimension($column)->setWidth($width[$i]);
                $objActSheet->setCellValue($column . '1', $title[$i]);
            }

            $dataList = array();
            foreach ($sbCodes as $code) {
                $sbRow = Service_ShipBatch::getByField($code, "sb_code", "*");
                $orderCodes = Service_ShipBatch::getOrderCodes($code);
                foreach ($orderCodes as $orderCode) {
                    $ordersInfo = Service_Orders::getByField($orderCode, 'order_code', "*");
                    $customerInfo = Service_Customer::getByField($ordersInfo['customer_code'], 'customer_code', "*");
                    $orderProduct = Service_OrderProduct::getByCondition(array('order_code' => $orderCode), "*");
                    $shipOrder = Service_ShipOrder::getByField($orderCode, 'order_code', "*");
                    $p = Service_Product::getByField($orderProduct[0]['product_id'], "product_id", "*");
                    $topdv = 0;
                    $totalQuantity = Service_ShipOrderDetail::getByCondition(array('order_code' => $orderCode));
                    $totalDeclaredValue = 0;
                    $shippingMethod = Service_ShippingMethod::getByField($shipOrder['sm_code'], 'sm_code');
                    foreach ($orderProduct as $ok => $op) {
                        $topdv = $topdv + $op['op_purpose_declared_value'] * $op['op_quantity'];
                        $totalDeclaredValue += $op['op_declared_value'] * $op['op_quantity'];
                    }
                    //件数
                    $Total = $shipOrder['so_piece'];
                    /*if($shippingMethod['sm_is_volume']!="1") {
                        $Total = 1;
                    }else{
                        if($shippingMethod['sm_code']=="HKDHL"){
                            $Total = count($totalQuantity);
                        }else{
                            foreach($totalQuantity as $sodRow){
                                if($sodRow['sub_tracking_number']!="") $Total++;
                            }
                        }
                    }*/
                    if ($Total < 1) $Total = 1;

                    $opt = Service_OrderOperationTime::getByField($orderCode, "order_code", "*");
                    $orderAddress = Service_OrderAddressBook::getByField($orderCode, 'order_code', "*");
                    $country = Service_Country::getByField($orderAddress['oab_country_id'], 'country_id', "*");
                    $bag = Service_OutboundBagDetail::getByField($orderCode, 'order_code');
                    $dataList[] = array(
                        $code,
                        $bag['ob_no'],
                        $orderCode,
                        $shipOrder['tracking_number'],
                        $p['product_title'],
                        $topdv,
                        $totalDeclaredValue,
                        $Total,
                        $shipOrder['so_weight'],
                        $shipOrder['sm_code'],
                        $sbRow['sb_ship_time'],
                        $country['country_name'],
                        $customerInfo['customer_company_name'],
                        $ordersInfo['delivery_address']
                    );
                }
            }
            $index = 2;
            foreach ($dataList as $key => $value) {
                for ($i = 0; $i < $length; ++$i) {
                    $column = Common_Common::getColumnName($i);
                    if ($title[$i] == '运单号') {
                        $objActSheet->setCellValueExplicit($column . $index, $value[$i], PHPExcel_Cell_DataType::TYPE_STRING);
                    } else {
                        $objActSheet->setCellValue($column . $index, $value[$i]);
                    }
                }
                $index++;
            }
            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name="' . $filename . '.xls');
            header("Content-Disposition:inline;filename=" . $filename . '.xls');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
        }
    }

    public function downDataAction()
    {

        $reportId = $this->_request->getParam('id', '');
        $sbCodes = $this->_request->getParam('sbcode', '');

        $report = Service_Report::getByField($reportId, "report_id");


        $sql = $report["report_sql"];
        $sql = $sql . "(";
        $sql = $sql . $sbCodes;
        $sql = $sql . ")";
        $sql = $sql . $report["report_sql_suffix"];

        $result = Common_Export::getDateBySql($sql);
        Ec::showError(var_export($result, 1), 'sql');
        if ($result['state'] == '1') {
            $filename = 'order';
            header("Content-Disposition: attachment; filename=" . $filename . ".csv");
            header('Content-Type:APPLICATION/OCTET-STREAM');
            echo Common_Export::exportCsv($result['data']);
            exit;
        } else {
            print_r($result);
        }
    }

    public function getDetailAction()
    {
        $sbCode = $this->_request->getParam("sb_code", "");
        $shipBatchDetail = Service_ShipBatchDetail::getByCondition(array('sb_code' => $sbCode), "*");
        $result = array(
            'ask' => '0',
            'message' => 'No Data',
        );
        if (count($shipBatchDetail)) {
            foreach ($shipBatchDetail as $key => $value) {
                $creater = Service_User::getByField($value['creater_id'], "user_id", "*");
                $shipBatchDetail[$key]['creater'] = $creater['user_code'];
            }
            $result['ask'] = '1';
            $result['data'] = $shipBatchDetail;
        }
        die(json_encode($result));
    }

    /**
     * @author colin-yang
     * @todo 用于导出出货总单表
     */
    public function hsinfoexportAction()
    {
        $sbCodes = $this->_request->getParam('sbCodes', '');
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $exportformat = 'xls';
        $fileName = 'shipbatch_list' . date('YmdHis');

        //客户代码信息数组
        $customers = Service_Customer::getAll();
        $customerInfo = array();
        foreach ($customers as $value) {
            $customerInfo[$value['customer_code']] = $value['customer_company_name'];
        }
        //产品单位信息数组
        $productUoms = Service_ProductUom::getAll();
        $productUomInfo = array();
        foreach ($productUoms as $value) {
            $productUomInfo[$value['pu_code']] = $value['pu_name'];
        }
        $stime = microtime(true); #获取程序开始执行的时间
        $etime = microtime(true); #获取程序执行结束的时间
        $total = $etime - $stime;   #计算差值
        // echo "<br />{$total} times";
        $orderHtml = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><table border="1">';

        $htmlTitle = "<tr><td colspan='21' style='font-size: 14px;font-weight: bold;text-align: center;'>前海湾保税港区跨境电商项目转关出区装箱清单</td></tr>";
        $htmlTitle .= '<tr><td>序号</td>';
        $htmlTitle .= '<td>出货总单号</td>';
        $htmlTitle .= '<td>出货子单号</td>';
        $htmlTitle .= '<td>包袋号</td>';
        $htmlTitle .= '<td>订单号</td>';
        $htmlTitle .= '<td>交易订单号</td>';
        $htmlTitle .= '<td>运单号</td>';
        $htmlTitle .= '<td>产品SKU</td>';
        $htmlTitle .= '<td>数量</td>';
        $htmlTitle .= '<td>单位</td>';
        $htmlTitle .= '<td>料件号</td>';
        $htmlTitle .= '<td>批次料件号</td>';
        $htmlTitle .= '<td>海关备案序号</td>';
        $htmlTitle .= '<td>海关商品编码</td>';
        $htmlTitle .= '<td>海关品名</td>';
        $htmlTitle .= '<td>产品中文名</td>';
        $htmlTitle .= '<td>单价(USD)</td>';
        $htmlTitle .= "<td>总价(USD)</td>";
        $htmlTitle .= "<td>重量(KG)</td>";
        $htmlTitle .= "<td>报关单项号</td>";
        $htmlTitle .= "<td>客户名称</td></tr>";
        $titlesku = '';
        $orderContent = '';
        $index = 1;
        if (!empty($sbCodes)) { //通过选择的订单获取
            //$exportData = $this->serviceClass->getHsinfoExportBySbcode(array('sb_code'=>$sbCodes));
            $exportData = Service_ShipBatchGoods::getHsinfoExportBySbcode(array('sb_code' => $sbCodes));
            foreach ($exportData as $data) {
                $orderContent .= "<tr>";
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$index}</td>";
                $index++;
                //出货总单单号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['sb_code']}</td>";
                //子单号
                $con2 = array(
                    'code_ts' => $data['hs_code'],
                    'sb_code' => $data['sb_code'],
                    'goods_id' => $data['goods_id'],
                );
                $sbxd = Service_ShipBatchXmlDetail::getByCondition($con2, "*");
                if (!empty($sbxd)) {
                    $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$sbxd[0]['sub_sb_code']}</td>";
                } else {
                    $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'></td>";
                }
                //包袋号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['ob_no']}</td>";
                //订单号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['order_code']}</td>";
                //交易订单号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['reference_no']}</td>";
                //运单号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['tracking_number']}</td>";
                //产品SKU
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['product_sku']}</td>";
                //数量
                $orderContent .= "<td>{$data['op_quantity']}</td>";
                //单位
                if ($data['pu_code'] != "") {
                    $puName = isset($productUomInfo[$data['pu_code']]) ? $productUomInfo[$data['pu_code']] : "";
                }
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$puName}</td>";
                //料件号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['goods_id']}</td>";
                //批次料件号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['batch_goods_id']}</td>";
                //海关备案号
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['hs_serial_no']}</td>";
                //商品海关编码
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['hs_code']}</td>";
                //海关品名
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['hs_goods_name']}</td>";
                //产品中文名
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['product_title_cn']}</td>";
                //单价
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['op_declared_value']}</td>";
                //总价
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>" . $data['op_declared_value'] * $data['op_quantity'] . "</td>";
                //重量
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>" . $data['product_weight'] * $data['op_quantity'] . "</td>";
                //报关单号
                $con = array(
                    'sb_code' => $sbxd[0]['sub_sb_code'] ? $sbxd[0]['sub_sb_code'] : $data['sb_code'],
                    'CODE_TS' => $data['hs_code'],
                    'G_UNIT' => $sbxd[0]['g_unit'] ? $sbxd[0]['g_unit'] : "",
                    'UNIT_1' => $sbxd[0]['unit_1'] ? $sbxd[0]['unit_1'] : "",
                );
                $sbm = Service_ShipBatchMerge::getByCondition($con, "GOODS_SEQ");
                $SEQNO = isset($sbm[0]['GOODS_SEQ']) ? $sbm[0]['GOODS_SEQ'] : "";
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$SEQNO}</td>";
                $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$customerInfo[$data['customer_code']]}</td>";
                $orderContent .= "</tr>";
            }
            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name="' . $fileName . ".{$exportformat}");
            header("Content-Disposition:inline;filename=" . $fileName . ".{$exportformat}");
            echo $orderHtml . $htmlTitle . $orderContent . '</table>';
            exit();
        } else {
            $params = $this->_request->getParams();
            $operationType = isset($params['operationType']) ? $params['operationType'] : '';
            $operationCode = isset($params['operationCode']) ? $params['operationCode'] : '';
            if (!empty($operationCode)) {
                $params[$operationType] = $operationCode;
            }
            $s_condition = $this->serviceClass->getMatchFields($params);
            $s_condition['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
            $s_condition['dateTo'] = isset($params['dateTo']) ? $params['dateTo'] : '';
            $s_condition['ship_time_start'] = isset($params['sb_ship_time_start']) ? $params['sb_ship_time_start'] : "";
            $s_condition['ship_time_end'] = isset($params['sb_ship_time_end']) ? $params['sb_ship_time_end'] : "";
            $s_condition['project_type'] = empty($params['E23']) ? '' : $params['E23'];
            $s_condition['sb_status_arr'] = isset($params['sb_status_arr']) ? trim($params['sb_status_arr']) : '';
            $s_condition['out_area'] = isset($params['out_area']) ? $params['out_area'] : '';
            $s_condition['ob_no'] = isset($params['ob_no']) ? trim($params['ob_no']) : '';
            //$count = $this->serviceClass->getHsinfoExportBySbcode($s_condition, 'count(*)');
            $count = Service_ShipBatchGoods::getHsinfoExportBySbcode($s_condition, 'count(*)');
            if ($count > 0) {
                $pageSize = 20;
                $pages = ceil($count / $pageSize);
                for ($page = 1; $page <= $pages; $page++) {
                    //通过查询条件的订单获取
                    //$exportData = $this->serviceClass->getHsinfoExportBySbcode($s_condition,'', $pageSize, $page, 'sb_id desc');
                    $exportData = Service_ShipBatchGoods::getHsinfoExportBySbcode($s_condition, '', $pageSize, $page, 'sb_code desc');
                    foreach ($exportData as $data) {
                        $orderContent .= "<tr>";
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$index}</td>";
                        $index++;
                        //出货总单单号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['sb_code']}</td>";
                        //子单号
                        $con2 = array(
                            'code_ts' => $data['hs_code'],
                            'sb_code' => $data['sb_code'],
                            'goods_id' => $data['goods_id']
                        );
                        $sbxd = Service_ShipBatchXmlDetail::getByCondition($con2, "*");
                        if (!empty($sbxd)) {
                            $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$sbxd[0]['sub_sb_code']}</td>";
                        } else {
                            $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'></td>";
                        }
                        //包袋号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['ob_no']}</td>";
                        //订单号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['order_code']}</td>";
                        //交易订单号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['reference_no']}</td>";
                        //运单号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['tracking_number']}</td>";
                        //产品SKU
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['product_sku']}</td>";
                        //数量
                        $orderContent .= "<td >{$data['op_quantity']}</td>";
                        //单位
                        if ($data['pu_code'] != "") {
                            $puName = isset($productUomInfo[$data['pu_code']]) ? $productUomInfo[$data['pu_code']] : "";
                        }
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$puName}</td>";
                        //料件号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['goods_id']}</td>";
                        //批次料件号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['batch_goods_id']}</td>";
                        //海关备案号
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['hs_serial_no']}</td>";
                        //商品海关编码
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['hs_code']}</td>";
                        //海关品名
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['hs_goods_name']}</td>";
                        //产品中文名
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['product_title_cn']}</td>";
                        //单价
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$data['op_declared_value']}</td>";
                        //总价
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>" . $data['op_declared_value'] * $data['op_quantity'] . "</td>";
                        //重量
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>" . $data['product_weight'] * $data['op_quantity'] . "</td>";
                        //报关单号
                        //报关单号
                        $con = array(
                            'sb_code' => $sbxd[0]['sub_sb_code'] ? $sbxd[0]['sub_sb_code'] : $data['sb_code'],
                            'CODE_TS' => $data['hs_code'],
                            'G_UNIT' => $sbxd[0]['g_unit'] ? $sbxd[0]['g_unit'] : "",
                            'UNIT_1' => $sbxd[0]['unit_1'] ? $sbxd[0]['unit_1'] : "",
                        );
                        $sbm = Service_ShipBatchMerge::getByCondition($con, "GOODS_SEQ");
                        $SEQNO = isset($sbm[0]['GOODS_SEQ']) ? $sbm[0]['GOODS_SEQ'] : "";
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$SEQNO}</td>";
                        $orderContent .= "<td style='vnd.ms-excel.numberformat:@;'>{$customerInfo[$data['customer_code']]}</td>";
                        $orderContent .= "</tr>";
                    }
                }
                header('Pragma:public');
                header('Content-Type:application/x-msexecl;name="' . $fileName . ".{$exportformat}");
                header("Content-Disposition:inline;filename=" . $fileName . ".{$exportformat}");
                echo $orderHtml . $htmlTitle . $orderContent . '</table>';
            }//if($count>0){
        }//if(!empty($sbCodes)){
        exit;
    }//function end

    /*
    *@desc 根据一般监管形式导出
    */
    public function modelexportAction()
    {
        set_time_limit(600);
        $exportformat = 'xls';
        $fileName = 'shipbatch_0110_list' . date('YmdHis');
        $pagesize = 50;

        ini_set('memory_limit', '1024M');
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $condition['trade_mode'] = '0110';
        $condition['sb_code'] = $this->_request->getParam('sbCodes', '');

        $obpe = new PHPExcel();
        /*$count = Service_ShipBatchGoods::getProductsByCondition($condition,'count');
        if(empty($count)){
            $count=$this->serviceClass->getProductsByCondition($condition,'count');
        }*/
        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($condition['sb_code'], 'sb_code', "*");
        $count = $this->serviceClass->getProductsByCondition($condition, 'count');
        $count = (int)$count;
        $ajax = $this->_request->getParam('ajax', false);
        if ($count > 0) {
            if ($ajax == true) {
                $result['ask'] = 1;
                die(Zend_Json::encode($result));
            }
            $pages = ceil($count / $pagesize);
            //$pages=1;
            $sbCodes = $this->_request->getParam('sbCodes', '');
            //$B3='LH-DH-'.date('Ymd').'-'.rand(10,4);
            $styleArray = array(
                'font' => array(
                    'bold' => true,
                    'size' => 9,
                    'color' => array(
                        'argb' => '00000000',
                    ),
                ),
                'alignment' => array(
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
            );
            $border = array(
                'borders' => array(
                    'allborders' => array(
                        //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                        'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框  
                        //'color' => array('argb' => 'FFFF0000'),  
                    ),
                ),
            );
            $totalNt = 0;
            $subindex = 1;
            $grossWtArr = array();
            $codeArr = array();
            $totalPrice = array();
            for ($page = 0; $page < $pages; $page++) {
                $list = $this->serviceClass->getProductsByCondition($condition, '*', $pagesize, ($page + 1));
                /*$list = Service_ShipBatchGoods::getProductsByCondition($condition,'*',$pagesize,($page+1));
                if(empty($list)){
                    $list=$this->serviceClass->getProductsByCondition($condition,'*',$pagesize,($page+1));
                }*/
                $obpe->createSheet();
                $obpe->setActiveSheetIndex($page);
                $obpe->getActiveSheet()->getColumnDimension('A')->setWidth(20);
                $obpe->getActiveSheet()->getColumnDimension('B')->setWidth(14);
                $obpe->getActiveSheet()->getColumnDimension('C')->setWidth(14);
                $obpe->getActiveSheet()->getColumnDimension('D')->setWidth(12);
                $obpe->getActiveSheet()->getColumnDimension('E')->setWidth(14);
                $obpe->getActiveSheet()->getStyle('E')->getAlignment()->setWrapText(true);
                $obpe->getActiveSheet()->getColumnDimension('F')->setWidth(46);
                $obpe->getActiveSheet()->getColumnDimension('G')->setWidth(12);
                $obpe->getActiveSheet()->getColumnDimension('H')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('I')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('J')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('K')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('L')->setWidth(10);
                $obpe->getActiveSheet()->getColumnDimension('M')->setWidth(10);
                $obpe->getActiveSheet()->getColumnDimension('N')->setWidth(8);

                $obpe->setActiveSheetIndex($page)->setCellValue('A1', '通用模板');
                $obpe->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->mergeCells('A1:N1');

                $obpe->setActiveSheetIndex($page)->setCellValue('A2', '项目名称:');
                $obpe->getActiveSheet()->getStyle('A2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B2', 'CSCM-OWNEX');
                $obpe->setActiveSheetIndex($page)->setCellValue('C2', '截重时间:');
                $obpe->getActiveSheet()->getStyle('C2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D2', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('E2', '截放行条:');
                $obpe->getActiveSheet()->getStyle('E2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F2', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('G2', 'S/O:');
                $obpe->getActiveSheet()->getStyle('G2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H2', '');

                $obpe->setActiveSheetIndex($page)->setCellValue('A3', '装箱单号(客户作业号):');
                $obpe->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B3', $shipBatchAttribute['sb_code'] . "-" . $subindex);
                $codeArr[$page] = $shipBatchAttribute['sb_code'] . "-" . $subindex;
                $subindex++;
                $obpe->setActiveSheetIndex($page)->setCellValue('C3', '出口口岸:');
                $obpe->getActiveSheet()->getStyle('C3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D3', '深圳湾海关');
                $obpe->setActiveSheetIndex($page)->setCellValue('E3', '目的港:');
                $obpe->getActiveSheet()->getStyle('E3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F3', '香港');
                $obpe->setActiveSheetIndex($page)->setCellValue('G3', '目的国:');
                $obpe->getActiveSheet()->getStyle('G3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H3', '香港');

                $obpe->setActiveSheetIndex($page)->setCellValue('A4', '船名/航次:');
                $obpe->getActiveSheet()->getStyle('A4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B4', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('C4', '柜号/柜型:');
                $obpe->getActiveSheet()->getStyle('C4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D4', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('E4', '仓库使用企业:');
                $obpe->getActiveSheet()->getStyle('E4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F4', '81862509Y/深圳保宏电子商务综合服务股份有限公司');
                $obpe->setActiveSheetIndex($page)->setCellValue('G4', '是否仓转仓:');
                $obpe->getActiveSheet()->getStyle('G4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H4', '否');

                $obpe->setActiveSheetIndex($page)->setCellValue('A5', '包装种类:');
                $obpe->getActiveSheet()->getStyle('A5')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B5', '其它');
                $obpe->setActiveSheetIndex($page)->setCellValue('C5', '总毛重:');
                $obpe->getActiveSheet()->getStyle('C5')->applyFromArray($styleArray);
                //$obpe->setActiveSheetIndex($page)->setCellValue('D5', $shipBatchAttribute['gross_wt']);

                $obpe->setActiveSheetIndex($page)->setCellValue('E5', '总净重:');
                $obpe->getActiveSheet()->getStyle('E5')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->setCellValue('G5', '总件数:');
                $obpe->getActiveSheet()->getStyle('G5')->applyFromArray($styleArray);
                //$obpe->setActiveSheetIndex($page)->setCellValue('H5',$shipBatchAttribute['pack_no']);

                $obpe->setActiveSheetIndex($page)->setCellValue('A6', '备注栏:');
                $obpe->getActiveSheet()->getStyle('A6')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->mergeCells('B6:F6');

                $obpe->setActiveSheetIndex($page)->setCellValue('G6', '拼数:');
                $obpe->getActiveSheet()->getStyle('G6')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H6', '');
                $obpe->getActiveSheet()->getStyle('A1:H6')->applyFromArray($border);

                $obpe->setActiveSheetIndex($page)->setCellValue('A8', '序号');
                $obpe->getActiveSheet()->getStyle('A8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B8', '入仓单号料件号');
                $obpe->getActiveSheet()->getStyle('B8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('C8', '商品编码');
                $obpe->getActiveSheet()->getStyle('C8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D8', '报关品名');
                $obpe->getActiveSheet()->getStyle('D8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('E8', '规格型号');
                $obpe->getActiveSheet()->getStyle('E8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F8', '申报数量');
                $obpe->getActiveSheet()->getStyle('F8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('G8', '申报单位');
                $obpe->getActiveSheet()->getStyle('G8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H8', '法定数量');
                $obpe->getActiveSheet()->getStyle('H8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('I8', '法定单位');
                $obpe->getActiveSheet()->getStyle('I8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('J8', '第二数量');
                $obpe->getActiveSheet()->getStyle('J8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('K8', '第二单位');
                $obpe->getActiveSheet()->getStyle('K8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('L8', '单价');
                $obpe->getActiveSheet()->getStyle('L8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('M8', '总价');
                $obpe->getActiveSheet()->getStyle('M8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('N8', '申报币制');
                $obpe->getActiveSheet()->getStyle('N8')->applyFromArray($styleArray);

                $index = 1;
                $count_w = 0;//总毛重
                $count_nw = 0;//总净重
                $count_price = 0;
                foreach ($list as $k => $v) {
                    $k = $k + 9;
                    $count_w += $v['cw'];
                    $count_price += $v['declared_value'];
                    //$count_nw+=$v['ncw'];
                    $hsElementCondition = array(
                        'product_id' => $v['product_id']
                    );
                    $hselementMaps = Service_HsElementMap::getByCondition($hsElementCondition, '*');
                    if (!empty($hselementMaps)) {
                        $hsString = array();
                        foreach ($hselementMaps as $khsm => $vhsm) {
                            $hsString[] = $vhsm['hem_detail'];
                        }
                        $hsString = implode('|', $hsString);
                    }
                    //$hum_quantity_law=$v['hum_quantity_law']*$v['quantity'];
                    $obpe->setActiveSheetIndex($page)->setCellValue('A' . $k, $index);
                    $index++;
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('B' . $k, $v['goods_id'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('C' . $k, $v['hs_code'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('D' . $k, $v['hs_goods_name']);
                    $obpe->setActiveSheetIndex($page)->setCellValue('E' . $k, empty($hsString) ? '' : $hsString);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('F' . $k, (string)sprintf('%.4f', $v['quantity']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('G' . $k, $v['pu_code']);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('H' . $k, (string)sprintf('%.4f', $v['hum_quantity_law']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('I' . $k, $v['pu_code_law']);
                    $v['hum_quantity_second'] =
                        empty($v['hum_quantity_second']) ?
                            '' : (string)sprintf('%.4f', $v['hum_quantity_second']);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('J' . $k, $v['hum_quantity_second'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('K' . $k, $v['pu_code_second']);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('L' . $k, (string)sprintf('%.2f', $v['declared_value'] / $v['quantity']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('M' . $k, sprintf('%.2f', $v['declared_value']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('N' . $k, $v['currency_name']);
                }
                //$obpe->setActiveSheetIndex($page)->setCellValue('D5', $count_w);
                $obpe->setActiveSheetIndex($page)
                    ->setCellValue('B6', '收货人：A-LINK TELECOM  总价：USD  '
                        . sprintf('%.2f', $count_price) .
                        '    总件数:');
                //$obpe->setActiveSheetIndex($page)->setCellValue('D5', $shipBatchAttribute['gross_wt']);
                $totalPrice[$page] = sprintf('%.2f', $count_price);

                $obpe->setActiveSheetIndex($page)->setCellValueExplicit('F5', round($count_w, 4), PHPExcel_Cell_DataType::TYPE_STRING);
                $totalNt += round($count_w, 4);
                $grossWtArr[$page] = round($count_w, 4);
                $obpe->getActiveSheet()->setTitle('第' . ($page + 1) . '单');

            }
            $totalGrossWDivNt = ($shipBatchAttribute['gross_wt'] - $totalNt) / $pages;
            $gwtArr = array();
            $packNoArr = array();
            for ($page = 0; $page < $pages; $page++) {
                $gwt = round($totalGrossWDivNt + $grossWtArr[$page], 4);
                $gwtArr[$page] = $gwt;
                $obpe->setActiveSheetIndex($page)->setCellValue('D5', $gwt);
                $packNo = round($gwt / $shipBatchAttribute['gross_wt'] * $shipBatchAttribute['pack_no']);
                $packNoArr[$page] = $packNo;
                $obpe->setActiveSheetIndex($page)->setCellValue('H5', $packNo);
            }
            $obpe->createSheet();
            $obpe->setActiveSheetIndex($pages);
            $obpe->getActiveSheet()->setTitle('汇总');
            $obpe->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obpe->getActiveSheet()->getColumnDimension('B')->setWidth(14);
            $obpe->getActiveSheet()->getColumnDimension('C')->setWidth(14);
            $obpe->getActiveSheet()->getColumnDimension('D')->setWidth(12);
            $obpe->getActiveSheet()->getColumnDimension('E')->setWidth(14);

            $obpe->setActiveSheetIndex($pages)->setCellValue('A1', '单号');
            $obpe->setActiveSheetIndex($pages)->setCellValue('B1', '件数');
            $obpe->setActiveSheetIndex($pages)->setCellValue('C1', '净重(KG)');
            $obpe->setActiveSheetIndex($pages)->setCellValue('D1', '毛重(KG)');
            $obpe->setActiveSheetIndex($pages)->setCellValue('E1', '价值(USD)');
            $index = 2;
            $allTotalPrice = 0;
            for ($page = 0; $page < $pages; $page++) {
                $obpe->setActiveSheetIndex($pages)->setCellValue('A' . $index, $codeArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('A' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('B' . $index, $packNoArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('B' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('C' . $index, $grossWtArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('C' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('D' . $index, $gwtArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('D' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('E' . $index, $totalPrice[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('E' . $index)->applyFromArray($styleArray);
                $allTotalPrice += $totalPrice[$page];
                $index++;
            }
            $obpe->setActiveSheetIndex($pages)->setCellValue('A' . $index, '总计');
            $obpe->setActiveSheetIndex($pages)->setCellValue('B' . $index, $shipBatchAttribute['pack_no']);
            $obpe->setActiveSheetIndex($pages)->setCellValue('C' . $index, $totalNt);
            $obpe->setActiveSheetIndex($pages)->setCellValue('D' . $index, $shipBatchAttribute['gross_wt']);
            $obpe->setActiveSheetIndex($pages)->setCellValue('E' . $index, $allTotalPrice);
            $obpe->setActiveSheetIndex($pages)->getStyle('A1:E' . $index)->applyFromArray($border);


            $obpe->setActiveSheetIndex(0);
            $obwrite = PHPExcel_IOFactory::createWriter($obpe, 'Excel5');
            header('pragma: public');
            header('expires: 0');
            header('accept-ranges: bytes');
            header('cache-control: must-revalidate');
            header('content-type: application/vnd.ms-excel; charset=utf-8');
            header('content-disposition: attachment; filename=' . $fileName . '-invoice.xls');
            $obwrite->save('php://output');
            exit();
        } else {
            $result['ask'] = 0;
            $result['msg'] = '无数据,请检查出区单的监管方式是否是一般贸易';
            die(Zend_Json::encode($result));
        }
    }

    public function trackinglistAction()
    {
        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);
            $condition['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
            $condition['dateTo'] = isset($params['dateTo']) ? $params['dateTo'] : '';
            $condition['sb_status_arr'] = array('1', '2', "3");
            if (!empty($condition['dateFor'])) {
                $condition['dateFor'] = date('Y-m-d H:i:s', strtotime($condition['dateFor'] . ' 00:00:00'));
            }
            if (!empty($condition['dateTo'])) {
                $condition['dateTo'] = date('Y-m-d H:i:s', strtotime($condition['dateTo'] . ' 23:59:59'));
            }
            //echo "<pre>";
            //var_dump($condition);
            //echo "</pre>";
            //die("XXX");
            //getJoinOrderByCondition

            //$count = $this->serviceClass->getLeftJoinUserByCondition($condition, 'count(*)');
            $count = $this->serviceClass->getJoinOrderByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields = array(

                    'sb_code',
                    'sm_code',
                    'warehouse_id',
                    'creater_id',
                    'sb_status',
                    'reference_no',
                    'sb_truck_no',
                    'sb_ship_time',
                    'sb_add_time',
                    'sb_update_time',
                    'sb_id',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                //$rows = $this->serviceClass->getLeftJoinUserByCondition($condition,$showFields, $pageSize, $page, array('sb_id desc'));
                $rows = $this->serviceClass->getJoinOrderByCondition($condition, $showFields, $pageSize, $page, array('sb_id desc'));
                //echo "<pre>";
                //var_dump($rows);
                //echo "</pre>";
                foreach ($rows as $key => $value) {
                    $shipBatchAttribute = Service_ShipBatchAttribute::getByField($value['E1'], 'sb_code', "*");
                    $rows[$key]['to_hongkong_time'] = $shipBatchAttribute['to_hongkong_time'];
                    $rows[$key]['delivery_dhl_time'] = $shipBatchAttribute['delivery_dhl_time'];
                    $rows[$key]['fly_time'] = $shipBatchAttribute['fly_time'];
                    $rows[$key]['arrival_time'] = $shipBatchAttribute['arrival_time'];
                    $rows[$key]['cleanup_time'] = $shipBatchAttribute['cleanup_time'];
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['status'] = Common_Status::shipBatchStatus('auto');
                $return['warehouse'] = Common_DataCache::getWarehouseSimple();
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "ship_batch_tracking.tpl", 'layout');
    }

    public function addTrackingAction()
    {
        //var MessageType = $("[name='MessageType']").val();
        //var sbCode = $("[name='sbCode']").val();
        //var sot_location = $("[name='sot_location']").val();
        //var sot_add_time = $("[name='sot_add_time']").val();
        //var sot_description = $("[name='sot_description']").val();

        $result = array('ask' => 0, 'message' => '');

        $messageType = $this->_request->getParam("MessageType", "");
        $sbCode = $this->_request->getParam("sbCode", "");
        $sot_location = $this->_request->getParam("sot_location", "");
        $sot_add_time = $this->_request->getParam("sot_add_time", "");
        $sot_description = $this->_request->getParam("sot_description", "");
        $sba = Service_ShipBatchAttribute::getByField($sbCode, 'sb_code');
        $shipBatchAttr = array();
        $type = "";
        switch ($messageType) {
            case 'toHongKong':
                $time = $sba['to_hongkong_time'];
                $shipBatchAttr['to_hongkong_time'] = $sot_add_time;
                $type = "1";
                break;
            case 'toDHL':
                $time = $sba['delivery_dhl_time'];
                $shipBatchAttr['delivery_dhl_time'] = $sot_add_time;
                $type = "2";
                break;
            case 'fly':
                $time = $sba['fly_time'];
                $shipBatchAttr['fly_time'] = $sot_add_time;
                $type = "3";
                break;
            case 'rearch':
                $time = $sba['arrival_time'];
                $shipBatchAttr['arrival_time'] = $sot_add_time;
                $type = "4";
                break;
            case 'tihuo':
                $time = $sba['cleanup_time'];
                $shipBatchAttr['cleanup_time'] = $sot_add_time;
                $type = "5";
                break;
        }//echo $time;exit;
        $DB = Common_Common::getAdapter();
        $DB->beginTransaction();
        try {
            Service_ShipBatchAttribute::update($shipBatchAttr, $sbCode, 'sb_code');
            $shipBatchOrder = Service_OutboundBagDetail::getJoinShipBatchDetailByCondition(array('sb_code' => $sbCode), "*");
            foreach ($shipBatchOrder as $k => $v) {
                $orderInfo = Service_Orders::getByField($v['order_code'], "order_code", "*");
                $userId = Service_User::getUserId();
                if ($orderInfo['sm_code'] == 'BH-HKZT') {
                    $userId = 0;
                }
                $shipOrderTracking = array(
                    'order_code' => $orderInfo['order_code'],
                    'sot_location' => $sot_location,
                    'sot_add_time' => $sot_add_time,
                    'warehouse_id' => $orderInfo['warehouse_id'],
                    'sot_description' => $sot_description,
                    'sot_type' => '0',
                    'sot_time_offset' => '',
                    'tracking_number' => $orderInfo['order_code'],
                    'ref_tracking_number' => '',
                    'status_desc' => '物流完成',
                    'user_id' => $userId,
                    'sot_info_type' => $type,
                );
                if ($time == '0000-00-00 00:00:00') {
                    Service_ShipOrderTracking::add($shipOrderTracking);
                    $result['ask'] = 1;
                    $result['message'] = "物流轨迹信息添加成功";
                } else {
                    $condition = array(
                        'order_code' => $orderInfo['order_code'],
                        'sot_info_type' => $type,
                    );
                    $sot = Service_ShipOrderTracking::getByCondition($condition);
                    foreach ($sot as $key => $value) {
                        Service_ShipOrderTracking::update($shipOrderTracking, $value['sot_id'], 'sot_id');
                    }
                    $result['ask'] = 1;
                    $result['message'] = "物流轨迹信息修改成功";
                }

            }
            $DB->commit();
        } catch (Exception $e) {
            $DB->rollBack();
            $result['error'][] = $e->getMessage();
            $result['msg'] = $e->getMessage();
            return $result;
        }
        die(Zend_Json::encode($result));
    }

    public function getTrackingInfoAction()
    {
        $sbCode = $this->_request->getParam("sbCode", "");
        $messageType = $this->_request->getParam("type", "");
        $type = "0";
        switch ($messageType) {
            case 'toHongKong':
                $type = "1";
                break;
            case 'toDHL':
                $type = "2";
                break;
            case 'fly':
                $type = "3";
                break;
            case 'rearch':
                $type = "4";
                break;
            case 'tihuo':
                $type = "5";
                break;
        }
        $shipBatchOrder = Service_OutboundBagDetail::getJoinShipBatchDetailByCondition(array('sb_code' => $sbCode), "*");
        $TrackingInfo = Service_ShipOrderTracking::getByCondition(array('order_code' => $shipBatchOrder[0]['order_code'], 'sot_info_type' => $type), "*");
        if (!empty($TrackingInfo)) {
            die(json_encode($TrackingInfo[0]));
        } else {
            die("0");
        }
    }

    // 打印出区派车单之前验证
    public function printCscmEcoValidateAction()
    {
        $response = array('status' => 0, 'message' => '非法请求');

        if ($this->getRequest()->isPost()) {
            $shipBatchCode = $this->getRequest()->getPost('sbCodes', NULL);
            $filterCode = array();

            if (is_array($shipBatchCode)) {
                foreach ($shipBatchCode as $key => $value) {
                    if ('' !== trim($value)) {
                        $filterCode[trim($value)] = trim($value);
                        continue;
                    }
                }

                if (count($filterCode) > 0) {
                    $error = array();
                    $car = array();
                    $port = array();
                    $cabinet = array();

                    foreach ($filterCode as $key => $code) {
                        $shipBatch = Service_ShipBatch::getByField($code, 'sb_code');

                        if (!empty($shipBatch)) {
                            /*if (!in_array((int) $shipBatch['sb_status'], array(2, 3), TRUE)) {
                              $error[] = '出货总单【' . $code . '】不是已审核或已出货状态';
                              continue ;
                            }*/

                            if (0 === (int)$shipBatch['sb_status']) {
                                $error[] = '出货总单【' . $code . '】为草稿状态';
                                continue;
                            }

                            $carNumber = trim($shipBatch['sb_truck_no']);
                            $car[] = $carNumber;

                            if ('' === $carNumber) {
                                $error[] = '出货总单【' . $code . '】车牌号为空';
                                continue;
                            }

                            $shipBatchAttr = Service_ShipBatchAttribute::getByField($code, 'sb_code');

                            if (empty($shipBatchAttr)) {
                                $error[] = '出货总单【' . $code . '】缺乏必要的属性';
                                continue;
                            }

                            $iePort = trim($shipBatchAttr['ie_port']);
                            $port[] = $iePort;
                            $cabinet[] = ('' !== trim($shipBatchAttr['conta_id'])) ? 1 : 0;

                            if ('' === $iePort) {
                                $error[] = '出货总单【' . $code . '】缺进出口口岸为空';
                                continue;
                            }
                        } else {
                            $error[] = '出货总单【' . $code . '】不存在';
                        }
                    }

                    if (empty($error)) { // 没有错误信息，则检查车牌号、进出口口岸是否一致
                        $ucar = array_unique($car);
                        $uport = array_unique($port);
                        $ucabinet = array_unique($cabinet);

                        if (empty($car)) {
                            $error[] = '所选的出货总单缺乏车牌号信息';
                        } elseif (!empty($car) && 1 !== count($ucar)) {
                            $error[] = '所选的出货总单存在车牌号不一致的情况';
                        }

                        if (empty($port)) {
                            $error[] = '所选的出货总单缺乏进出口口岸信息';
                        } elseif (!empty($port) && 1 !== count($uport)) {
                            $error[] = '所选的出货总单存在进出口口岸不一致的情况';
                        } elseif (!empty($uport) && 1 === count($uport)) {
                            $iePort = Service_IePort::getByField($uport[0], 'ie_port');

                            if (empty($iePort)) {
                                $error[] = '进出口口岸【' . $uport[0] . '】不存在';
                            }
                        }

                        /*if (empty($cabinet)) {
                          $error[] = '所选的出货总单缺乏柜型信息';
                        }
                        elseif (!empty($cabinet) && 1 !== count($ucabinet)) {
                          $error[] = '所选的出货总单存在柜型不一致的情况';
                        }*/
                    }

                    if (count($error) > 0) { // 错误信息
                        $response['message'] = '打印出区派车单失败，原因：<br />' . join($error, '<br />');
                    } else {
                        $response['status'] = 1;
                        $response['message'] = '__IT_IS_VALID_DATA__' . count($filterCode);
                    }
                }
            }
        }

        exit(Zend_Json::encode($response));
    }

    // 打印出区派车单
    public function printCscmEcoAction()
    {
        $shipBatchCode = $this->getRequest()->getParam('sbCodes', NULL);
        $filterCode = array();
        $error = array();
        $car = array();
        $port = array();
        $cabinet = array();
        $this->view->isError = FALSE;

        if (is_array($shipBatchCode)) {
            foreach ($shipBatchCode as $key => $value) {
                if ('' !== trim($value)) {
                    $filterCode[trim($value)] = trim($value);
                    continue;
                }
            }

            if (count($filterCode) > 0) {
                foreach ($filterCode as $key => $code) {
                    $shipBatch = Service_ShipBatch::getByField($code, 'sb_code');

                    if (!empty($shipBatch)) {
                        /*if (!in_array((int) $shipBatch['sb_status'], array(2, 3), TRUE)) {
                          $error[] = '出货总单【' . $code . '】不是已审核或已出货状态';
                          continue ;
                        }*/

                        if (0 === (int)$shipBatch['sb_status']) {
                            $error[] = '出货总单【' . $code . '】为草稿状态';
                            continue;
                        }

                        $carNumber = trim($shipBatch['sb_truck_no']);
                        $car[] = $carNumber;
                        $filterCode[$key] = $shipBatch;
                        $shipBatchAttr = Service_ShipBatchAttribute::getByField($code, 'sb_code');
                        $shipBatchDetail = Service_ShipBatchDetail::getByCondition(
                            array('sb_code' => $shipBatch['sb_code'])
                        );

                        if (empty($shipBatchAttr)) {
                            $error[] = '出货总单【' . $code . '】缺乏必要的属性';
                            continue;
                        }

                        $iePort = trim($shipBatchAttr['ie_port']);
                        $port[] = $iePort;
                        $cabinet[] = ('' !== trim($shipBatchAttr['conta_id'])) ? 1 : 0;
                        $filterCode[$key]['attribute'] = $shipBatchAttr;

                        if ('' === $iePort) {
                            $error[] = '出货总单【' . $code . '】缺进出口口岸为空';
                            continue;
                        }

                        $dataMessage = Service_FtpMessageSendlist::getByCondition(array(
                            'fmt_code' => 'MCK',
                            'refercence_no' => $code
                        ));
                        $dataMessagePath = $dataMessage ? trim($dataMessage[0]['fml_path']) : '';

                        $filterCode[$key]['packNo'] = 0; // 件数
                        $filterCode[$key]['totalGrossWeight'] = 0; // 毛重
                        $filterCode[$key]['totalNetWeight'] = 0; // 净重
                        $filterCode[$key]['totalDecalreValue'] = 0; // 申报价值

                        // 获取出货报文路径
                        if ('' !== $dataMessagePath) {
                            $dataMessagePath = APPLICATION_PATH . '/../data/ftp' . $dataMessagePath;
                            $objDataXml = simplexml_load_file($dataMessagePath);

                            if (FALSE !== $objDataXml) {
                                $filterCode[$key]['packNo'] = trim($objDataXml->Declaration->WAREHOUSE_BILL_HEAD->PACK_NO);
                                $filterCode[$key]['totalGrossWeight'] = trim($objDataXml->Declaration->WAREHOUSE_BILL_HEAD->GROSS_WT);
                                $filterCode[$key]['totalNetWeight'] = trim($objDataXml->Declaration->WAREHOUSE_BILL_HEAD->NET_WT);

                                foreach ($objDataXml->Declaration->WAREHOUSE_BILL_HEAD->WAREHOUSE_BILL_LIST as $item) {
                                    $filterCode[$key]['totalDecalreValue'] += floatval(trim($item->DECL_TOTAL));
                                }
                            }
                        }

                        /*$filterCode[$key]['totalGrossWeight']  = $shipBatchAttr['gross_wt']; // 毛重计算=出货总单所有袋子重量之和
                        $filterCode[$key]['totalNetWeight']    = $shipBatchAttr['net_wt']; // 净重计算=所有产品质量之和
                        $filterCode[$key]['totalDecalreValue'] = 0; // 总价计算=所有产品目的海关申报价值之和
                        if (!empty($shipBatchDetail)) {
                          foreach ($shipBatchDetail as $item) {
                            // ship_batch_attribute表存在gross_wt则直接取其值否则需计算
                            if (empty($shipBatchAttr['gross_wt']) || preg_match('/^0(?:\.0+)?$/', $shipBatchAttr['gross_wt'])) {
                              $filterCode[$key]['totalGrossWeight'] += $item['ob_weight'];
                            }

                            // 获取袋子里的订单
                            $outboundBagDetail = Service_OutboundBagDetail::getByCondition(array(
                              'ob_no' => $item['ob_no']
                            ));

                            if (!empty($outboundBagDetail)) {
                              // 根据订单提取产品
                              foreach ($outboundBagDetail as $record) {
                                $orderProduct = Service_OrderProduct::getByCondition(array(
                                  'order_code' => $record['order_code']
                                ));

                                // 计算总价、计算净重
                                if (!empty($orderProduct)) {
                                  foreach ($orderProduct as $product) {
                                    $filterCode[$key]['totalDecalreValue'] += $product['op_quantity'] * $product['op_purpose_declared_value'];
                                    $productDetail = Service_Product::getByField((int) $product['product_id'], 'product_id');

                                    // ship_batch_attribute表存在net_wt则直接取其值否则需计算
                                    if (empty($shipBatchAttr['net_wt']) || preg_match('/^0(?:\.0+)?$/', $shipBatchAttr['net_wt'])) {
                                      $filterCode[$key]['totalNetWeight'] += $productDetail ? $product['op_quantity'] * $productDetail['product_weight'] : 0;
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }*/

                        if ('' === $carNumber) {
                            $error[] = '出货总单【' . $code . '】车牌号为空';
                            continue;
                        }
                    } else {
                        $error[] = '出货总单【' . $code . '】不存在';
                    }
                }

                if (empty($error)) { // 没有错误信息，则检查车牌号、进出口口岸是否一致
                    $ucar = array_unique($car);
                    $uport = array_unique($port);
                    $ucabinet = array_unique($cabinet);

                    if (empty($car)) {
                        $error[] = '所选的出货总单缺乏车牌号信息';
                    } elseif (!empty($car) && 1 !== count($ucar)) {
                        $error[] = '所选的出货总单存在车牌号不一致的情况';
                    }

                    if (empty($port)) {
                        $error[] = '所选的出货总单缺乏进出口口岸信息';
                    } elseif (!empty($port) && 1 !== count($uport)) {
                        $error[] = '所选的出货总单存在进出口口岸不一致的情况';
                    } elseif (!empty($uport) && 1 === count($uport)) {
                        $iePort = Service_IePort::getByField($uport[0], 'ie_port');

                        if (empty($iePort)) {
                            $error[] = '进出口口岸【' . $uport[0] . '】不存在';
                        }
                    }

                    /*if (empty($cabinet)) {
                      $error[] = '所选的出货总单缺乏柜型信息';
                    }
                    elseif (!empty($cabinet) && 1 !== count($ucabinet)) {
                      $error[] = '所选的出货总单存在柜型不一致的情况';
                    }*/
                }
            }
        } else {
            $this->view->isError = TRUE;
            $this->view->errorContent = '非法请求';
        }

        if (count($error) > 0) {
            $this->view->errorContent = join($error, '<br />');
            $this->view->isError = TRUE;
        } else {
            $carNumber = preg_replace('/([a-zA-Z0-9]+)/', '<span class="english">\1</span>', $ucar[0]);

            $this->view->shipBatch = array_chunk($filterCode, 8);
            $this->view->totalShipBatch = count($filterCode);
            $this->view->totalPage = ceil(count($filterCode) / 8);
            $this->view->carNumber = $carNumber;
            $this->view->cabinet = (1 === (int)$ucabinet[0]) ? '集装箱' : '吨车';
            $this->view->iePortCode = $iePort['ie_port'];
            $this->view->iePortName = $iePort['ie_port_name'];
            $this->view->year = date('Y');
            $this->view->month = date('n');
            $this->view->day = date('j');
        }

        echo $this->view->render($this->tplDirectory . 'cscm-eco.tpl');
    }


    public function exportBgdAction()
    {
        set_time_limit(600);
        $exportformat = 'xls';
        $fileName = 'shipbatch_0110_list' . date('YmdHis');
        $pagesize = 50;

        ini_set('memory_limit', '1024M');
        require_once APPLICATION_PATH . '/../libs/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel/IOFactory.php';

        $condition['trade_mode'] = '0110';
        $condition['sb_code'] = $this->_request->getParam('sbCodes', '');

        $obpe = new PHPExcel();
        /*$count = Service_ShipBatchGoods::getProductsByCondition($condition,'count');
        if(empty($count)){
            $count=$this->serviceClass->getProductsByCondition($condition,'count');
        }*/
        $shipBatchAttribute = Service_ShipBatchAttribute::getByField($condition['sb_code'], 'sb_code', "*");
        $count = Service_ShipBatchGoods::getProductsByCondition($condition, 'count');
        $count = (int)$count;
        $ajax = $this->_request->getParam('ajax', false);
        if ($count > 0) {
            if ($ajax == true) {
                $result['ask'] = 1;
                die(Zend_Json::encode($result));
            }
            $pages = ceil($count / $pagesize);
            //$pages=1;
            $sbCodes = $this->_request->getParam('sbCodes', '');
            //$B3='LH-DH-'.date('Ymd').'-'.rand(10,4);
            $styleArray = array(
                'font' => array(
                    'bold' => true,
                    'size' => 9,
                    'color' => array(
                        'argb' => '00000000',
                    ),
                ),
                'alignment' => array(
                    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                ),
            );
            $border = array(
                'borders' => array(
                    'allborders' => array(
                        //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的
                        'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框
                        //'color' => array('argb' => 'FFFF0000'),
                    ),
                ),
            );
            $totalNt = 0;
            $subindex = 1;
            $grossWtArr = array();
            $codeArr = array();
            $totalPrice = array();
            for ($page = 0; $page < $pages; $page++) {
                //$list=$this->serviceClass->getProductsByCondition($condition,'*',$pagesize,($page+1));
                $list = Service_ShipBatchGoods::getProductsByCondition($condition, '*', $pagesize, ($page + 1));
                /*if(empty($list)){
                    $list=$this->serviceClass->getProductsByCondition($condition,'*',$pagesize,($page+1));
                }*/
                $obpe->createSheet();
                $obpe->setActiveSheetIndex($page);
                $obpe->getActiveSheet()->getColumnDimension('A')->setWidth(20);
                $obpe->getActiveSheet()->getColumnDimension('B')->setWidth(14);
                $obpe->getActiveSheet()->getColumnDimension('C')->setWidth(14);
                $obpe->getActiveSheet()->getColumnDimension('D')->setWidth(12);
                $obpe->getActiveSheet()->getColumnDimension('E')->setWidth(14);
                $obpe->getActiveSheet()->getStyle('E')->getAlignment()->setWrapText(true);
                $obpe->getActiveSheet()->getColumnDimension('F')->setWidth(46);
                $obpe->getActiveSheet()->getColumnDimension('G')->setWidth(12);
                $obpe->getActiveSheet()->getColumnDimension('H')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('I')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('J')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('K')->setWidth(8);
                $obpe->getActiveSheet()->getColumnDimension('L')->setWidth(10);
                $obpe->getActiveSheet()->getColumnDimension('M')->setWidth(10);
                $obpe->getActiveSheet()->getColumnDimension('N')->setWidth(8);

                $obpe->setActiveSheetIndex($page)->setCellValue('A1', '通用模板');
                $obpe->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->mergeCells('A1:N1');

                $obpe->setActiveSheetIndex($page)->setCellValue('A2', '项目名称:');
                $obpe->getActiveSheet()->getStyle('A2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B2', 'CSCM-OWNEX');
                $obpe->setActiveSheetIndex($page)->setCellValue('C2', '截重时间:');
                $obpe->getActiveSheet()->getStyle('C2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D2', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('E2', '截放行条:');
                $obpe->getActiveSheet()->getStyle('E2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F2', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('G2', 'S/O:');
                $obpe->getActiveSheet()->getStyle('G2')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H2', '');

                $obpe->setActiveSheetIndex($page)->setCellValue('A3', '装箱单号(客户作业号):');
                $obpe->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B3', $shipBatchAttribute['sb_code'] . "-" . $subindex);
                $codeArr[$page] = $shipBatchAttribute['sb_code'] . "-" . $subindex;
                $subindex++;
                $obpe->setActiveSheetIndex($page)->setCellValue('C3', '出口口岸:');
                $obpe->getActiveSheet()->getStyle('C3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D3', '深圳湾海关');
                $obpe->setActiveSheetIndex($page)->setCellValue('E3', '目的港:');
                $obpe->getActiveSheet()->getStyle('E3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F3', '香港');
                $obpe->setActiveSheetIndex($page)->setCellValue('G3', '目的国:');
                $obpe->getActiveSheet()->getStyle('G3')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H3', '香港');

                $obpe->setActiveSheetIndex($page)->setCellValue('A4', '船名/航次:');
                $obpe->getActiveSheet()->getStyle('A4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B4', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('C4', '柜号/柜型:');
                $obpe->getActiveSheet()->getStyle('C4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('D4', '');
                $obpe->setActiveSheetIndex($page)->setCellValue('E4', '仓库使用企业:');
                $obpe->getActiveSheet()->getStyle('E4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F4', '81862509Y/深圳保宏电子商务综合服务股份有限公司');
                $obpe->setActiveSheetIndex($page)->setCellValue('G4', '是否仓转仓:');
                $obpe->getActiveSheet()->getStyle('G4')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H4', '否');

                $obpe->setActiveSheetIndex($page)->setCellValue('A5', '包装种类:');
                $obpe->getActiveSheet()->getStyle('A5')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('B5', '其它');
                $obpe->setActiveSheetIndex($page)->setCellValue('C5', '总毛重:');
                $obpe->getActiveSheet()->getStyle('C5')->applyFromArray($styleArray);
                //$obpe->setActiveSheetIndex($page)->setCellValue('D5', $shipBatchAttribute['gross_wt']);

                $obpe->setActiveSheetIndex($page)->setCellValue('E5', '总净重:');
                $obpe->getActiveSheet()->getStyle('E5')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->setCellValue('G5', '总件数:');
                $obpe->getActiveSheet()->getStyle('G5')->applyFromArray($styleArray);
                //$obpe->setActiveSheetIndex($page)->setCellValue('H5',$shipBatchAttribute['pack_no']);

                $obpe->setActiveSheetIndex($page)->setCellValue('A6', '备注栏:');
                $obpe->getActiveSheet()->getStyle('A6')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->mergeCells('B6:F6');

                $obpe->setActiveSheetIndex($page)->setCellValue('G6', '拼数:');
                $obpe->getActiveSheet()->getStyle('G6')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H6', '');
                $obpe->getActiveSheet()->getStyle('A1:H6')->applyFromArray($border);

                $obpe->setActiveSheetIndex($page)->setCellValue('A8', '序号');
                $obpe->getActiveSheet()->getStyle('A8')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->setCellValue('B8', '海关备案序号');
                $obpe->getActiveSheet()->getStyle('B8')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->setCellValue('C8', '批次料件号');
                $obpe->getActiveSheet()->getStyle('C8')->applyFromArray($styleArray);

                $obpe->setActiveSheetIndex($page)->setCellValue('D8', '入仓单号料件号');
                $obpe->getActiveSheet()->getStyle('D8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('E8', '商品编码');
                $obpe->getActiveSheet()->getStyle('E8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('F8', '报关品名');
                $obpe->getActiveSheet()->getStyle('F8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('G8', '规格型号');
                $obpe->getActiveSheet()->getStyle('G8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('H8', '申报数量');
                $obpe->getActiveSheet()->getStyle('H8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('I8', '申报单位');
                $obpe->getActiveSheet()->getStyle('I8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('K8', '法定数量');
                $obpe->getActiveSheet()->getStyle('K8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('K8', '法定单位');
                $obpe->getActiveSheet()->getStyle('K8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('L8', '第二数量');
                $obpe->getActiveSheet()->getStyle('L8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('M8', '第二单位');
                $obpe->getActiveSheet()->getStyle('M8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('N8', '单价');
                $obpe->getActiveSheet()->getStyle('N8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('O8', '总价');
                $obpe->getActiveSheet()->getStyle('O8')->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($page)->setCellValue('P8', '申报币制');
                $obpe->getActiveSheet()->getStyle('P8')->applyFromArray($styleArray);

                $index = 1;
                $count_w = 0;//总毛重
                $count_nw = 0;//总净重
                $count_price = 0;
                foreach ($list as $k => $v) {
                    $k = $k + 9;
                    $count_w += $v['cw'];
                    $count_price += $v['declared_value'];
                    //$count_nw+=$v['ncw'];
                    $hsElementCondition = array(
                        'product_id' => $v['product_id']
                    );
                    $hselementMaps = Service_HsElementMap::getByCondition($hsElementCondition, '*');
                    if (!empty($hselementMaps)) {
                        $hsString = array();
                        foreach ($hselementMaps as $khsm => $vhsm) {
                            $hsString[] = $vhsm['hem_detail'];
                        }
                        $hsString = implode('|', $hsString);
                    }
                    //$hum_quantity_law=$v['hum_quantity_law']*$v['quantity'];
                    $obpe->setActiveSheetIndex($page)->setCellValue('A' . $k, $index);
                    $index++;
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('B' . $k, $v['hs_serial_no'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('C' . $k, $v['batch_goods_id'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('D' . $k, $v['goods_id'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('E' . $k, $v['hs_code'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('F' . $k, $v['hs_goods_name']);
                    $obpe->setActiveSheetIndex($page)->setCellValue('G' . $k, empty($hsString) ? '' : $hsString);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('H' . $k, (string)sprintf('%.4f', $v['quantity']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('I' . $k, $v['pu_code']);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('J' . $k, (string)sprintf('%.4f', $v['hum_quantity_law']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('K' . $k, $v['pu_code_law']);
                    $v['hum_quantity_second'] =
                        empty($v['hum_quantity_second']) ?
                            '' : (string)sprintf('%.4f', $v['hum_quantity_second']);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('L' . $k, $v['hum_quantity_second'], PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('M' . $k, $v['pu_code_second']);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('N' . $k, (string)sprintf('%.2f', $v['declared_value'] / $v['quantity']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValueExplicit('O' . $k, sprintf('%.2f', $v['declared_value']), PHPExcel_Cell_DataType::TYPE_STRING);
                    $obpe->setActiveSheetIndex($page)->setCellValue('P' . $k, $v['currency_name']);
                }
                //$obpe->setActiveSheetIndex($page)->setCellValue('D5', $count_w);
                $obpe->setActiveSheetIndex($page)
                    ->setCellValue('B6', '收货人：A-LINK TELECOM  总价：USD  '
                        . sprintf('%.2f', $count_price) .
                        '    总件数:');
                //$obpe->setActiveSheetIndex($page)->setCellValue('D5', $shipBatchAttribute['gross_wt']);
                $totalPrice[$page] = sprintf('%.2f', $count_price);

                $obpe->setActiveSheetIndex($page)->setCellValueExplicit('F5', round($count_w, 4), PHPExcel_Cell_DataType::TYPE_STRING);
                $totalNt += round($count_w, 4);
                $grossWtArr[$page] = round($count_w, 4);
                $obpe->getActiveSheet()->setTitle('第' . ($page + 1) . '单');

            }
            $totalGrossWDivNt = ($shipBatchAttribute['gross_wt'] - $totalNt) / $pages;
            $gwtArr = array();
            $packNoArr = array();
            for ($page = 0; $page < $pages; $page++) {
                $gwt = round($totalGrossWDivNt + $grossWtArr[$page], 4);
                $gwtArr[$page] = $gwt;
                $obpe->setActiveSheetIndex($page)->setCellValue('D5', $gwt);
                $packNo = round($gwt / $shipBatchAttribute['gross_wt'] * $shipBatchAttribute['pack_no']);
                $packNoArr[$page] = $packNo;
                $obpe->setActiveSheetIndex($page)->setCellValue('H5', $packNo);
            }
            $obpe->createSheet();
            $obpe->setActiveSheetIndex($pages);
            $obpe->getActiveSheet()->setTitle('汇总');
            $obpe->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obpe->getActiveSheet()->getColumnDimension('B')->setWidth(14);
            $obpe->getActiveSheet()->getColumnDimension('C')->setWidth(14);
            $obpe->getActiveSheet()->getColumnDimension('D')->setWidth(12);
            $obpe->getActiveSheet()->getColumnDimension('E')->setWidth(14);

            $obpe->setActiveSheetIndex($pages)->setCellValue('A1', '单号');
            $obpe->setActiveSheetIndex($pages)->setCellValue('B1', '件数');
            $obpe->setActiveSheetIndex($pages)->setCellValue('C1', '净重(KG)');
            $obpe->setActiveSheetIndex($pages)->setCellValue('D1', '毛重(KG)');
            $obpe->setActiveSheetIndex($pages)->setCellValue('E1', '价值(USD)');
            $index = 2;
            $allTotalPrice = 0;
            for ($page = 0; $page < $pages; $page++) {
                $obpe->setActiveSheetIndex($pages)->setCellValue('A' . $index, $codeArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('A' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('B' . $index, $packNoArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('B' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('C' . $index, $grossWtArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('C' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('D' . $index, $gwtArr[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('D' . $index)->applyFromArray($styleArray);
                $obpe->setActiveSheetIndex($pages)->setCellValue('E' . $index, $totalPrice[$page]);
                $obpe->setActiveSheetIndex($pages)->getStyle('E' . $index)->applyFromArray($styleArray);
                $allTotalPrice += $totalPrice[$page];
                $index++;
            }
            $obpe->setActiveSheetIndex($pages)->setCellValue('A' . $index, '总计');
            $obpe->setActiveSheetIndex($pages)->setCellValue('B' . $index, $shipBatchAttribute['pack_no']);
            $obpe->setActiveSheetIndex($pages)->setCellValue('C' . $index, $totalNt);
            $obpe->setActiveSheetIndex($pages)->setCellValue('D' . $index, $shipBatchAttribute['gross_wt']);
            $obpe->setActiveSheetIndex($pages)->setCellValue('E' . $index, $allTotalPrice);
            $obpe->setActiveSheetIndex($pages)->getStyle('A1:E' . $index)->applyFromArray($border);


            $obpe->setActiveSheetIndex(0);
            $obwrite = PHPExcel_IOFactory::createWriter($obpe, 'Excel5');
            header('pragma: public');
            header('expires: 0');
            header('accept-ranges: bytes');
            header('cache-control: must-revalidate');
            header('content-type: application/vnd.ms-excel; charset=utf-8');
            header('content-disposition: attachment; filename=' . $fileName . '-invoice.xls');
            $obwrite->save('php://output');
            exit();
        } else {
            $result['ask'] = 0;
            $result['msg'] = '无数据,请检查出区单的监管方式是否是一般贸易';
            die(Zend_Json::encode($result));
        }
    }

}//controller end	