<?php

class Default_IndexController extends Ec_Controller_DefaultAction {

    public $_loginSuccessUrl = '/';
    public $_authCode = 0; //是否用验证码

    public function preDispatch() {
        $this->view->authCode = $this->_authCode;
        $this->view->errMsg = '';
        $this->tplDirectory = "default/views/default/";
    }

    public function indexAction() {
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        if ($userAuth->userId && $userAuth->isLogin) {
            echo Ec::renderTpl($this->tplDirectory . "index.tpl", "systemLayout");
            exit();
        }
        $this->view->errMsg = '';
        echo $this->view->render($this->tplDirectory . 'login.tpl');
    }

    public function loginAction() {
        $errMsg = '';
        if ($this->_request->isPost()) {
            setcookie('currentPage', '', -1, '/');
            $param['userName'] = $this->_request->getParam('userName', '');
            $param['userPass'] = $this->_request->getParam('userPass', '');
            $param['authCode'] = $this->_request->getParam('authCode', '');
            $param['warehouse_id'] = $this->_request->getParam('warehouse', '');
            $param['valid'] = $this->_authCode;
            $result = Service_User::login($param);
            if (isset($result['state']) && $result['state'] == '1') {
                $this->_redirect($this->_loginSuccessUrl);
            } else {
                $errMsg = isset($result['message']) ? $result['message'] : '';
            }
        }
        $warehouse = Common_DataCache::getWarehouse();
        $viewWarehouse = [];
        if(!empty($warehouse)){
            foreach ($warehouse as $k=>$w){
                if($w['warehouse_status']=='1'){
                    $viewWarehouse[$w['warehouse_code']]=$w['warehouse_desc'];
                }

            }
        }
        $hostName = $this->_request->getHttpHost();
        $this->view->warehouses = $warehouse;
        $this->view->errMsg = $errMsg;
        echo $this->view->render($this->tplDirectory . 'login.tpl');
    }

    public function logoutAction() {
        $session = new Zend_Session_Namespace('userAuthorization');
        $session->unsetAll();
        session_destroy();
        $errMsg = '';
        setcookie('currentPage', '', -1, '/');
        $warehouse = Common_DataCache::getWarehouseSimple();
        $this->view->warehouses = $warehouse;
        $this->view->errMsg = $errMsg;
        echo $this->view->render($this->tplDirectory . 'login.tpl');
    }

    /**
     * @todo code128
     */
    public function barcodeAction() {
        $option = array();

        if (NULL !== $this->_request->getParam('height', NULL)) {
            $option['height'] = $this->_request->getParam('height');
        }

        if (NULL !== $this->_request->getParam('width', NULL)) {
            $option['width'] = $this->_request->getParam('width');
        }

        if (NULL !== $this->_request->getParam('show', NULL)) {
            $option['show'] = (bool) $this->_request->getParam('show');
        }

        if (NULL !== $this->_request->getParam('type', NULL)) {
            $option['type'] = $this->_request->getParam('type');
        }
        if (NULL !== $this->_request->getParam('codeType', NULL)) {
            $option['codeType'] = $this->_request->getParam('codeType');
        }
        if (!empty($option)) {
            Common_Barcode::render($this->_request->code, $option);
        }
        else {
            Common_Barcode::barcode($this->_request->code);
        }
        //$drawText = $this->_request->getParam('drawText', '1');
        //Common_Barcode::barcode($this->_request->code, 'code128', $drawText);
        exit;
    }

    public function barcode39Action() {
        Common_Barcode::barcode($this->_request->code, 'code39');
        exit;
    }

    public function verifyCodeAction() {
        $verifyCode = new Common_Verifycode();
        $verifyCode->set_sess_name('AdminVerifyCode');
        echo $verifyCode->render();
    }

    public function printBarcodeAction() {
        $condition = array(
            'barcode' => $this->_request->getParam('barcode', ""),
            "type" => $this->_request->getParam('type', ""),
            "height" => $this->_request->getParam('height', ""),
            "width" => $this->_request->getParam('width', ""),
            "quality" => $this->_request->getParam('quality', ""),
            "format" => $this->_request->getParam('format', ""),
            "text" => $this->_request->getParam('text', "")
        );
        Common_Barcode::outImage($condition);
    }

    /**
     * @author william-fan
     * @todo 签名
     */
    public function signatureAction() {
        /* echo APPLICATION_PATH;
          exit; */
        $ttfPath = APPLICATION_PATH . '/../data/font/english111 .ttf';
        $name = $this->_request->getParam('name', '');
        Header("Content-type: image/gif");
        $im = imagecreate(150, 20);
        $black = ImageColorAllocate($im, 255, 255, 255);
        $white = ImageColorAllocate($im, 0, 0, 0);
        imagettftext($im, 20, 0, 10, 20, $white, $ttfPath, $name);
        ImageGif($im);
        ImageDestroy($im);
    }
    
     /**
   * 打印配货单，用于打包贴标、单票打包、单据打印自动打印
   */
  public function printPeihuoAction() {
    $errorArr = $result = array();
    $pickCodes = $this->_request->getParam('pickCodes');
    $ordrCode = $this->_request->getParam('orderCode', '');
    $orderCodeStr = $this->_request->getParam('orderCodeStr', '');
    $orderCodeArr = explode(',', $orderCodeStr);

    if('' != $ordrCode){
      $orderCodeArr = array($ordrCode);
    }

    foreach($orderCodeArr as $k => $v){
      if(empty($v)) {
        unset($orderCodeArr[$k]);
      }
    }

    foreach ($pickCodes as $pickCode) {
        $tpl = "print_picking.tpl";
        $pickRow = Service_Picking::getByField($pickCode,"picking_code",array('picking_model'));
        if($pickRow['picking_model']=="1"){
            $tpl = "print_picking_sw.tpl";
        }
        $return = Service_PickProcess::getPacking($pickCode , TRUE);
        if ($return['state'] == '1') {
            if($ordrCode != ''){
                $orders =   array();
                foreach ($return['data']['orders'] as $key => $order) {
                    if($order['order_code'] == $ordrCode && in_array($ordrCode , $orderCodeArr)){
                        $orders[$key] = $order;
                    }
                }
                if(empty($orders)){
                    $errorArr = '订单号或服务商单号不存在';
                }
                $return['data']['orders']   =   $orders;
            }
            $result[] = $return['data'];
        } else {
            $errorArr = $return['message'];
        }
    }
    $this->view->error = $errorArr;
    $this->view->result = $result;
    echo Ec::renderTpl('shipment/views/pickup/'.$tpl, 'layout');
  }

    public function printOrderAction() {
        $code = trim($this->_request->getParam('code', ''));
        $result = Service_PackProcess::getOrderInfo($code);
        /* echo "<pre>";
          print_r($result);
          echo "</pre>"; */
        if ($result['state'] != '1') {
            die($result['message']);
        }
        $smCode = $result['data']['order']['sm_code'];
        $codetype = $this->_request->getParam('codeType', 'code128');
        $byurl = $this->_request->getParam('byurl', '0'); //默认自动打印
        if ($codetype == 'code39') {
            $action = 'barcode39';
        } elseif ($codetype == 'code128') {
            $action = 'barcode';
        } else {
            $action = 'barcode';
        }
        //print_r($smCode);
        if (strlen($smCode) > 2) {
            switch (strtoupper($smCode)) {
                case "HKEMS":
                case "BH-MMP1":
                case "BH-MMP":
                case "SWPT":
                    $smCode = 'sw';
                    break;
                case "CJ-DGMG":
                    //德国邮政小包挂号
                    $smCode = 'dem-p';
                    break;
                case "CJ-DGMP":
                    //德国邮政小包平邮
                    $smCode = 'dem';
                    break;
                case "BH-DGMG":
                    $smCode = 'bh-dgmg';
                    break;
                case "SZY-EMS":
                case 'WG-EMS':
                    $city = $result['data']['address']['oab_city'];
                    $state = $result['data']['address']['oab_state'];
                    $stateAddcity = $city . " " . $state;
                    if (strlen($stateAddcity) > 26) {
                        $scArray = explode(" ", $stateAddcity);
                        $strlength = 0;
                        $brkey = 0;
                        $scStr = "";
                        for ($i = 0; $i < count($scArray); $i++) {
                            $strlength+=strlen($scArray[$i]);
                            $brkey = $i;
                            if ($strlength > 21)
                                break;
                        }
                        for ($j = 0; $j < count($scArray); $j++) {
                            if ($j == $brkey - 1) {
                                $scStr.=$scArray[$j] . "<br>";
                            } else {
                                $scStr.=$scArray[$j] . " ";
                            }
                        }
                        $result['data']['address']['cityAddstate'] = $scStr;
                    } else {
                        $result['data']['address']['cityAddstate'] = $stateAddcity;
                    }
                    $address = $result['data']['address']['oab_street_address1'];
                    $breakAddress1 = "";
                    $breakAddress2 = "";
                    if ($result['data']['address']['oab_street_address2'] != "") {
                        $address.=" " . $result['data']['address']['oab_street_address2'];
                    }
                    if (strlen($address) > 36) {
                        $addressArray = explode(" ", $address);
                        $length = 0;
                        for ($i = 0; $i < count($addressArray); $i++) {
                            $length+=strlen($addressArray[$i]);
                            if ($length > 36) {
                                $breakAddress2.= $addressArray[$i] . " ";
                            } else {
                                $breakAddress1.= $addressArray[$i] . " ";
                            }
                        }
                    } else {
                        $breakAddress1 = $address;
                    }
                    $result['data']['address']['breakAddress1'] = $breakAddress1;
                    $result['data']['address']['breakAddress2'] = $breakAddress2;
                    $smCode = 'SZY-EMS';
                    break;
                case "BH-SGG":
                case "BH-SGP":
                    $smCode = 'sg';
                    break;
                case 'BH-MPPG':
                    $smCode = 'bh-mppg';
                    break;
                case "HKPG":
                    $smCode = 'hkpg';
                    break;
                case "HKPP":
                    $smCode = 'hkpp';
                    $checkpack = new Service_ChangePack();
                    $packNo = $checkpack->getPackNo($result['data']['address']['country']['country_code'], $result['data']['address']['oab_postcode']);
                    $this->view->packNo = $packNo;
                    break;
                case 'PNLG': // 荷兰小包挂号
                case 'PNLP': // 荷兰小包平邮
                case 'PNLN': // 荷兰小包平邮-HF
                    $smCode = 'pnlg';
                    $currency = Service_Currency::getByField('EUR', 'currency_code');

                    foreach ($result['data']['orderProduct'] as $k => $v) {
                        // 把美元报价改为欧元
                        $revertToEur = Service_Currency::converByCode('USD', 'EUR', $v['op_purpose_declared_value']);
                        // 获取相应产品海关编码
                        $hs_code = Service_Product::getByField($v['product_id']);
                        $result['data']['orderProduct'][$k]['op_purpose_declared_value'] = $revertToEur;
                        $result['data']['orderProduct'][$k]['hs_code'] = $hs_code ? $hs_code['hs_code'] : '';
                    }

                    $this->view->currency_symbol = $currency ? $currency['currency_symbol_left'] : '';
                    $this->view->data = $result['data'];
                    break;
                case 'SF-RUPR':
                $smCode='SF-RUPR';
                break;
                case 'RUMALL-RU-EP':
                       $orderProducts = Service_OrderProduct::getByCondition(array('order_id'=>$result['data']['order']['order_id']));
                     if(!empty($orderProducts)){
                         $op=array();
                            foreach ($orderProducts as $keyp=>$product){
                                    $productSku = Service_Product::getByField($product['product_id']);
                                    $product['product_weight'] = $productSku['product_weight'];
                                    $product['total_weight']=floatval($productSku['product_weight']*$product['op_quantity']);
                           $product['total_op_declared']=floatval($product['op_purpose_declared_value']*$product['op_quantity']);
                           $op[]=$product;
                                if($keyp==4){
                                    break;
                                }
                        }
                        $result['data']['orderProduct']=$op;
                     }
                    $smCode='rumal-ru-ep';
                break;
              case 'RUMALL-RU-G':
                     $orderProducts = Service_OrderProduct::getByCondition(array('order_id'=>$result['data']['order']['order_id']));
                     if(!empty($orderProducts)){
                         $op=array();
                            foreach ($orderProducts as $keyp=>$product){
                                    $productSku = Service_Product::getByField($product['product_id']);
                                    $product['product_weight'] = $productSku['product_weight'];
                                     $product['total_weight']=floatval($productSku['product_weight']*$product['op_quantity']);
                           $product['total_op_declared']=floatval($product['op_purpose_declared_value']*$product['op_quantity']);
                           $op[]=$product;
                                if($keyp==4){
                                    break;
                                }
                        }
                        $result['data']['orderProduct']=$op;
                     }
                    $smCode='rumal-ru-g';
                break;
                case 'SF-RUPT':
                $smCode='SF-RUPT';
                break;
                case 'DHL-PDUK':
                    $smCode="DHL-PDUK";
                    break;
                case 'TWPG':
                case 'TWPP':
                    $result['data']['order']['change_code']=  Service_HjtwApi::getCode($result['data']['address']['oab_country_id'],$result['data']['address']['oab_postcode'],$smCode);
                    if(empty($result['data']['order']['print_no'])){
                          $printNo=Service_OrderProcess::getPrintNo();
                           $result['data']['order']['print_no']=$printNo;
                            $updateOrder=array(
                                'print_no'=>$printNo
                            );
                          Service_Orders::update($updateOrder,$result['data']['order']['order_id']);
                    }else{
                          $checkResult=Service_OrderProcess::checkPrintNo($result['data']['order']['print_no']);
                          if($checkResult==FALSE){
                                $printNo=Service_OrderProcess::getPrintNo();
                               $result['data']['order']['print_no']=$printNo;
                                $updateOrder=array(
                                    'print_no'=>$printNo
                                );
                              Service_Orders::update($updateOrder,$result['data']['order']['order_id']);
                          }
                    }
                    break;
                case  '4PX-SINGAPO_SPACK_IMAIR':
                case  '4PX-OZXBTH':   
                    $condition=array(
                        'country_id'=>$result['data']['address']['oab_country_id'],
                        // 'sm_code'=>'4PX-Singapo_SPack_IMAIR',
                        'sm_code'=>strtoupper($smCode),
                        );
                    $picupArea=  Service_SmCountryPickcode::getByCondition($condition,'*',0,1,'post_code_end desc');
                    if(!empty($picupArea)){
                        foreach($picupArea as $area){
                            if(is_numeric($area['post_code_start'])&&!empty($area['post_code_end']) && !empty($result['data']['address']['oab_postcode'])){
                                //add by @Felix 1182
                                $postCodeLen = strlen($area['post_code_end']);
                                if(strlen($result['data']['address']['oab_postcode']) >= $postCodeLen ){ 
                                    $tmpPostcode = substr($result['data']['address']['oab_postcode'],0,$postCodeLen);
                                }else{ 
                                    $format = '%0'.$postCodeLen.'s';
                                    $tmpPostcode = sprintf($format, $result['data']['address']['oab_postcode']);
                                }
                                
                                if((int)$tmpPostcode>=(int)$area['post_code_start']
                                  &&(int)$tmpPostcode<=(int)$area['post_code_end']){
                                    break;
                                }
                            }
                        }
                    }
                    
                    $result['data']['pick_up']=array(
                        'pick_code'=>$area['pick_code'],
                        'number_area'=>$area['area']
                    );
                    
                   if($smCode == '4PX-OZXBTH'){
                        $smCode='4PXOZXBTH';
                   }else{
                        $smCode='4PXIMAILR';
                   }

                    break;
                case 'ALBP-G':
                case 'BH-BPG':
                    $smCode='ALBP-GH';
                    break;
                case 'BH-BPP':
                case 'ALBP-P':
                    $smCode='ALBP';
                    break;
                case 'ALBP-EU':
                    $smCode='ALBP-EU';
                    break;
                case 'BH-BPEU':
                    $smCode='ALBP-EU';
                    break;
                case 'BH-DHL-HKDELIVERY':
                    $smCode='BH-DHL-HKDELIVERY';
                    break;
				case 'BH-AZAT-G':
                    $smCode="BH-AZAT-G";
                    break;
				case 'BH-POST-NL':
				    if($result['data']['address']['country']['country_code'] == 'NL'){
				        $smCode = 'BH-POST-NL';
				    }else{
				        $smCode = 'BH-POST-NNL';
				    }
				    break;
				case 'BH-NLPOST-TH':
				    $smCode = 'BH-NLPOST-TH';
				    $filePath = APPLICATION_PATH . '/../data/file/BH-NLPOST-TH-PICKCODES.xlsx';
				    $fileData = Common_Upload::readEXCEL($filePath);
				    $res      = 0;
				    foreach ($fileData as $k => $v) {
				        if ($k == 0) {
				            continue;
				        }
				        $str = strpos(strtolower($result['data']['address']['country']['country_code']), strtolower($v[0]));
				        if (is_numeric($str)) {
				            $res = 1;
				            $pick_code = $v[3];
				            break;
				        }
				    }
				    if ($res) {
				        $pick_code = $pick_code ? $pick_code : '';
				        $result['data']['pick_up']=array(
				            'pick_code'=>$pick_code,
				        );
				    }
				    break;
                default:
                    $smCode = 'F4';
            }
            /* if(strtoupper($smCode)=='HKEMS'||strtoupper($smCode)=='BH-MMP'||strtoupper($smCode)=='SWPT'){
              $smCode='sw';
              }else{
              $smCode='F4';
              } */
        }
        //$smCode = 'dem';
        //$smCode = 'dem-p';
        //echo $smCode;
        $this->view->data = $result['data'];
        $this->view->action = $action;
        $this->view->byurl = $byurl;
        $this->view->nowTime = date("Y-m-d");
        $this->view->nowTime2 = date("Y-m-d H:i:s");
        echo Ec::renderTpl("shipment/views/template/" . $smCode . ".tpl", 'layout');
    }

    /**
     * @desc 打印货架条码
     */
    public function printShelfAction() {
        $orderlist = isset($_POST['orderlist']) ? $_POST['orderlist'] : '';
        if (!$orderlist) {
            echo '<html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"></head><body>';
            echo '注：将单号复制到输入框中，每个单号以换行区分；<br>格式：A4 * 5<form action="" method="post">
                <textarea rows="36" cols="70" name="orderlist"></textarea>
                <input type="submit" name="submit" value="submit">
            </form>';
            echo '</body></html>';
        } else {
            $orderlist = $_POST['orderlist'];
            $orderlist = preg_split('/\r\n/', $orderlist, -1, PREG_SPLIT_NO_EMPTY);
            // print_r($orderlist);die;
            $result = array_chunk($orderlist, 2);
            $this->view->results = $result;
            echo $this->view->render($this->tplDirectory . 'print_thermal_9X8.5x2.tpl');
        }
    }

    /* 客人LOGO */

    public function viewLogoImageAction() {
        $customerCode = $this->_request->getParam('customerCode', "");
        if (empty($customerCode)) {
            exit;
        }
        $customer_array = Service_Customer::getByField($customerCode, 'customer_code');
        $fileName = $customer_array['customer_logo'];
        $path = APPLICATION_PATH . "/../data/images/register/" . $customerCode . '/' . $fileName;
        //echo $path;exit;
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);
        } else {
            //header("Location: /images/noimg.jpg");
        }

        exit();
    }

    /* 上传图片查看 */

    public function viewUploadImageAction() {
        $fileName = $this->_request->getParam('fileName', "");
        $customerCode = $this->_request->getParam('customerCode', "");
        $path = APPLICATION_PATH . "/../data/images/register/" . $customerCode . '/' . $fileName;

        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);
        } else {
            header("Location: /images/noimg.jpg");
        }

        exit();
    }

    /**
     * @author william-fan
     * @todo 用于获取hkdhl打印的文档
     */
    public function printAction() {
        $path = $this->_request->getParam('path', '');
        //$filename="E:/wamp/www/chukouwms/public/images/2143826683/epl2";        
        $decodePath = base64_decode($path);       
        /* echo $decodePath;
          exit; */
        $str = '';
        if ($decodePath == '' || !file_exists($decodePath)) {
            $str = '文件不存在';
            die($str);
        }

        /* header('Content-type: application/pdf');
          $fname = 'aaa';
          header('filename='.$fname);
          //readfile($filename); */
        $str = file_get_contents($decodePath);
        //$str = base64_decode($str);
        //echo $str;
        if (!empty($str)) {
            echo $str;
            exit;
        } else {
            $str = '打印内容为空';
            die($str);
        }
    }

    public function taxRebateImageAction() {
        $trId = $this->_request->getParam("tr_id", "");
        //$fileName = $this->_request->getParam('fileName',"");
        //$customerCode = $this->_request->getParam('customerCode', "");
        $trRow = Service_TaxRebate::getByField($trId, 'tr_id', "*");
        $path = APPLICATION_PATH . '/../data/images/taxrebate/' . $trRow['customer_code'] . "/" . $trRow['filename'];
        if (empty($trRow) || $trRow['filename'] == "") {
            header("Location: /images/noimg.jpg");
            exit();
        }
        if (file_exists($path)) {
            header('Content-Type: image/jpeg');
            echo file_get_contents($path);
        } else {
            header("Location: /images/noimg.jpg");
        }
        exit();
    }

    public function downloadTaxImageAction() {
        $trId = $this->_request->getParam("tr_id", "");
        $trRow = Service_TaxRebate::getByField($trId, 'tr_id', "*");
        //方法2
        $fullPath = APPLICATION_PATH . '/../data/images/taxrebate/' . $trRow['customer_code'] . "/" . $trRow['filename'];

        if (empty($trRow) || $trRow['filename'] == "") {
            header('Content-Type: image/jpeg');
            header("Location: /images/noimg.jpg");
            //header($header );
            exit;
        }
        if (!file_exists($fullPath)) {
            $noimageFile = APPLICATION_PATH . '/../data/images/taxrebate/noimg.jpg';
            header('Content-Type: image/jpeg');
            header("Content-Disposition: attachment; filename=noimg.jpg");
            echo file_get_contents($noimageFile);
            exit;
        }
        $fileArray = explode(".", $trRow['filename']);

        if ($fileArray[1] == "pdf") {
            header('Content-Type: application/pdf; charset=utf-8');
            header("Content-Disposition:attachment; filename=" . $trRow['taxrebate_code'] . ".pdf");
            echo file_get_contents($fullPath);
            exit;
        } else {
            header('Content-Type: image/' . $fileArray[1]);
            //Force the download
            $header = "Content-Disposition: attachment; filename=" . $trRow['taxrebate_code'] . "." . $fileArray[1];
            header($header);
            // 	header("Content-Transfer-Encoding: binary");
            // 	header("Content-Length: ".$len);
            echo file_get_contents($fullPath);
            exit;
        }
    }

    /* 提供给网站用的轨迹查询 colin */

    public function getTrackingAction() {
        $return = array('ask' => 0,
            'message' => '',
            'detail' => '',
            'tracking_number' => '',
            'is_found' => '0');


        $tracking_number = trim($this->_request->getParam("tracking_number", ""));
        if (empty($tracking_number)) {
            $return['message'] = "没有提供运单号";
            die(Zend_Json::encode($return));
        }
        $return['tracking_number'] = $tracking_number;
        $orderInfo = Service_Orders::getByCondition(array("reference_no" => $tracking_number, 'order_status_neq' => 0), 'order_code', 1, 1);
        $tracings = Service_ShipOrderTracking::getByCondition(array('order_code' => $orderInfo[0]['order_code']), "*", '', '', 'sot_add_time DESC');
        //$tracings = Service_ShipOrderTracking::getByCondition(array('tracking_number'=>trim($tracking_number)));	
        if (empty($tracings)) {
            $return['is_found'] = '0';
            $return['message'] = '找不到数据';
        } else {
            $return['ask'] = '1';
            $return['is_found'] = '1';
            $return['message'] = '找到数据';
            $return['detail'] = $tracings;
        }
        die(Zend_Json::encode($return));
    }

    /* 提供给网站用的费用查询 colin */

    public function getFeeSearchAction() {
        $return = array('ask' => 0,
            'message' => '',
            'detail' => '',
            'tracking_number' => '',
            'is_found' => '0'
        );
        $country_code = trim($this->_request->getParam("country_code", ""));
        $goods_weight = trim($this->_request->getParam("goods_weight", ""));
        $goods_length = trim($this->_request->getParam("goods_length", 0));
        $goods_width = trim($this->_request->getParam("goods_width", 0));
        $goods_heigth = trim($this->_request->getParam("goods_heigth", 0));
        if (empty($country_code)) {
            $return['message'] = "没有提供目的地国家代码";
            die(Zend_Json::encode($return));
        }
        $condition = array();
        $condition['warehouse_id'] = 1;
        $condition['country_code'] = $country_code;
        $condition['sm_status'] = '1';
        $condition['sm_channel'] = '0';
        $smcountrymapListTemp = Service_SmCountryMap::getJoinCountryByCondition($condition, 'smcm_id');
        foreach ($smcountrymapListTemp as $smcountryRow) {
            $objCalculate = new Common_CalculateShipping();
            $keys = array(
                'warehouseId' => $smcountryRow['warehouse_id'],
                'countryId' => $smcountryRow['country_id'],
                'smCode' => $smcountryRow['sm_code'],
                'weight' => $goods_weight,
                'length' => $goods_length,
                'width' => $goods_width,
                'height' => $goods_heigth,
            );
            $objCalculate->setParams($keys);
            $result = $objCalculate->getRate();

            if ($result['state'] == 1) {
                $fee = $result['data']['cost']['price'];
                $smcountryRow['base_fee'] = $fee;
                $smcountryRow['ex_fee'] = $smcountryRow['base_fee'] * $smcountryRow['sm_baf'];
                $smcountryRow['total_fee'] = $result['data']['cost']['totalCost'];
                $smcountryRow['currency_code'] = $result['data']['cost']['currency_code'];

                $currency = Service_Currency::getByField($smcountryRow['currency_code'], 'currency_code');
                if ($currency) {
                    $smcountryRow['base_fee'] = $smcountryRow['base_fee'] * $currency['currency_rate'];
                    $smcountryRow['ex_fee'] = $smcountryRow['ex_fee'] * $currency['currency_rate'];
                    $smcountryRow['total_fee'] = $smcountryRow['total_fee'] * $currency['currency_rate'];
                }
                $smcountrymapList[] = $smcountryRow;
            }
        }
        if (empty($smcountrymapList)) {
            $return['is_found'] = '0';
            $return['message'] = '找不到数据';
        } else {
            $return['ask'] = '1';
            $return['is_found'] = '1';
            $return['message'] = '找到数据';
            $return['detail'] = $smcountrymapList;
        }
        die(Zend_Json::encode($return));
    }
    
    public function viewImagesAction() {
        $path = $this->_request->getParam('path', '');  
        $type = $this->_request->getParam('type' , 'png');
        $decodePath = base64_decode($path);       
        if ($decodePath == '' || !file_exists($decodePath)) {
            $str = '文件不存在';
            die($str);
        }
        $str = file_get_contents($decodePath);
        if (!empty($str)) {
            header("Content-Type:image/{$type}");
            echo $str;
            exit;
        } else {
            $str = "图片内容为空";
            die($str);
        }
    }

    //PDA登陆
    public function pdaIndexAction() {
        $userAuth = new Zend_Session_Namespace('userAuthorization');
        
        if ($userAuth->userId && $userAuth->isLogin && isset($userAuth->padLogin) && $userAuth->padLogin) {
            $this->_redirect("/pda/pda/index");
            exit();
        }
        $errMsg   =   '';
        if($this->_request->isPost()){
            $param  =   array();
            $param['userName'] = $this->_request->getParam('user_account', '');
            $param['userPass'] = $this->_request->getParam('user_password', '');
            $result = Service_User::padLogin($param);
        
            if (isset($result['state']) && $result['state'] == '1') {
                $this->_redirect("/pda/pda/index");
            } else {
                $errMsg = isset($result['message']) ? $result['message'] : '';
            }
        }       
        $this->view->errMsg = $errMsg;
        echo $this->view->render($this->tplDirectory . 'pda-login.tpl');
    }

    public function printPickingAction(){
        $pickCodes = $this->_request->getParam('pickCode');
        $pickType = $this->_request->getParam('pickType', '');
        $offset = $this->_request->getParam("offset","1");
        $pickCodeArr = explode(",",$pickCodes);
        $return = array();
        if ($pickType == 'more') {
            $tpl = "print_picking.tpl";
            foreach($pickCodeArr as $pickCode){
                if($pickCode=="") continue;
                $result = Service_PickProcess::getPacking($pickCode);
                $result['data']['offset'] = $offset;
                if ($result['state'] == '1') {
                    $return[] = $result['data'];
                } else {
                    $errorArr = $result['message'];
                }
            }
        } else {
            $tpl = "print_down_goods_shelves.tpl";
            $result = $return = array();
            //$indexNo = 1;
            foreach($pickCodeArr as $pickCode){
                if($pickCode=="") continue;
                $pickingRow = Service_Picking::getByField($pickCode,'picking_code',"*");
                $pdObj = new Service_PickingDetail();
                $orderPickProduct = $pdObj->getLeftJoinOrderProductByCondition(array('picking_id' => $pickingRow['picking_id']), '*', 0, 0, array('lc_code','order_product.order_code'));
                $orders = $tmpShelf = array();
                $order['page'] = 0;
                $shelfTotal = 0;
                $category = Common_DataCache::getProductCategory();
                $orderCodeArr = array();
                $keyArray = array();
                $orderIndex = 1;
                foreach ($orderPickProduct as $k => $v) {
                    if(!in_array($v['order_code'],$orderCodeArr)){
                        $keyArray[$v['order_code']] = $orderIndex;
                        $orderIndex+=1;
                        $orderCodeArr[] = $v['order_code'];
                    }
                    if (!in_array($v['lc_code'], $tmpShelf)) {
                        $tmpShelf[] = $v['lc_code'];
                    }
                    $order['products'][$v['order_code'] . '_' . $v['lc_code'].'_'.$v['product_id']] = array(
                        'orderIndex'=>$keyArray[$v['order_code']],
                        'order_code'=> $v['order_code'],
                        'product_id' => $v['product_id'],
                        'pd_quantity' => $v['pd_quantity'],
                        'lc_code' => $v['lc_code'],
                        'product_barcode' => $v['product_barcode'],
                        'product_title' => $v['product_title'],
                        'category' => isset($category[$v['pc_id']]['pc_name'])?$category[$v['pc_id']]['pc_name']:''
                    );
                }
                $shelfTotal = count($tmpShelf);
                $chunk = array_chunk($order['products'], 9);

                $i = 1;
                foreach ($chunk as $k => $v) {
                    $order['products'] = $v;
                    $order['page'] = $i++;
                    $order['indexNo'] = $offset; //$indexNo;
                    $orders[$pickingRow['picking_id'] . '_' . $k . '_' . $order['page']] = $order;
                }

                $pickerName = '';
                if ($pickingRow['picker_id'] != '0' && $pickingRow['picker_id'] != '') {
                    $userRow = Service_User::getByField($pickingRow['picker_id'], 'user_id');
                    $pickerName = $userRow['user_name'];
                }

                unset($order);
                if (!empty($orders)) {
                    $result['state'] = 1;
                    $result['data'] = array(
                        'total' => $shelfTotal,
                        'pageTotal' => count($orders),
                        'picking_code' => $pickCode,
                        'pickerName' => $pickerName,
                        'date' => date('Y-m-d'),
                        'products' => $orders,
                    );
                }
                $return[] = $result['data'] ;
                //$indexNo++;
            }

            /*$return = Service_PickProcess::downGoodsShelves($pickCode);
            if ($return['state'] == '1') {
                $result[] = $return['data'];
            } else {
                $errorArr = $return['message'];
            }*/
        }
        //echo "<pre>";
        //var_dump($return);
        //echo "</pre>";
        $this->view->error = $errorArr;
        $this->view->result = $return;
        echo Ec::renderTpl($this->tplDirectory . $tpl, 'layout');
    }
    
    public function viewUspsBarcode128Action() {   
        $orderCode = $this->_request->getParam('code', '');      
        $usps   =   new Service_UspsInterface();        
        try {
            $usps->buildLabelBarcode($orderCode);            
        } catch (Exception $exc) {
            echo $exc->getMessage();
        }      
        
    }

    public function printUspsAction(){
        // $orderCode='SOEC0010001422';
        $orderCode = $this->_request->getParam('code', '');
        #订单
        $order = Service_Orders::getByField($orderCode,'order_code',"*");  
        $shippingMethod =   Service_ShippingMethod::getByField($order['sm_code'] , 'sm_code' , 'sm_name_cn');
        #订单收货地址
        $orderReceiveAddressRows = Service_OrderAddressBook::getByCondition(array('order_code'=>$orderCode,'oab_type'=>'0'),"*");
        $orderReceiveAddress = $orderReceiveAddressRows[0];
        unset($orderReceiveAddressRows);       
        if($orderReceiveAddress['oab_street_address2']!=""){
            $orderReceiveAddress['oab_street_address1'] = $orderReceiveAddress['oab_street_address1']." ".$orderReceiveAddress['oab_street_address2'];
        }       
        $country = Service_Country::getByField($orderReceiveAddress['oab_country_id'] , 'country_id' ,array('country_code','country_name_en'));
        $orderOperationTime =   Service_OrderOperationTime::getByField($orderCode , 'order_code' ,'pack_time');
        $this->view->order = $order;
        $this->view->shippingMethod = $shippingMethod;
        $this->view->orderAddress = $orderReceiveAddress;
        $this->view->country = $country;
        $this->view->packTime   =   $orderOperationTime['pack_time'];
		$countryCodeArr = array('AT','BE','BG','HR','DK','EE','FI','FR','DE','GR','HU','IE','IT','LV','LT','LU','NL','PL','PT','RO','SK','SI','ES','SE','GB','CZ');
        $usEastPost = array(
            '0'=>array('start'=>'00500','end'=>'00599'),
            '1'=>array('start'=>'01000','end'=>'08999'),
            '2'=>array('start'=>10000,'end'=>21299),
            '3'=>array('start'=>21400,'end'=>26899),
            '4'=>array('start'=>27000,'end'=>33999),
            '5'=>array('start'=>34100,'end'=>34299),
            '6'=>array('start'=>34400,'end'=>34499),
            '7'=>array('start'=>34600,'end'=>34799),
            '8'=>array('start'=>34900,'end'=>35299),
            '9'=>array('start'=>35400,'end'=>41899),
            '10'=>array('start'=>42000,'end'=>42799),
            '11'=>array('start'=>43000,'end'=>51699),
            '12'=>array('start'=>52000,'end'=>52899),
            '13'=>array('start'=>53000,'end'=>53299),
            '14'=>array('start'=>53400,'end'=>53599),
            '15'=>array('start'=>53700,'end'=>55199),
            '16'=>array('start'=>55300,'end'=>56799),
            '17'=>array('start'=>57000,'end'=>57799),
            '18'=>array('start'=>58000,'end'=>58899),
            '19'=>array('start'=>60000,'end'=>62099),
            '20'=>array('start'=>62200,'end'=>63199),
            '21'=>array('start'=>63300,'end'=>64199),
            '22'=>array('start'=>64400,'end'=>65899),
            '23'=>array('start'=>66000,'end'=>66299),
            '24'=>array('start'=>66400,'end'=>67699),
            '25'=>array('start'=>67701,'end'=>67701),
            '26'=>array('start'=>67800,'end'=>67899),
            '27'=>array('start'=>67901,'end'=>67901),
            '28'=>array('start'=>67905,'end'=>67905),
            '29'=>array('start'=>68000,'end'=>68199),
            '30'=>array('start'=>68300,'end'=>68999),
            '31'=>array('start'=>69001,'end'=>69001),
            '32'=>array('start'=>69101,'end'=>69101),
            '33'=>array('start'=>69130,'end'=>69130),
            '34'=>array('start'=>69132,'end'=>69132),
            '35'=>array('start'=>69153,'end'=>69153),
            '36'=>array('start'=>69160,'end'=>69160),
            '37'=>array('start'=>69162,'end'=>69162),
            '38'=>array('start'=>69171,'end'=>69171),
            '39'=>array('start'=>69301,'end'=>69301),
            '40'=>array('start'=>69341,'end'=>69341),
            '41'=>array('start'=>69361,'end'=>69361),
            '42'=>array('start'=>69363,'end'=>69363),
            '43'=>array('start'=>72300,'end'=>72334),
            '44'=>array('start'=>72337,'end'=>72395),
            '45'=>array('start'=>72397,'end'=>72499),
            '46'=>array('start'=>72601,'end'=>72602)
        );
        $usWestPost = array(
            '0'=>array('start'=>59000,'end'=>59999),
            '1'=>array('start'=>67700,'end'=>67700),
            '2'=>array('start'=>67702,'end'=>67799),
            '3'=>array('start'=>67900,'end'=>67900),
            '4'=>array('start'=>67902,'end'=>67904),
            '5'=>array('start'=>67906,'end'=>67999),
            '6'=>array('start'=>69000,'end'=>69000),
            '7'=>array('start'=>69002,'end'=>69100),
            '8'=>array('start'=>69102,'end'=>69129),
            '9'=>array('start'=>69131,'end'=>69131),
            '10'=>array('start'=>69133,'end'=>69152),
            '11'=>array('start'=>69154,'end'=>69159),
            '12'=>array('start'=>69161,'end'=>69161),
            '13'=>array('start'=>69163,'end'=>69170),
            '14'=>array('start'=>69172,'end'=>69300),
            '15'=>array('start'=>69302,'end'=>69340),
            '16'=>array('start'=>69342,'end'=>69360),
            '17'=>array('start'=>69362,'end'=>69362),
            '18'=>array('start'=>69364,'end'=>69399),
            '19'=>array('start'=>70000,'end'=>70199),
            '20'=>array('start'=>70300,'end'=>70899),
            '21'=>array('start'=>71000,'end'=>71499),
            '22'=>array('start'=>71600,'end'=>72299),
            '23'=>array('start'=>72335,'end'=>72336),
            '24'=>array('start'=>72396,'end'=>72396),
            '25'=>array('start'=>72500,'end'=>72600),
            '26'=>array('start'=>72603,'end'=>73199),
            '27'=>array('start'=>73300,'end'=>74199),
            '28'=>array('start'=>74300,'end'=>77099),
            '29'=>array('start'=>77200,'end'=>81699),
            '30'=>array('start'=>82000,'end'=>83899),
            '31'=>array('start'=>84000,'end'=>84799),
            '32'=>array('start'=>85000,'end'=>85399),
            '33'=>array('start'=>85500,'end'=>85799),
            '34'=>array('start'=>85900,'end'=>86099),
            '35'=>array('start'=>86300,'end'=>86599),
            '36'=>array('start'=>87000,'end'=>87199),
            '37'=>array('start'=>87300,'end'=>87599),
            '38'=>array('start'=>87700,'end'=>88599),
            '39'=>array('start'=>88900,'end'=>89199),
            '40'=>array('start'=>89300,'end'=>89599),
            '41'=>array('start'=>89700,'end'=>89899),
            '42'=>array('start'=>90000,'end'=>90899),
            '43'=>array('start'=>91000,'end'=>92899),
            '44'=>array('start'=>93000,'end'=>96199),
            '45'=>array('start'=>97000,'end'=>98699),
            '46'=>array('start'=>98800,'end'=>99499),
        );
        if($order['sm_code']=="BH-USPS"){
            $sortCode = "";
            foreach($usEastPost as $k=>$v){
                if($orderReceiveAddress['oab_postcode']>=$v['start']&&$orderReceiveAddress['oab_postcode']<=$v['end']){
                    $sortCode = "4R-JFK";
                    break;
                }
            }
            if( $sortCode == ""){
                foreach($usWestPost as $k=>$v){
                    if($orderReceiveAddress['oab_postcode']>=$v['start']&&$orderReceiveAddress['oab_postcode']<=$v['end']){
                        $sortCode = "4R-LAX";
                        break;
                    }
                }
            }
        }else{
            $sortCode = '';
            $orderProduct = Service_OrderProduct::getByCondition(array('order_code'=>$orderCode),"*");
            $op_purpose_declared_value = 0;
            $weight = 0;
            foreach($orderProduct as $key=>$op){
                $op_purpose_declared_value+=$op['op_purpose_declared_value'];
                $product = Service_Product::getByField($op['product_id'],"product_id","*");
                $weight+=$product['product_weight']*$op['op_quantity'];
            }
            $convertDeclaredValue = Service_Currency::converByCode('USD','EUR',$op_purpose_declared_value);
            if(in_array($country['country_code'],$countryCodeArr)){
                //$shipOrder = Service_ShipOrder::getByField($orderCode,'order_code',"*");
                if($weight>3){
                    if($convertDeclaredValue>=50){
                        $sortCode = '7E-B-2';
                    }else{
                        $sortCode = '7E-B-1';
                    }
                }else{
                    if($convertDeclaredValue>=50){
                        $sortCode = '7E-A-2';
                    }else{
                        $sortCode = '7E-A-1';
                    }
                }
            }elseif($country['country_code']=='AU'){
                $sortCode = '5E-AU';
            }
        }
        $this->view->sortingCode = $sortCode;
        echo $this->view->render($this->tplDirectory . "print_{$order['sm_code']}.tpl");
    }

    public function pdaLogoutAction(){
        $session = new Zend_Session_Namespace('userAuthorization');
        $session->unsetAll();
        session_destroy();
        setcookie('currentPage','',-1,'/');
        $this->_redirect("/default/index/pda-index");
        exit;
    }

    public function outBagNumAction()
    {
        $ob_no = trim($this->_request->getParam('ob_no'));
        if($ob_no && !empty($ob_no)){
            $outBag = Service_OutboundBag::getByField($ob_no,'ob_no');
            if(!$outBag && empty($outBag)){
                echo 'no data';exit();
            }
            $aOutboundBagDetail = Service_OutboundBagDetail::getByCondition(array('ob_no'=>$ob_no), '*');
            $outBagAddressBook = Service_OrderAddressBook::getByField($aOutboundBagDetail[0]['order_code'],'order_code');
			$order=Service_Orders::getByField($aOutboundBagDetail[0]['order_code'],'order_code');
            $outBagHjtw = Service_HjtwApi::getCode($outBagAddressBook['oab_country_id'],$outBagAddressBook['oab_postcode'],$order['sm_code']);
            $ref = Service_HjtwApi::getReferred($outBagAddressBook['oab_country_id'],$outBagAddressBook['oab_postcode'],$order['sm_code']);
            $outBag['ref'] = $ref;
            $outBag['outBagHjtw'] = $outBagHjtw;
            $this->view->obNum=$outBag;
            echo Ec::renderTpl('shipment/views/template/' . "ob_num.tpl", 'layout');
        } 
    }

    public function receiveTrackingAction(){
        $RequestData = $this->_request->getParam("RequestData","");
        //$RequestData = urldecode($RequestData);
        $data = Zend_Json::decode($RequestData);//json_decode($RequestData);
        if(!empty($data)){
            $tkData = $data['Data'];

            $trackStatusInfo = array(
                'BH-DGMG'=>array(
                    'Arrival DHL eCommerce Facility',
                    'Shipment Was Processed at Export Sorting Hub',
                    'Arrived at Terminal Location',
                    'Delivered',
                ),
                'BH-HKDHL'=>array(
                    '快件已从发件人处提取',
                    '离开转运地',
                    '快件到达中转中心',
                    '已派送并签收'
                ),
                'BH-SGG'=>array(
                    'Received from Customer',
                    'Despatched to overseas',
                    'Arrival at Destination Post',
                    'Product Delivered'
                ),
                'BH-USPS'=>array(
                    'Picked Up by Shipping Partner [ INWOOD, NY 11096 ]',
                    '暂无',
                    'Arrived Shipping Partner Facility [ ELIZABETHPORT, NJ 07206 ]',
                    'Delivered',
                ),
                'CJ-DGMG'=>array(
                    'Arrival DHL eCommerce Facility',
                    'Processing Completed at Origin',
                    'ARRIVED AT TERMINAL LOCATION',
                    'Delivered'
                ),
                'HKDHL'=>array(
                    '快件已从发件人处提取',
                    '离开转运地',
                    '快件到达中转中心',
                    '已派送并签收',
                ),
                'SF-RUPR'=>array(
                    'Почта России Прибыло на территорию России',
                    'Прием на таможню',
                    'Передано в доставку по России',
                    'Получено адресатом'
                ),
                'SF-RUPR'=>array(
                    'Прием на таможню',
                    'Прием на таможню',
                    'Передано в доставку по России',
                    'Получено адресатом',
                ),
                'SZY-EMS'=>array(
                    '深圳市邮政速递物流公司国际业务分公司已收件',
                    '到达处理中心,来自中国',
                    '到达投递局',
                    '妥投',
                ),
                'SZY-EUB'=>array(
                    '深圳市 深圳市邮政速递物流公司国际业务分公司已收件',
                    '到达处理中心,来自中国',
                    '到达投递局',
                    '妥投'
                ),
                'WG-EMS'=>array(
                    '深圳市邮政速递物流公司国际业务分公司已收件',
                    '到达处理中心,来自中国',
                    '到达投递局',
                    '妥投',
                ),
                'WG-EUB'=>array(
                    '深圳市邮政速递物流公司国际业务分公司已收件',
                    '到达处理中心,来自中国',
                    '到达投递局',
                    '妥投',
                ),
                'WG-EUB-EBAY'=>array(
                    '深圳市邮政速递物流公司国际业务分公司已收件',
                    '到达处理中心,来自中国',
                    '到达投递局',
                    '妥投',
                )
            );

            foreach($tkData as $key=>$trackingInfo){
                $tracking_number = $trackingInfo['LogisticCode'];
                $shipOrder = Service_ShipOrder::getByField($tracking_number,'tracking_number',"*");
                if(empty($shipOrder)) continue;
                $trackStatus = 0;
                $online_time = "";
                foreach($trackingInfo['Traces'] as $info){
                    $shipOrderTracking = array(
                        'so_id'=>$shipOrder['so_id'],
                        'so_code'=>$shipOrder['so_code'],
                        'order_code'=>$shipOrder['order_code'],
                        'sot_location'=>$info['AcceptStation'],
                        'sot_description'=>$info['AcceptStation'],
                        'sot_add_time'=>$info['AcceptTime'],
                        'status_desc'=>'物流完成',
                        'tracking_number'=>$tracking_number,
                    );
                    $exist = Service_ShipOrderTracking::getByCondition($shipOrderTracking,"count(*)");
                    if(!$exist) Service_ShipOrderTracking::add($shipOrderTracking);
                    if($trackStatus==0){
                        $InfoArr = $trackStatusInfo[$shipOrder['sm_code']];
                        for($i=count($InfoArr)-1;$i>=0;$i--){
                            $findStr = $InfoArr[$i];
                            if(strpos($info['AcceptStation'],$findStr)>-1){
                                $trackStatus = $i+1;
                                break;
                            }
                        }
                    }
                    if($online_time==""){
                        $InfoArr = $trackStatusInfo[$shipOrder['sm_code']];
                        for($i=0;$i<=count($InfoArr)-1;$i++){
                            $findStr = $InfoArr[$i];
                            if(strpos($info['AcceptStation'],$findStr)>-1){
                                $online_time = $info['AcceptTime'];
                                break;
                            }
                        }
                    }
                }
                if($trackingInfo['State']=="3"){
                    $result = Service_Orders::update(array('order_status'=>13),$shipOrder['order_code'],'order_code');
                    //插入ETP队列
                    if( $result ) {
                        Service_EtpOrderTrackingProcess::addSendList( $shipOrder['order_code'] );
                    }

                }
                if($trackStatus>0){
                    Service_Orders::update(array('track_status'=>$trackStatus),$shipOrder['order_code'],'order_code');
                }
                if($online_time) {
                    Service_OrderOperationTime::update(array('online_time'=>$online_time),$shipOrder['order_code'],'order_code');
                }
            }
        }
        $return = array(
            "EBusinessID"=> "1255385",
            "UpdateTime"=>date("Y/m/d H:i:s"),
            "Success"=>true,
            "Reason"=> ""
        );
        die(json_encode($return));
    }
  public function passBackTrackingAction() {
        $return = array(
            'ask' => 0,
            'message' => '失败',
            'data' => array(),
        );
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();

            try {
                $token = 'RUMAL';
                $appKey = 'a0ff809a5634d025b0906ae5351b3c41dca8146809e33f02a3793f3dbbeacef3';
                $xmlData = $this->_request->getPost('data');
                $xmlObj = simplexml_load_string($xmlData);
                if ($xmlObj == FALSE) {
                    throw new Exception('参数错误');
                }
                $getPost = Common_Common::objectToArray($xmlObj);
                if ($getPost['Header']['appKey'] != $appKey || $getPost['Header']['appToken'] != $token) {
                    throw new Exception('App Key or App Token Not match ');
                }
                if (count($getPost['data']['item']) > 20) {
                    throw new Exception('最多提交20个订单');
                }
                if (count($getPost['data']['item']) < 1) {
                    throw new Exception('没有订单提交');
                }
                $orderList=array();
                if(is_array($getPost['data']['item'])){
                    if(isset($getPost['data']['item']['orderCode'])||isset($getPost['data']['item']['trackingCode'])){
                        $orderList[]=$getPost['data']['item'];
                    }else{
                     $orderList=$getPost['data']['item'];
                    }
                }
                foreach ($orderList as $key => $order) {
                    $ordersCode = $order['orderCode'];
                    $trackingCode = trim($order['trackingCode']);
                    $return['data'][$key] = array(
                        'orderCode' => $ordersCode,
                        'trackingCode' => $trackingCode,
                        'message' => '修改失败',
                        'error' =>1
                    );
                    try {
                            $db->beginTransaction();
                        if (empty($ordersCode)) {
                            throw new Exception('订单号不能为空');
                        }
                        if (empty($trackingCode)) {
                            throw new Exception('运单号不能为空');
                        }elseif(strlen($trackingCode)>64){
                              throw new Exception('运单号不能超过64位字符');
                        }
                        $orderRow = Service_Orders::getByField($ordersCode, "order_code", "*");
                        if (empty($orderRow) || !in_array($orderRow['sm_code'], array('Rumall-RU-EP', 'Rumall-RU-G'))) {
                            throw new Exception('订单号不存在');
                        }
                        $shipOrder = Service_ShipOrder::getByField($ordersCode, "order_code", "*");
                       

                        $shipOrderUpdateRow = array(
                            'tracking_number' => $trackingCode,
                        );
                        $orderUpdateRow = array(
                            'ref_tracking_number' => $trackingCode,
                        );
                        Service_orders::update($orderUpdateRow, $orderRow['order_id']);
                         if (!empty($shipOrder)) {
                             Service_ShipOrder::update($shipOrderUpdateRow, $shipOrder['so_id']);
                        }
                        $return['data'][$key]['message'] = '修改成功';
                        $return['data'][$key]['error'] = '0';
                        $return['ask']=1;
                        $return['message']='修改成功';
                        $db->commit();
                    } catch (Exception $e) {
                        $return['data'][$key]['message'] = $e->getMessage();
                        $db->rollBack();
                    }
                }
            } catch (Exception $e) {
                $return['message'] = $e->getMessage();
            }
        }
        die(Service_RumalApiProcess::assocArrayToXML($return, '', '', 'Response'));
    }

    public function pullOrderAction(){
        $xmlString = file_get_contents('php://input');
        $xmlDom= simplexml_load_string($xmlString);
        $orderInfoArr = Common_Common::objectToArray($xmlDom);
        $shipOrderList = $orderInfoArr['order'];
        //$shipOrderArr = array();
        $filePath = APPLICATION_PATH.'/../data/log/'.'opadsd.txt';
        if(!file_exists($filePath)){
            $fp= fopen($filePath,"w");
            fclose($fp);
        }
        file_put_contents($filePath,var_export($shipOrderList,true),FILE_APPEND);
        $infoList = array();
        foreach($shipOrderList as $key=>$value){
            if(!is_numeric($key)){
                $infoList[$value] = array(
                    'order_code'=>$shipOrderList['order_code'],
                );
                $infoList[$shipOrderList['order_code']]['weightInfo'][] = $shipOrderList;
                break;
            }else{
                if(!array_key_exists($value['order_code'],$infoList)){
                    $infoList[$value['order_code']] = array(
                        'order_code'=>$value['order_code'],
                    );
                }
                $infoList[$value['order_code']]['weightInfo'][] = $value;
            }
        }
        foreach($infoList as $key=>$value){
            $orderRow = Service_Orders::getByField($value['order_code'],"order_code","*");
            $weightInfo = $value['weightInfo'];
            foreach($weightInfo as $info){
                $ovw = array(
                    'order_id'=>$orderRow['order_id'],
                    'order_code'=>$orderRow['order_code'],
                    'vow_weight'=>$info['so_weight'],
                    'vow_length'=>$info['so_length'],
                    'vow_width'=>$info['so_width'],
                    'vow_height'=>$info['so_height'],
                    'vow_add_time'=>date("Y-m-d H:i:s")
                );
                Service_OrdersVolumeWeight::add($ovw);
            }

        }
        $returnXml = "<?xml version='1.0'?>".
            "<result>".
            "<success>Suceess</success>".
            "<errorMsg>no error</errorMsg>".
            "<errorCode>S06</errorCode>".
            "<status></status>".
            "</result>";
        echo $returnXml;
    }

    public function calculateAction(){
        $time_year = $this->_request->getParam("time_year","2017");
        //$timeStart=date("Y-m-d", strtotime("-1 year"));
        $timeStartHis = $time_year."-01-01 00:00:00";
        $nowYear = date("Y");
        if($time_year!=$nowYear){
            $timeNowHis = $time_year."-12-31 23:59:59";
        }else{
            $timeNowHis = date("Y-m-d H:i:s");
        }
        $customerCode = 'E0851,E0711';
        $timeNow = date("Y-m-d");
        $startdate=strtotime($timeStartHis);
        $enddate=strtotime($timeNowHis);
        //echo "startdat=".$startdate."&enddate=".$enddate;
        $days=round(($enddate-$startdate)/3600/24);
        //echo "</br>days=".$days;
        $db = Common_Common::getAdapter();
        $countSql = "SELECT count(orders.order_code) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code WHERE orders.customer_code in ('E0851','E0711') AND ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."'";
        $count = $db->fetchOne($countSql);

        $totalWeightSql = "SELECT SUM(ship_order.so_weight) FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN ship_order ON ship_order.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' AND orders.customer_code in ('E0851','E0711')";
        $totalWeight = $db->fetchOne($totalWeightSql);

        $totalValueSql1 = "SELECT SUM(receiving_detail.rd_receiving_qty*product.product_declared_value) AS total_value FROM receiving JOIN receiving_detail ON receiving_detail.receiving_code=receiving.receiving_code JOIN product ON product.product_id=receiving_detail.product_id WHERE receiving.customer_code in ('E0851','E0711') AND receiving.receiving_status=7 and receiving.receiving_add_time>='".$timeStartHis."' AND receiving.receiving_add_time<='".$timeNowHis."'";
        $totalValue1 = $db->fetchOne($totalValueSql1);
        $countReSql1 = "SELECT count(DISTINCT receiving.receiving_code) FROM receiving JOIN receiving_detail ON receiving_detail.receiving_code=receiving.receiving_code JOIN product ON product.product_id=receiving_detail.product_id WHERE receiving.customer_code in ('E0851','E0711') AND receiving.receiving_status=7 and receiving.receiving_add_time>='".$timeStartHis."' AND receiving.receiving_add_time<='".$timeNowHis."'";
        $countRe1 =  $db->fetchOne($countReSql1);

        $totalValueSql2 = "SELECT SUM(order_product.op_quantity*product.product_declared_value) AS total_value FROM receiving JOIN receiving_order_detail ON receiving.receiving_code=receiving_order_detail.receiving_code JOIN order_product ON order_product.order_code=receiving_order_detail.order_code JOIN product ON product.product_id=order_product.product_id WHERE receiving.customer_code in ('E0851','E0711') AND receiving.receiving_status=7 and receiving.receiving_add_time>='".$timeStartHis."' AND receiving.receiving_add_time<='".$timeNowHis."'";
        $totalValue2 = $db->fetchOne($totalValueSql2);
        $countReSql2 = "SELECT count(DISTINCT receiving.receiving_code) FROM receiving JOIN receiving_order_detail ON receiving.receiving_code=receiving_order_detail.receiving_code JOIN order_product ON order_product.order_code=receiving_order_detail.order_code JOIN product ON product.product_id=order_product.product_id WHERE receiving.customer_code in ('E0851','E0711') AND receiving.receiving_status=7 and receiving.receiving_add_time>='".$timeStartHis."' AND receiving.receiving_add_time<='".$timeNowHis."'";
        $countRe2 =  $db->fetchOne($countReSql2);
        $totalValue = $totalValue1+$totalValue2;
        $countRe = $countRe1 + $countRe2;

        $totalInventorySql = "SELECT SUM(product_inventory.pi_sellable) FROM product_inventory JOIN product ON product.product_id=product_inventory.product_id WHERE product.customer_code in ('E0851','E0711')";
        $totalInventory = $db->fetchOne($totalInventorySql);;

        $sumReTimeSql = "SELECT SUM(UNIX_TIMESTAMP(receiving_attribute.shelf_time)-UNIX_TIMESTAMP(receiving.receiving_add_time)) FROM receiving_attribute JOIN receiving ON receiving.receiving_code=receiving_attribute.receiving_code WHERE receiving_status=7 AND receiving.receiving_add_time>='".$timeStartHis."' AND receiving.receiving_add_time<='".$timeNowHis."' AND customer_code in ('E0851','E0711')";
        $sumReTime = $db->fetchOne($sumReTimeSql);
        $totalRecSql = "SELECT count(receiving.receiving_code) FROM receiving_attribute JOIN receiving ON receiving.receiving_code=receiving_attribute.receiving_code WHERE receiving_status=7 AND receiving.receiving_add_time>='".$timeStartHis."' AND receiving.receiving_add_time<='".$timeNowHis."' AND customer_code in ('E0851','E0711')";
        $totalRec = $db->fetchOne($totalRecSql);
        $avg_ruku = 0;
        if($totalRec!=0) $avg_ruku = round($sumReTime/3600/$totalRec,2);
        $sumOTSql = "SELECT SUM(UNIX_TIMESTAMP(order_operation_time.shipment_time)-UNIX_TIMESTAMP(order_operation_time.submit_time)) FROM order_operation_time JOIN orders ON orders.order_code=order_operation_time.order_code WHERE orders.order_status>=11 AND orders.customer_code in ('E0851','E0711') AND orders.add_time>='".$timeStartHis."' AND orders.add_time<='".$timeNowHis."'";
        $sumOT = $db->fetchOne($sumOTSql);
        $totalOrderSQL = "SELECT count(orders.order_code) FROM order_operation_time JOIN orders ON orders.order_code=order_operation_time.order_code WHERE orders.order_status>=11 AND orders.customer_code in ('E0851','E0711') AND orders.add_time>='".$timeStartHis."' AND orders.add_time<='".$timeNowHis."'";
        $totalOrder = $db->fetchOne($totalOrderSQL);
        $avg_chuqu = 0;
        if($totalOrder!=0) $avg_chuqu = round($sumOT/3600/$totalOrder,2);
        $sql = "SELECT SUM(order_product.op_quantity),pc_id FROM order_product JOIN product ON product.product_id=order_product.product_id WHERE 1 AND product.pc_id<>0 AND product.pc_id<>'' AND order_product.op_add_time>='".$timeStartHis."' AND order_product.op_add_time<='".$timeNowHis."' and product.customer_code in ('E0851','E0711') GROUP by pc_id order by SUM(order_product.op_quantity) DESC LIMIT 2 ";
        $ret = $db->fetchAll($sql);
        $product_category = "";
        $smtpcArr = array();
        foreach($ret as $rk=>$rv){
            if(!in_array($rv['pc_id'],$smtpcArr)){
                $pc = Service_ProductCategory::getByField($rv['pc_id'],"pc_id","*");
                $product_category.=$pc['pc_name']." ";
                $smtpcArr[] = $rv['pc_id'];
            }
        }
        //var_dump($smtpcArr);
        $sumaitongBord = array(
            'customer_code'=>'深圳速恒电子有限公司',
            'avg_order'=>round($count/$days,2),
            'avg_weight'=>round($totalWeight/$days,2),
            'totalWeight'=>$totalWeight==0?$totalWeight:round($totalWeight/$count,4),
            'avg_value'=>round($totalValue/$days,2),
            'totalValue'=>$totalValue==0?$totalValue:round($totalValue/$countRe,2),
            'totalInventory'=>$totalInventory,
            'avg_ruku'=>$avg_ruku,
            'avg_chuqu'=>$avg_chuqu,
            'product_category'=>$product_category,
        );
        $sql2 = "SELECT count(orders.order_code) AS total,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN customer ON customer.customer_code=orders.customer_code WHERE customer.customer_platform='oms' AND ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' GROUP BY  month(ship_batch.sb_ship_time)";
        $ret2 = $db->fetchAll($sql2);
        $OrderMonthArr = array(
            'avg_month1'=>'0',
            'avg_month2'=>'0',
            'avg_month3'=>'0',
            'avg_month4'=>'0',
            'avg_month5'=>'0',
            'avg_month6'=>'0',
            'avg_month7'=>'0',
            'avg_month8'=>'0',
            'avg_month9'=>'0',
            'avg_month10'=>'0',
            'avg_month11'=>'0',
            'avg_month12'=>'0',
        );
        foreach($ret2 as $r2k=>$r2v){
            $key = "";
            $key = "avg_month".$r2v['month'];
            if(in_array($r2v['month'],array(1,3,5,7,8,10,12))){
                $OrderMonthArr[$key] = round($r2v['total']/31,2);
            }elseif(in_array($r2v['month'],array(4,6,9,11))){
                $OrderMonthArr[$key] = round($r2v['total']/30,2);
            }else{
                $div=28;
                if($time_year%4==0) $div=29;
                $OrderMonthArr[$key] = round($r2v['total']/$div,2);
            }
        }
        $sqlWeight = "SELECT SUM(ship_order.so_weight) AS totalWeight,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN customer ON customer.customer_code=orders.customer_code JOIN ship_order ON ship_order.order_code=orders.order_code WHERE customer.customer_platform='oms' AND ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' GROUP BY  month(ship_batch.sb_ship_time)";
        $WeightRet = $db->fetchAll($sqlWeight);
        $WeightMonthArr = array(
            'avg_month1'=>'0',
            'avg_month2'=>'0',
            'avg_month3'=>'0',
            'avg_month4'=>'0',
            'avg_month5'=>'0',
            'avg_month6'=>'0',
            'avg_month7'=>'0',
            'avg_month8'=>'0',
            'avg_month9'=>'0',
            'avg_month10'=>'0',
            'avg_month11'=>'0',
            'avg_month12'=>'0',
        );
        foreach($WeightRet as $wrk=>$wrv){
            $key = "";
            $key = "avg_month".$wrv['month'];
            if(in_array($wrv['month'],array(1,3,5,7,8,10,12))){
                $WeightMonthArr[$key] = round($wrv['totalWeight']/31,2);
            }elseif(in_array($wrv['month'],array(4,6,9,11))){
                $WeightMonthArr[$key] = round($wrv['totalWeight']/30,2);
            }else{
                $div=28;
                if($time_year%4==0) $div=29;
                $WeightMonthArr[$key] = round($wrv['totalWeight']/$div,2);
            }
        }
        $SMTOrderSql = "SELECT count(orders.order_code) AS total,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN customer ON customer.customer_code=orders.customer_code WHERE ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' and customer.customer_code in ('E0851','E0711') GROUP BY  month(ship_batch.sb_ship_time)";
        $SMTORet = $db->fetchAll($SMTOrderSql);
        $SMTOrderMonthArr = array(
            'avg_month1'=>'0',
            'avg_month2'=>'0',
            'avg_month3'=>'0',
            'avg_month4'=>'0',
            'avg_month5'=>'0',
            'avg_month6'=>'0',
            'avg_month7'=>'0',
            'avg_month8'=>'0',
            'avg_month9'=>'0',
            'avg_month10'=>'0',
            'avg_month11'=>'0',
            'avg_month12'=>'0',
        );
        foreach($SMTORet as $smtk=>$smtv){
            $key = "";
            $key = "avg_month".$smtv['month'];
            if(in_array($smtv['month'],array(1,3,5,7,8,10,12))){
                $SMTOrderMonthArr[$key] = round($smtv['total']/31,2);
            }elseif(in_array($smtv['month'],array(4,6,9,11))){
                $SMTOrderMonthArr[$key] = round($smtv['total']/30,2);
            }else{
                $div=28;
                if($time_year%4==0) $div=29;
                $SMTOrderMonthArr[$key] = round($smtv['total']/$div,2);
            }
        }

        $SMTSqlWeight = "SELECT SUM(ship_order.so_weight) AS totalWeight,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN customer ON customer.customer_code=orders.customer_code JOIN ship_order ON ship_order.order_code=orders.order_code WHERE ship_batch.sb_ship_time>='".$timeStartHis."'and customer.customer_code in ('E0851','E0711') AND ship_batch.sb_ship_time<='".$timeNowHis."' GROUP BY  month(ship_batch.sb_ship_time)";
        $SMTWeightRet = $db->fetchAll($SMTSqlWeight);
        $SMTWeightMonthArr = array(
            'avg_month1'=>'0',
            'avg_month2'=>'0',
            'avg_month3'=>'0',
            'avg_month4'=>'0',
            'avg_month5'=>'0',
            'avg_month6'=>'0',
            'avg_month7'=>'0',
            'avg_month8'=>'0',
            'avg_month9'=>'0',
            'avg_month10'=>'0',
            'avg_month11'=>'0',
            'avg_month12'=>'0',
        );
        foreach($SMTWeightRet as $smtwrk=>$smtwrv){
            $key = "";
            $key = "avg_month".$smtwrv['month'];
            if(in_array($smtwrv['month'],array(1,3,5,7,8,10,12))){
                $SMTWeightMonthArr[$key] = round($smtwrv['totalWeight']/31,2);
            }elseif(in_array($smtwrv['month'],array(4,6,9,11))){
                $SMTWeightMonthArr[$key] = round($smtwrv['totalWeight']/30,2);
            }else{
                $div=28;
                if($time_year%4==0) $div=29;
                $SMTWeightMonthArr[$key] = round($smtwrv['totalWeight']/$div,2);
            }
        }

        $customerTotalSql = "SELECT count(customer_id) FROM customer WHERE customer_reg_time>='".$timeStartHis."' AND customer_reg_time<='".$timeNowHis."' AND (customer_status=2 or customer_status=1)";
        $totalCustomer = $db->fetchOne($customerTotalSql);

        $sql = "SELECT SUM(order_product.op_quantity),pc_id FROM order_product JOIN product ON product.product_id=order_product.product_id WHERE 1 AND product.pc_id<>0 AND product.pc_id<>'' AND order_product.op_add_time>='".$timeStartHis."' AND order_product.op_add_time<='".$timeNowHis."' GROUP by pc_id order by SUM(order_product.op_quantity) DESC LIMIT 2 ";
        $ret2 = $db->fetchAll($sql);
        $pcArr = array();
        foreach($ret2 as $rk2=>$rv2){
            if(!in_array($rk2['pc_id'],$pcArr)){
                $pc = Service_ProductCategory::getByField($rv2['pc_id'],"pc_id","*");
                $product_category.=$pc['pc_name']." ";
                $pcArr[] = $rv2['pc_id'];
            }
        }

        $productCategoryList = Service_ProductCategory::getAll();
        $AllSmtProduct = array();
        $ALlDsProduct = array();
        foreach($productCategoryList as $pck=>$pcv){
            $smtProduct = array(
                'pc_name'=>'',
                'avg_month1'=>'0',
                'avg_month2'=>'0',
                'avg_month3'=>'0',
                'avg_month4'=>'0',
                'avg_month5'=>'0',
                'avg_month6'=>'0',
                'avg_month7'=>'0',
                'avg_month8'=>'0',
                'avg_month9'=>'0',
                'avg_month10'=>'0',
                'avg_month11'=>'0',
                'avg_month12'=>'0',
            );
            $smtdsplSql = "SELECT SUM(order_product.op_quantity) AS total_quantity,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN order_product ON order_product.order_code=orders.order_code JOIN customer ON customer.customer_code=orders.customer_code JOIN product ON product.product_id=order_product.product_id WHERE ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' AND customer.customer_code in ('E0851','E0711') AND product.pc_id='".$pcv['pc_id']."' GROUP BY  month(ship_batch.sb_ship_time)";
            $smtp1 = $db->fetchAll($smtdsplSql);
            if(!empty($smtp1)){
                foreach($smtp1 as $smk1=>$smv1){
                    $key = "";
                    $key = "avg_month".$smv1['month'];
                    $smtProduct[$key] = $smv1['total_quantity'];
                }
                $smtProduct['pc_name'] = $pcv['pc_name'];
                $AllSmtProduct[] = $smtProduct;
            }


            $dsplSql = "SELECT SUM(order_product.op_quantity) AS total_quantity,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN order_product ON order_product.order_code=orders.order_code JOIN customer ON customer.customer_code=orders.customer_code JOIN product ON product.product_id=order_product.product_id WHERE ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' AND customer.customer_platform='oms' AND product.pc_id='".$pcv['pc_id']."' GROUP BY  month(ship_batch.sb_ship_time)";

            $dsplAll = $db->fetchAll($dsplSql);
            $dsplProduct = array(
                'pc_name'=>'',
                'avg_month1'=>'0',
                'avg_month2'=>'0',
                'avg_month3'=>'0',
                'avg_month4'=>'0',
                'avg_month5'=>'0',
                'avg_month6'=>'0',
                'avg_month7'=>'0',
                'avg_month8'=>'0',
                'avg_month9'=>'0',
                'avg_month10'=>'0',
                'avg_month11'=>'0',
                'avg_month12'=>'0',
            );
            if(!empty($dsplAll)){
                foreach($dsplAll as $dk=>$dv){
                    $key = "";
                    $key = "avg_month".$dv['month'];
                    $dsplProduct[$key] = $dv['total_quantity'];
                }
                $dsplProduct['pc_name'] = $pcv['pc_name'];
                $ALlDsProduct[] = $dsplProduct;
            }
        }

        $smtdsplSql = "SELECT SUM(order_product.op_quantity) AS total_quantity,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN order_product ON order_product.order_code=orders.order_code JOIN customer ON customer.customer_code=orders.customer_code JOIN product ON product.product_id=order_product.product_id WHERE ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' AND customer.customer_code in ('E0851','E0711') AND product.pc_id='0' GROUP BY  month(ship_batch.sb_ship_time)";
        $smtp1 = $db->fetchAll($smtdsplSql);
        $smtProduct = array(
            'pc_name'=>'',
            'avg_month1'=>'0',
            'avg_month2'=>'0',
            'avg_month3'=>'0',
            'avg_month4'=>'0',
            'avg_month5'=>'0',
            'avg_month6'=>'0',
            'avg_month7'=>'0',
            'avg_month8'=>'0',
            'avg_month9'=>'0',
            'avg_month10'=>'0',
            'avg_month11'=>'0',
            'avg_month12'=>'0',
        );
        if(!empty($smtp1)){
            foreach($smtp1 as $smk1=>$smv1){
                $key = "";
                $key = "avg_month".$smv1['month'];
                $smtProduct[$key] = $smv1['total_quantity'];
            }
            $smtProduct['pc_name'] = "其他";
            $AllSmtProduct[] = $smtProduct;
        }

        $dsplSql = "SELECT SUM(order_product.op_quantity) AS total_quantity,MONTH(ship_batch.sb_ship_time) AS month FROM ship_batch JOIN ship_batch_detail ON ship_batch.sb_code=ship_batch_detail.sb_code JOIN outbound_bag_detail ON outbound_bag_detail.ob_no=ship_batch_detail.ob_no JOIN orders ON orders.order_code=outbound_bag_detail.order_code JOIN order_product ON order_product.order_code=orders.order_code JOIN customer ON customer.customer_code=orders.customer_code JOIN product ON product.product_id=order_product.product_id WHERE ship_batch.sb_ship_time>='".$timeStartHis."' AND ship_batch.sb_ship_time<='".$timeNowHis."' AND customer.customer_platform='oms' AND product.pc_id='0' GROUP BY  month(ship_batch.sb_ship_time)";
        $dsplAll = $db->fetchAll($dsplSql);
        $dsplProduct = array(
            'pc_name'=>'',
            'avg_month1'=>'0',
            'avg_month2'=>'0',
            'avg_month3'=>'0',
            'avg_month4'=>'0',
            'avg_month5'=>'0',
            'avg_month6'=>'0',
            'avg_month7'=>'0',
            'avg_month8'=>'0',
            'avg_month9'=>'0',
            'avg_month10'=>'0',
            'avg_month11'=>'0',
            'avg_month12'=>'0',
        );
        if(!empty($dsplAll)){
            foreach($dsplAll as $dk=>$dv){
                $key = "";
                $key = "avg_month".$dv['month'];
                $dsplProduct[$key] = $dv['total_quantity'];
            }
            $dsplProduct['pc_name'] = '其他';
            $ALlDsProduct[] = $dsplProduct;
        }


        $this->view->AllSmtProduct=$AllSmtProduct;
        $this->view->ALlDsProduct=$ALlDsProduct;
        $this->view->totalCustomer = $totalCustomer;
        $this->view->SMTOrderMonthArr = $SMTOrderMonthArr;
        $this->view->SMTWeightMonthArr = $SMTWeightMonthArr;
        $this->view->OrderMonthArr = $OrderMonthArr;
        $this->view->WeightMonthArr = $WeightMonthArr;
        $this->view->sumaitongBord= $sumaitongBord;
        //$this->view->timeStart = $timeStart;
        //$this->view->timeNow = $timeNow;
        $this->view->time_year = $time_year;
        echo Ec::renderTpl($this->tplDirectory . "calculate.tpl", 'layout');
    }
	function  testAutoTaskAction(){
			header("Content-type:text/plain;charset=utf-8");
			require_once (APPLICATION_PATH. '/../auto/autoKFive.php');

	}

    public function getPdfLabelAction(){
        $orderCode = trim($this->_request->getParam("code",""));
        $pdfFile = APPLICATION_PATH.'/../data/pdf/error.pdf';
        if ($orderCode) {
            $order = Service_Orders::getByField($orderCode,"order_code","*");
            if($order instanceof Zend_Db_Table_Row){
                $order = $order->toArray();
            }
            if(empty($order)){
                $order = Service_Orders::getByField($orderCode,"ref_tracking_number","*");
                if($order instanceof Zend_Db_Table_Row){
                    $order = $order->toArray();
                }
            }
            $tmp = '';
            if($order){
                switch($order['sm_code']){
                    case 'SZY-EUB':
                    case 'WG-EUB':
                        $tmp = 'EUB';
                        break;
                    case 'UKTL';
                        $tmp = 'UKTL';
                        break;
                    case 'SZY-ETK':
                        $tmp = 'ETK';
                        break;
                    case 'BH-HKDHL':
                        $tmp='BHHKDHL';
                        break;
                    case 'PNLG':
                        $tmp='PNLG';
                        break;
                    case 'PNLN':
                        $tmp='PNLN';
                        break;
                    case '4PX-LYT_GH':
                    case '4PX-EU_PACKET':
                    case '4PX-RU_POST-LINK_RMAIL':
                    case '4PX-HKDHL':
                    case '4PX-YX':
                    case '4PX-SG_ordinary_mail+':
                    case 'LYT-SMTGH-X':
                        $fourPx = true;
                        $tmp = 'Fourpx';
                        break;
                    case 'Rumall-RU-G':
                        $tmp='RUMAll-RU-G';
                        break;
                    case 'Rumall-RU-EP':
                        $tmp='RUMAll-RU-EP';
                        break;
                    case 'BH-SFEP':
                        $tmp='BHSFEP';
                        break;
                    case 'CJ-DGMG':
                    case 'CJ-DGMP':
                    case 'DGM-US' :
                        $tmp='CJ';
                        break;
                    case 'BH-3HPA':
                    case 'BH-3H':
                    case 'BH-UKECSLTYD':
                    case 'BH-UKECSLTRM':
                    case 'BH-CORREOS':
                    case 'BH-19EURDPDDE':
                    case 'BH-DAC':
                    case 'BH-SL018':
                    case 'BH-IESLTANPOST':
                        $tmp = 'oneWorldExpress';
                        break;
                    case 'DHL-TH':
                        $tmp = 'DHLTH';
                        break;
                    default:
                        break;
                }
            }
            if($order && $tmp){
                $pdfFile = APPLICATION_PATH.'/../data/pdf/'.$tmp.'/'.$order['order_code'].".pdf";
                //标签不存在就去获取标签
                if(!file_exists($pdfFile)){
                    if($tmp=='BHHKDHL'){
                        $trackingNumber=  Service_ShipOrder::getByField($order['order_code'], 'order_code');
                        if(!empty($trackingNumber)){
                            $bhhkdhlService=new Service_BHHKDHLApiProcess($order['order_code'], '', '');
                            $bhhkdhlService->setWaybillNumber($trackingNumber['tracking_number']);
                            $bhhkdhlService->generatePdf();
                        }
                    }elseif($tmp=='PNLG'||$tmp=='PNLN'){
                        if(!empty($order['ref_tracking_number'])){
                            $savePdfPath=array(
                                'PNLG'=> APPLICATION_PATH . '/../data/pdf/PNLG/',
                                'PNLN'=>APPLICATION_PATH . '/../data/pdf/PNLN/',
                            );
                            $UspsClass = new Service_UspsInterface();
                            $pdfPath=$UspsClass->getLabel($order['order_code'], $order['ref_tracking_number']);
                            if($pdfPath['pdfUrl']){
                                $b=fopen($pdfPath['pdfUrl'],'r');
                                $content='';
                                while(!feof($b)){
                                    $content.=fread($b,1024);
                                }
                                file_put_contents($savePdfPath[$order['sm_code']].$order['order_code'].'.pdf' , $content);
                            }
                        }
                    }elseif($tmp=='RUMAll-RU-EP'||$tmp=='RUMAll-RU-G'){
                        $rumalService=new Service_RumalApiProcess();
                        if(!empty($order['reference_no'])&&(!empty($order['ref_tracking_number'])||!empty($order['agent_mailno']))){
                            $p=$rumalService->genaratLabel($order['reference_no']);
                            if(strpos($p,'%PDF-1.4')!==FALSE){
                                file_put_contents($pdfFile, $p);
                                Service_OrdersLabel::add(array('order_code'=>$order['order_code'],'ol_content'=>  base64_encode($p),'ol_time'=>date('Y-m-d H;i:s')));
                            }
                        }
                    }elseif($fourPx){
                        $soap = new Service_FourpxWebService();
                        $result = $soap->getPdfByOrderCode($orderCode);
                        if ($result['status']) {
                            $orderLog = array(
                                'order_id'=>$order['order_id'],
                                'order_code'=>$order['order_code'],
                                'ol_type'=>'1',
                                'order_status_from'=>$order['order_status'],
                                'order_status_to'=>$order['order_status'],
                                'ol_add_time'=>date("Y-m-d H:i:s"),
                                'user_id'=>0,
                                'ol_comments'=>'4PX打印单据时取标签'
                            );
                            Service_OrderLog::add($orderLog);
                        }
                    }elseif($tmp =='CJ'){
                        $labelResult = Service_OrdersLabel::getByField($order['order_code'],'order_code');
                        if(!empty($labelResult['ol_content'])){
                            $labelString = base64_decode($labelResult['ol_content']);
                            $dirPath = dirname($pdfFile);
                            $dirPath=str_replace("\\","/",$dirPath);
                            mkdir($dirPath);
                            chmod($dirPath,0777);
                            file_put_contents($pdfFile, $labelString);
                        }
                    }elseif($tmp=="BHSFEP"){
                        $labelResult = Service_OrdersLabel::getByField($order['order_code'],'order_code');
                        $content='';
                        if(!empty($labelResult['ol_content'])){
                            $content = base64_decode($labelResult['ol_content']);
                        }else{
                            $UspsClass = new Service_UspsInterface();
                            $pdfPath=$UspsClass->getLabel($order['order_code'], $order['ref_tracking_number']);
                            if($pdfPath['pdfUrl']){
                                $b=fopen($pdfPath['pdfUrl'],'r');
                                while(!feof($b)){
                                    $content.=fread($b,1024);
                                }
                            }
                        }
                        header('Content-Type: application/pdf; charset=utf-8');
                        header('Content-Disposition:inline; filename=report.pdf');
                        echo $content;
                    }else{
                        $epaService = new Service_EpacketWebService();
                        $labelResult = $epaService->getOneLableByMailnum($order['ref_tracking_number']);
                        $result = $epaService->getPdfByOrderCode($order['order_code']);
                        if($result){
                            $orderLog = array(
                                'order_id'=>$order['order_id'],
                                'order_code'=>$order['order_code'],
                                'ol_type'=>'1',
                                'order_status_from'=>$order['order_status'],
                                'order_status_to'=>$order['order_status'],
                                'ol_add_time'=>date("Y-m-d H:i:s"),
                                'user_id'=>0,
                                'ol_comments'=>'EUB打印单据时取标签'
                            );
                            Service_OrderLog::add($orderLog);
                        }
                    }

                    //判断重新生成后的标签是否存在
                    if(!file_exists($pdfFile)){ // 再次确认标签是否存在
                        $pdfFile = APPLICATION_PATH.'/../data/pdf/create_error.pdf';
                    }
                }
            }
        }
        $pdfContent = file_get_contents($pdfFile,false,null);
        header('Content-Type: application/pdf; charset=utf-8');
        header('Content-Disposition:inline; filename=report.pdf');
        echo $pdfContent;
    }

    public function templateAction() {
        $file = $this->_request->getParam('file_name');
        $templatePath = APPLICATION_PATH . '/../data/xls/';
        $fullPath = $templatePath . $file;
        if (file_exists($fullPath)) {
            Common_Common::downloadFile($fullPath);
        } else {
            echo 'file not exit';
        }
        die();
    }

}
