<?php
class Ship_PriceTempController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "ship/views/";
        $this->serviceClass = new Service_ShipPriceTemp();
    }
    /**
     * 列表
     * (non-PHPdoc)
     * @see Ec_Controller_Action::listAction()
     */
    public function listAction()
    {
        $currency=Common_DataCache::getCurrency();
        $type=Common_Type::SMFeeType('auto');
        $warehouse=Common_DataCache::getWarehouseSimple();
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();
            $condition = $this->serviceClass->getMatchFields($params);
            unset($params);
            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    'sm_code',
                    'sp_weight',
                    'sp_cost',
                    'sp_price',
                    'currency_code',
                    'area',
                    'sp_fee_type',
                    'warehouse_id',
                    'sp_id',
                    'sp_ticket_cost',
                    'cost_currency_code',
                    'one_ticket_cbcost',
                    'price_batch_number',
                    'date_start',
                    'date_end'
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('date_start desc', 'sp_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['type'] = $type;
                $return['warehouse'] = $warehouse;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->currency=$currency;
        $this->view->type=$type;
        //$this->view->SM=Common_DataCache::getShippingMethodSimple();
        $sm=Service_ShippingMethod::getAll();
        $sm=Common_Common::multisort($sm);
        $this->view->SM =$sm; 
        $this->view->warehouse=$warehouse;
        echo Ec::renderTpl($this->tplDirectory . "price_temp_index.tpl", 'layout');
    }
    /**
     * 编辑
     */
    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'sp_id' => '',
                'sm_code' => '',
                'sp_weight' => '',
                'sm_id' => '',
                'sp_cost' => '',
                'sp_price' => '',
                'currency_code' => '',
                'area' => '',
                'sp_fee_type' => '',
                'warehouse_id' => '',
                'sp_ticket_cost' => '',
                'cost_currency_code' => '', // 成本币种
                'one_ticket_cbcost' => '',
                'date_start' => '',
                'date_end' => ''
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            unset($params);
            $paramId = $row['sp_id'];
            if (!empty($row['sp_id'])) {
                unset($row['sp_id']);
            }
            $smRow = Service_ShippingMethod::getByField($row['sm_id'], 'sm_id');
            $row['sm_id']=$smRow['sm_id'];
            $row['sm_code'] = $smRow['sm_code'];
            unset($smRow);
            $errorArr = $this->serviceClass->validator($row);
            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }
            $smRow = Service_ShippingMethod::getByField($row['sm_id'], 'sm_id');
            $row['sm_id'] = $smRow['sm_id'];
            unset($smRow);
            if (!empty($paramId)) {
                unset($row['price_batch_number']); /* price_batch_number 不允许修改 */
                $result = $this->serviceClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }
        }
        die(Zend_Json::encode($return));
    }
    
    /**
     * 编辑获取数据
     */
    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'sp_id')) {
            $rows=$this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }
    
    /**
     * 删除
     */
    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }
    
    /**
     * 批量导入运输区域模板
     */
    public function batchImportTemplateAction(){
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH."/../data/xls".'/ship_price_batch_import.xls';
        //方法2
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        //  header("Content-Transfer-Encoding: binary");
        //  header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }
    
    /**
     * 批量导入运输价格
     */
    public function batchImportAction(){
        set_time_limit(0);
        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_SmCustomerMap::getXLSData($_FILES,'filename');
        if(count($xlsData[0])!=14 ||$xlsData[0][0]!="仓库"||$xlsData[0][1]!="运输代码"||$xlsData[0][2]!="成本币种"||$xlsData[0][3]!="货币Code"||$xlsData[0][4]!="费用类型"||$xlsData[0][5]!="运输分区"||$xlsData[0][6]!="重量（KG）"|| $xlsData[0][7]!="成本"|| $xlsData[0][8]!="费用" || $xlsData[0][9]!="单票费用"||$xlsData[0][10]!="单票成本"||$xlsData[0][11]!="开始时间"||$xlsData[0][12]!="结束时间"||$xlsData[0][13]!="价格编号" ){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照仓库,运输代码,成本币种,货币Code,费用类型,运输分区,重量（KG）,成本,费用,单票费用,单票成本,价格编号排列!";
            die(json_encode($result));
        }
        $dataFormat = '/^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/';
        foreach($xlsData as $key=>$value){
            if($key==0) continue;
            $existError = 0;
            //仓库代码
            $warehouse_code = $value[0];
            //运输方式代码
            $sm_code = $value[1];
            // 成本币种
            $cost_currency_code = $value[2];
            //币种
            $currency_code = $value[3];
            //费用类型
            $sp_fee_type_text = $value[4];
            //收费分区
            $area = $value[5];
            //重量
            $sp_weight = $value[6];
            //成本
            $sp_cost = $value[7];
            //费用
            $sp_price = $value[8];
            //费用
            $sp_ticket_cost = $value[9];
            //单票成本
            $one_ticket_cbcost = $value[10];
            $date_start = $value[11];
            
            if(preg_match('/^\d{5}$/',$date_start)){
                $date_start = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_start));
            }
            $date_end = $value[12];
            if(preg_match('/^\d{5}$/',$date_end)){
                $date_end = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_end));
            }
            $start=explode(" ", $date_start);
            $date_start=$start[0];
            $end=explode(" ", $date_end);
            $date_end=$end[0];
            //价格编号
            $price_batch_number = $value[13];
            $resultData = array(
                'warehouse_code'=>$warehouse_code,
                'sm_code'=>$sm_code,
                'currency_code'=>$currency_code,
                'cost_currency_code' => $cost_currency_code,
                'sp_fee_type_text'=>$sp_fee_type_text,
                'area'=>$area,
                'sp_weight'=>$sp_weight,
                'sp_cost'=>$sp_cost,
                'sp_price'=>$sp_price,
                'sp_ticket_cost'=>$sp_ticket_cost,
                'one_ticket_cbcost'=>$one_ticket_cbcost,
                'date_start'=>$date_start,
                'date_end'=>$date_end,
                'price_batch_number'=>$price_batch_number,
                'ok'=>1
            );
            $resultData['message'] = "";
            if(empty($warehouse_code)){
                $warehouse_code = '';
            }
            if(empty($warehouse_id)){
                $warehouse_id = 0;
            }   
            if($warehouse_code!='全部'){
                if($warehouse_code == ""){//仓库标识
                    $existError = 1;
                    $resultData['message'] .= "仓库代码为空;";
                }else{
                    /*检查仓库代码*/
                    $warehouse = Service_Warehouse::getByField($warehouse_code,'warehouse_code');           
                    if(empty($warehouse)){
                        $resultData['message'] .= "仓库".$warehouse_code."不存在";
                        $resultData['ok'] = '0';
                        $result['data'][] = $resultData;
                        continue;
                    }
                    $warehouse_id = $warehouse['warehouse_id'];
                    $warehouse_code = $warehouse['warehouse_code'];
                }           
            }else{
                $warehouse_id = 0;
                $warehouse_code = '';
            }
            //运输代码
            if($sm_code==""){
                $existError = 1;
                $resultData['message'] .= "运输代码为空;";
            }else{          
                /*检查运输代码*/
                $condition = array(
                    'warehouse_id_arr'=>array(0,$warehouse_id),
                    'sm_code'=>$sm_code
                );
                $shippingMethod = Service_ShippingMethod::getByCondition($condition,'*');
                if(empty($shippingMethod)){
                    $resultData['message'] .= "运输代码".$sm_code."不存在";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            // 验证成本币种
            if ('' == $cost_currency_code) {
                $existError = 1;
                $resultData['message'] .= '成本币种为空';
            }else {
                $currency = Service_Currency::getByField($cost_currency_code, 'currency_code');
                if(empty($currency)) {
                    $resultData['message'] .= '币种' . $cost_currency_code . '不存在';
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //币种
            if($currency_code==""){
                $existError = 1;
                $resultData['message'] .= "币种为空;";
            }else{          
                $currency = Service_Currency::getByField($currency_code,'currency_code');
                if(empty($currency)){
                    $resultData['message'] .= "币种".$currency_code."不存在";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }           
            }
            
            //费用类型
            if($sp_fee_type_text==""){
                $existError = 1;
                $resultData['message'] .= "费用类型为空;";
            }else{                      
                if($sp_fee_type_text!='单票计费' && $sp_fee_type_text!='总单计费'){
                    $resultData['message'] .= "费用类型错误";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }else{                  
                    if($sp_fee_type_text=='单票计费'){ $sp_fee_type = 0;}
                    if($sp_fee_type_text=='总单计费')   {  $sp_fee_type = 1;}           
                }           
            }
            
            //运输区域
            if($area==""){
                $existError = 1;
                $resultData['message'] .= "运输区域为空;";
            }
            //重量
            if($sp_weight==""){
                $existError = 1;
                $resultData['message'] .= "重量为空;";
            }else{      
                if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $sp_weight)){
                    $resultData['message'] .= "重量必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }               
            }
            //价格，费用
            if($sp_price===""){
                $existError = 1;
                $resultData['message'] .= "费用为空;";
            }else{
                if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $sp_price)&&$sp_price!=0){
                    $resultData['message'] .= "费用必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }               
            }           
            //成本
            if($sp_cost===""){
                $existError = 1;
                $resultData['message'] .= "成本为空;";
            }else{
                if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $sp_cost)&&$sp_cost!=0){
                    $resultData['message'] .= "成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }               
            }           
            //单票价格
            if($sp_ticket_cost===""){
                $existError = 1;
                $resultData['message'] .= "单票价格为空;";
            }else{
                 if (! (preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/",$sp_ticket_cost) )&& $sp_ticket_cost!=0 ) {
                    $resultData['message'] .= "单票价格必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }               
            }
            //单票成本
            if($one_ticket_cbcost===""){
                $existError = 1;
                $resultData['message'] .= "单票成本为空;";
            }else{
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $one_ticket_cbcost)&&$one_ticket_cbcost!=0){
                    $resultData['message'] .= "单票成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //价格编号
            if($price_batch_number===""){
                $existError = 1;
                $resultData['message'] .= "价格编号为空;";
            }else{
                if (!ctype_digit((string)$price_batch_number)){
                    $resultData['message'] .= $price_batch_number."价格编号必须是数值类型，建议采用20140803这样的格式";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //有效开始时间
            if($date_start==""){
                $existError = 1;
                $resultData['message'] .= "报价生效日期为空;";
            }else {
                if(!preg_match($dataFormat, $date_start)){
                    $resultData['message'] .= $date_start."不是日期格式，建议格式yyyy-mm-dd";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }/*else if(strtotime($date_start) < strtotime(date('Y-m-d'))){
                    $resultData['message'] .= $date_start."必须大于当前日期".date('Y-m-d');
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }*/
            }
            //有效截止时间
            if($date_end==""){
                $existError = 1;
                $resultData['message'] .= "报价截止日期为空;";
            }else{
                if(!preg_match($dataFormat, $date_end)){
                    $resultData['message'] .= $date_end."不是日期格式，建议格式yyyy-mm-dd";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }else if(strtotime($date_end) < strtotime(date('Y-m-d'))){
                    $resultData['message'] .= $date_end."必须大于当前日期".date('Y-m-d');
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            if($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }           
            $row = array(); 
            $row['warehouse_code'] = $warehouse_code;
            $row['warehouse_id'] = $warehouse_id;
            $row['sm_code'] = $sm_code;
            $row['sm_id'] = $shippingMethod[0]['sm_id'];
            $row['cost_currency_code'] = $cost_currency_code; // 成本币种
            $row['currency_code'] = $currency_code;
            $row['sp_fee_type'] = $sp_fee_type;         
            $row['area'] = $area;   
            $row['sp_weight'] = $sp_weight;
            $row['sp_price'] = $sp_price;
            $row['sp_cost'] = $sp_cost; 
            $row['sp_ticket_cost'] = $sp_ticket_cost;
            $row['one_ticket_cbcost'] = $one_ticket_cbcost;
            $row['date_start'] = $date_start;
            $row['date_end'] = $date_end;
            $row['price_batch_number'] = $price_batch_number;
            //先插入到临时表
            $status = Service_ShipPriceTemp::add($row);
            if($status){
                $resultData['message'] = "插入临时报价表成功";
            }else{
                $resultData['message'] = "插入临时报价表失败";
            }
            $result['data'][] = $resultData;
        }//foreach
        die(json_encode($result));
    }//function end     


    /**
     * 导出
     */
    public function exportAction(){
        set_time_limit(0);
        $codes = $this->_request->getParam('codes','');     
        $exportformat = 'xls';
        $fileName = 'shipprice'.date('Y-m-d-H-i-s');    
        
        if(!empty($codes)){     //通过选择的订单获取
                    
            if($exportformat=='xls'){
                $orderHtml = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><table border="1"><tr>'; 
                $htmlTitle  = '<td>仓库</td>';
                $htmlTitle .= '<td>运输代码</td>';
                $htmlTitle .= '<td>成本币种</td>';
                $htmlTitle .= '<td>货币Code</td>';
                $htmlTitle .= '<td>费用类型</td>';
                $htmlTitle .= '<td>运输分区</td>';
                $htmlTitle .= '<td>重量（KG）</td>';
                $htmlTitle .= '<td>成本</td>';
                $htmlTitle .= '<td>费用</td>';
                $htmlTitle .= '<td>单票费用</td>';
                $htmlTitle .= '<td>单票成本</td>';
                $htmlTitle .= '<td>开始时间</td>';
                $htmlTitle .= '<td>结束时间</td>';
                $htmlTitle .= '<td>价格编号</td>';
                $htmlTitle .= '</tr>';                  
                $titlesku = '';
                $orderContent = '';
                $max = 1;               
                foreach($codes as $key=>$id){
                     $shipPrice = Service_ShipPrice::getByField($id, 'sp_id');
                     if(!$shipPrice){continue;}
                     
                     if(!$shipPrice['warehouse_code']){
                            
                        if($shipPrice['warehouse_id']){                     
                             $warehouse = Service_Warehouse::getByField($shipPrice['warehouse_id'],'warehouse_id');
                             if($warehouse){
                                $shipPrice['warehouse_code'] =  $warehouse['warehouse_code'];
                             }else{
                                $shipPrice['warehouse_code'] = '全部';
                             }
                        }else{
                            $shipPrice['warehouse_code'] = '全部';
                        }                           
                            
                     }
                     $shipPrice['sp_fee_type_text'] = Service_ShipPrice::get_sp_fee_type_text($shipPrice['sp_fee_type']); 
                     
                     $orderContent.="<tr>";                 
                     //仓库
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['warehouse_code']}</td>";
                     //运输代码
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sm_code']}</td>";
                    // 成本币种
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['cost_currency_code']}</td>";
                     //货币Code
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['currency_code']}</td>";                   
                     //费用类型
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_fee_type_text']}</td>";
                     //运输分区
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['area']}</td>";
                     //重量(KG)
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_weight']}</td>";                   
                     //成本
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_cost']}</td>";                    
                     //费用
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_price']}</td>";  
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_ticket_cost']}</td>";
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['one_ticket_cbcost']}</td>"; 
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['date_start']}</td>";
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['date_end']}</td>";
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['price_batch_number']}</td>";
                     $orderContent.="</tr>";
                }       
                $html = $orderHtml.$htmlTitle.$orderContent.'</table>';             
                header('Pragma:public');        
                header('Content-Type:application/x-msexecl;name="' . $fileName . ".{$exportformat}");
                header("Content-Disposition:inline;filename=" . $fileName . ".{$exportformat}");   
                //file_put_contents(APPLICATION_PATH . "/../data/{$fileName}",$html);
                echo $html;
                exit;
                //echo $orderHtml;exit;
                
            }elseif($exportformat=='csv'){
                
            }
                
        }else{      
                $sm_code = $this->_request->getParam('E1','');  
                $warehouse_code = $this->_request->getParam('E9','');   
                $currency_code = trim($this->_request->getParam('E5',''));                                  
                $area = $this->_request->getParam('E6','');  
                    
                $condition  = array(                    
                    'warehouse_code'=>$warehouse_code,
                    'currency_code'=>$currency_code,
                    'sm_code'=>$sm_code,
                    'area'=>$area,                              
                );
            
            $count = Service_ShipPrice::getByCondition($condition, 'count(*)');
            if($count>0){
                $pageSize = 20;
                $pages = ceil($count/20);
                $orderHtml = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><table border="1"><tr>';    
                $htmlTitle  = '<td>仓库</td>';
                $htmlTitle .= '<td>运输代码</td>';
                $htmlTitle .= '<td>成本币种</td>';
                $htmlTitle .= '<td>货币Code</td>';
                $htmlTitle .= '<td>费用类型</td>';
                $htmlTitle .= '<td>运输分区</td>';
                $htmlTitle .= '<td>重量（KG）</td>';
                $htmlTitle .= '<td>成本</td>';
                $htmlTitle .= '<td>费用</td>';
                $htmlTitle .= '<td>单票费用</td>';
                $htmlTitle .= '<td>单票成本</td>';    
                $htmlTitle .= '<td>开始时间</td>';
                $htmlTitle .= '<td>结束时间</td>';
                $htmlTitle .= '<td>价格编号</td>';
                $htmlTitle .= '</tr>';  
                $orderContent = '';
                $max = 1;

                for($page=1;$page<=$pages;$page++){
                    $rows = Service_ShipPrice::getByCondition($condition, '*', $pageSize,$page,'sp_id desc');
                    if(!$rows){continue;}
                    
                    foreach($rows as $keyo=>$shipPrice){
                    
                     $shipPrice['sp_fee_type_text'] = Service_ShipPrice::get_sp_fee_type_text($shipPrice['sp_fee_type']); 
                     
                     if(!$shipPrice['warehouse_code']){
                            
                        if($shipPrice['warehouse_id']){                     
                             $warehouse = Service_Warehouse::getByField($shipPrice['warehouse_id'],'warehouse_id');
                             if($warehouse){
                                $shipPrice['warehouse_code'] =  $warehouse['warehouse_code'];
                             }else{
                                $shipPrice['warehouse_code'] = '全部';
                             }
                        }else{
                            $shipPrice['warehouse_code'] = '全部';
                        }                           
                            
                     }
                        $orderContent.="<tr>";                  
                        //仓库
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['warehouse_code']}</td>";
                        //运输代码
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sm_code']}</td>";
                        // 成本币种
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['cost_currency_code']}</td>";
                        //货币Code
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['currency_code']}</td>";                    
                        //费用类型
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_fee_type_text']}</td>";
                        //运输分区
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['area']}</td>";
                        //重量(KG)
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_weight']}</td>";                    
                        //成本
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_cost']}</td>";                 
                        //费用
                         $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_price']}</td>";  
                         $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['sp_ticket_cost']}</td>";
                         $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['one_ticket_cbcost']}</td>"; 
                         $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['date_start']}</td>";
                         $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['date_end']}</td>";
                         $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipPrice['price_batch_number']}</td>";
                         $orderContent.="</tr>";
                    }

                }      
                echo $orderHtml.$htmlTitle.$orderContent.'</table>';         
                header('Pragma:public');        
                header('Content-Type:application/x-msexecl;name="' . $fileName . ".{$exportformat}");
                header("Content-Disposition:inline;filename=" . $fileName . ".{$exportformat}");
                
            }
        }
        exit;
    }
    /**
     * 批量删除
     */
    public function batchDeleteAction(){
        $info = "系统错误";     
        $codesArray = $this->_request->getParam('codes','');
        if(empty($codesArray) || !is_array($codesArray)){  echo "没有选择待删除记录!!!";exit; }
        Service_ShipPriceTemp::batchDelete($codesArray,'sp_id');
        $info = "已经删除";
        echo $info;
    }

    /**
     * 批量拷贝到history表
     */
    public function batchCopyToHistoryAction(){
        $info = "系统错误";     
        $codesArray = $this->_request->getParam('codes','');
        if(empty($codesArray) || !is_array($codesArray)){  echo "没有选择待拷贝的记录!!!";exit; }
        Service_ShipPriceTemp::batchCopyToHistory($codesArray,'sp_id');
        $info = "已经拷贝";
        echo $info;
    }

    public function customerPriceListAction()
    {
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();
            $obj = new Service_ShipCustomerPriceTemp();
            $condition = $obj->getMatchFields($params);
            unset($params);
            $count = Service_ShipCustomerPriceTemp::getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    'scpt_id',
                    'warehouse_id',
                    'sm_code',
                    'area',
                    'scp_weight',
                    'scp_price',
                    'scp_cost',
                    'currency_code',
                    'scp_fee_type',
                    'sm_id',
                    'scp_ticket_cost',
                    'cost_currency_code',
                    'one_ticket_cbcost',
                    'price_batch_number',
                    'date_start',
                    'date_end',
                    'customer_code',
                );
                $showFields = $obj->getFieldsAlias($showFields);
                $rows = Service_ShipCustomerPriceTemp::getByCondition($condition,$showFields, $pageSize, $page, array('date_start desc', 'scpt_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $warehouse = Common_DataCache::getWarehouseSimple();
        $currency = Common_DataCache::getCurrency();
        $type = Common_Type::SMFeeType('auto');
        $this->view->currency = $currency;
        $this->view->type = $type;
        //$this->view->SM=Common_DataCache::getShippingMethodSimple();
        $sm = Service_ShippingMethod::getAll();
        $sm = Common_Common::multisort($sm);
        $this->view->SM = $sm;
        $this->view->warehouse = $warehouse;
        echo Ec::renderTpl($this->tplDirectory . "customer_price_temp_index.tpl", 'layout');
    }

    /**
     * 编辑
     */
    public function customerPriceEditAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'scpt_id' => '',
                'sm_code' => '',
                'scp_weight' => '',
                'sm_id' => '',
                'scp_cost' => '',
                'scp_price' => '',
                'currency_code' => '',
                'area' => '',
                'scp_fee_type' => '',
                'warehouse_id' => '',
                'scp_ticket_cost' => '',
                'cost_currency_code' => '', // 成本币种
                'one_ticket_cbcost' => '',
                'date_start' => '',
                'date_end' => '',
                'customer_code'=>'',
                'price_batch_number'=>'',
            );
            $obj = new Service_ShipCustomerPriceTemp();
            $row = $obj->getMatchEditFields($params, $row);
            unset($params);
            $paramId = $row['scpt_id'];
            if (!empty($row['scpt_id'])) {
                unset($row['scpt_id']);
            }
            $smRow = Service_ShippingMethod::getByField($row['sm_id'], 'sm_id');
            $row['sm_id']=$smRow['sm_id'];
            $row['sm_code'] = $smRow['sm_code'];
            unset($smRow);
            $errorArr = $obj->validator($row);
            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }
            if (!empty($paramId)) {
                unset($row['price_batch_number']); /* price_batch_number 不允许修改 */
                unset($row['customer_code']); /* 客户代码 不允许修改 */
                $result = Service_ShipCustomerPriceTemp::update($row, $paramId);
            } else {
                $result = Service_ShipCustomerPriceTemp::add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }
        }
        die(Zend_Json::encode($return));
    }

    /**
     * 批量导入运输区域模板
     */
    public function batchImportCpTemplateAction(){
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH.'/../data/xls/ship_customer_price_batch_import.xls';
        //方法2
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        //  header("Content-Transfer-Encoding: binary");
        //  header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

    /**
     * 批量导入运输价格
     */
    public function batchImportCustomerPriceAction(){
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_SmCustomerMap::getXLSData($_FILES,'filename');
        if(count($xlsData[0])!=15 ||$xlsData[0][0]!="仓库"||$xlsData[0][1]!="运输代码"||$xlsData[0][2]!="成本币种"||$xlsData[0][3]!="货币Code"||$xlsData[0][4]!="费用类型"||$xlsData[0][5]!="运输分区"||$xlsData[0][6]!="重量（KG）"|| $xlsData[0][7]!="成本"|| $xlsData[0][8]!="费用" || $xlsData[0][9]!="单票费用"||$xlsData[0][10]!="单票成本"||$xlsData[0][11]!="开始时间"||$xlsData[0][12]!="结束时间"||$xlsData[0][13]!="价格编号" || $xlsData[0][14]!="客户代码"){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照仓库,运输代码,成本币种,货币Code,费用类型,运输分区,重量（KG）,成本,费用,单票费用,单票成本,开始时间,结束时间,价格编号,客户代码排列!";
            die(json_encode($result));
        }
        $dataFormat = '/^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/';
        foreach($xlsData as $key=>$value){
            if($key==0) continue;
            $existError = 0;
            //仓库代码
            $warehouse_code = $value[0];
            //运输方式代码
            $sm_code = $value[1];
            // 成本币种
            $cost_currency_code = $value[2];
            //币种
            $currency_code = $value[3];
            //费用类型
            $sp_fee_type_text = $value[4];
            //收费分区
            $area = $value[5];
            //重量
            $sp_weight = $value[6];
            //成本
            $sp_cost = $value[7];
            //费用
            $sp_price = $value[8];
            //费用
            $sp_ticket_cost = $value[9];
            //单票成本
            $one_ticket_cbcost = $value[10];
            $date_start = $value[11];

            if(preg_match('/^\d{5}$/',$date_start)){
                $date_start = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_start));
            }
            $date_end = $value[12];
            if(preg_match('/^\d{5}$/',$date_end)){
                $date_end = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_end));
            }
            $start=explode(" ", $date_start);
            $date_start=$start[0];
            $end=explode(" ", $date_end);
            $date_end=$end[0];
            //价格编号
            $price_batch_number = $value[13];
            $customerCode = $value[14];
            $resultData = array(
                'warehouse_code'=>$warehouse_code,
                'sm_code'=>$sm_code,
                'currency_code'=>$currency_code,
                'cost_currency_code' => $cost_currency_code,
                'scp_fee_type_text'=>$sp_fee_type_text,
                'area'=>$area,
                'scp_weight'=>$sp_weight,
                'scp_cost'=>$sp_cost,
                'scp_price'=>$sp_price,
                'scp_ticket_cost'=>$sp_ticket_cost,
                'one_ticket_cbcost'=>$one_ticket_cbcost,
                'date_start'=>$date_start,
                'date_end'=>$date_end,
                'price_batch_number'=>$price_batch_number,
                'customer_code' => $customerCode,
                'ok'=>1
            );
            $resultData['message'] = "";
            if(empty($warehouse_code)){
                $warehouse_code = '';
            }
            if(empty($warehouse_id)){
                $warehouse_id = 0;
            }
            if($warehouse_code!='全部'){
                if($warehouse_code == ""){//仓库标识
                    $existError = 1;
                    $resultData['message'] .= "仓库代码为空;";
                }else{
                    /*检查仓库代码*/
                    $warehouse = Service_Warehouse::getByField($warehouse_code,'warehouse_code');
                    if(empty($warehouse)){
                        $resultData['message'] .= "仓库".$warehouse_code."不存在";
                        $resultData['ok'] = '0';
                        $result['data'][] = $resultData;
                        continue;
                    }
                    $warehouse_id = $warehouse['warehouse_id'];
                    $warehouse_code = $warehouse['warehouse_code'];
                }
            }else{
                $warehouse_id = 0;
                $warehouse_code = '';
            }
            //运输代码
            if($sm_code==""){
                $existError = 1;
                $resultData['message'] .= "运输代码为空;";
            }else{
                /*检查运输代码*/
                $condition = array(
                    'warehouse_id_arr'=>array(0,$warehouse_id),
                    'sm_code'=>$sm_code
                );
                $shippingMethod = Service_ShippingMethod::getByCondition($condition,'*');
                if(empty($shippingMethod)){
                    $resultData['message'] .= "运输代码".$sm_code."不存在";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            // 验证成本币种
            if ('' == $cost_currency_code) {
                $existError = 1;
                $resultData['message'] .= '成本币种为空';
            }else {
                $currency = Service_Currency::getByField($cost_currency_code, 'currency_code');
                if(empty($currency)) {
                    $resultData['message'] .= '币种' . $cost_currency_code . '不存在';
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //币种
            if($currency_code==""){
                $existError = 1;
                $resultData['message'] .= "币种为空;";
            }else{
                $currency = Service_Currency::getByField($currency_code,'currency_code');
                if(empty($currency)){
                    $resultData['message'] .= "币种".$currency_code."不存在";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }

            //费用类型
            if($sp_fee_type_text==""){
                $existError = 1;
                $resultData['message'] .= "费用类型为空;";
            }else{
                if($sp_fee_type_text!='单票计费' && $sp_fee_type_text!='总单计费'){
                    $resultData['message'] .= "费用类型错误";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }else{
                    if($sp_fee_type_text=='单票计费'){ $sp_fee_type = 0;}
                    if($sp_fee_type_text=='总单计费')   {  $sp_fee_type = 1;}
                }
            }

            //运输区域
            if($area==""){
                $existError = 1;
                $resultData['message'] .= "运输区域为空;";
            }
            //重量
            if($sp_weight===""){
                $existError = 1;
                $resultData['message'] .= "重量为空;";
            }else{
                if (!is_numeric( $sp_weight ) || 0 >= floatval( $sp_weight ) ){
                    $resultData['message'] .= "重量必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //价格，费用
            if($sp_price===""){
                $existError = 1;
                $resultData['message'] .= "费用为空;";
            }else{
                if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $sp_price)&&$sp_price!=0){
                    $resultData['message'] .= "费用必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //成本
            if($sp_cost===""){
                $existError = 1;
                $resultData['message'] .= "成本为空;";
            }else{
                if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $sp_cost)&&$sp_cost!=0){
                    $resultData['message'] .= "成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //单票价格
            if($sp_ticket_cost===""){
                $existError = 1;
                $resultData['message'] .= "单票价格为空;";
            }else{
                if (! (preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/",$sp_ticket_cost) )&& $sp_ticket_cost!=0 ) {
                    $resultData['message'] .= "单票价格必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //单票成本
            if($one_ticket_cbcost===""){
                $existError = 1;
                $resultData['message'] .= "单票成本为空;";
            }else{
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $one_ticket_cbcost)&&$one_ticket_cbcost!=0){
                    $resultData['message'] .= "单票成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //价格编号
            if($price_batch_number===""){
                $existError = 1;
                $resultData['message'] .= "价格编号为空;";
            }else{
                if (!ctype_digit((string)$price_batch_number)){
                    $resultData['message'] .= $price_batch_number."价格编号必须是数值类型，建议采用20140803这样的格式";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //有效开始时间
            if($date_start==""){
                $existError = 1;
                $resultData['message'] .= "报价生效日期为空;";
            }else {
                if(!preg_match($dataFormat, $date_start)){
                    $resultData['message'] .= $date_start."不是日期格式，建议格式yyyy-mm-dd";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }/*else if(strtotime($date_start) < strtotime(date('Y-m-d'))){
                    $resultData['message'] .= $date_start."必须大于当前日期".date('Y-m-d');
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }*/
            }
            //有效截止时间
            if($date_end==""){
                $existError = 1;
                $resultData['message'] .= "报价截止日期为空;";
            }else{
                if(!preg_match($dataFormat, $date_end)){
                    $resultData['message'] .= $date_end."不是日期格式，建议格式yyyy-mm-dd";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }else if(strtotime($date_end) < strtotime(date('Y-m-d'))){
                    $resultData['message'] .= $date_end."必须大于当前日期".date('Y-m-d');
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            if( empty( $customerCode ) ) {
                $resultData['message'] .= "客户代码不能为空";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            } else {
                $customer = Service_Customer::getByField($customerCode,'customer_code');
                if(empty($customer)){
                    $resultData['message'] .= "客户代码".$customerCode."不存在";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            if($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $row = array();
            $row['warehouse_id'] = $warehouse_id;
            $row['sm_code'] = $sm_code;
            $row['sm_id'] = $shippingMethod[0]['sm_id'];
            $row['cost_currency_code'] = $cost_currency_code; // 成本币种
            $row['currency_code'] = $currency_code;
            $row['scp_fee_type'] = $sp_fee_type;
            $row['area'] = $area;
            $row['scp_weight'] = $sp_weight;
            $row['scp_price'] = $sp_price;
            $row['scp_cost'] = $sp_cost;
            $row['scp_ticket_cost'] = $sp_ticket_cost;
            $row['one_ticket_cbcost'] = $one_ticket_cbcost;
            $row['date_start'] = $date_start;
            $row['date_end'] = $date_end;
            $row['price_batch_number'] = $price_batch_number;
            $row['customer_code'] = $customerCode;
            //先插入到临时表
            $status = Service_ShipCustomerPriceTemp::add($row);
            if($status){
                $resultData['message'] = "插入临时报价表成功";
            }else{
                $resultData['message'] = "插入临时报价表失败";
            }
            $result['data'][] = $resultData;
        }//foreach
        die(json_encode($result));
    }//function end


    /**
     * 编辑获取数据
     */
    public function customerPriceGetByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = Service_ShipCustomerPriceTemp::getByField($paramId, 'scpt_id')) {
            $obj = new Service_ShipCustomerPriceTemp();
            $rows = $obj->getVirtualFields( $rows );
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    /**
     * 删除
     */
    public function customerPriceDeleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if (Service_ShipCustomerPriceTemp::delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * 批量删除
     */
    public function batchDeleteCustomerPriceAction(){
        $info = "系统错误";
        $codesArray = $this->_request->getParam('codes','');
        if(empty($codesArray) || !is_array($codesArray)){  echo "没有选择待删除记录!!!";exit; }
        Service_ShipCustomerPriceTemp::batchDelete($codesArray,'scpt_id');
        $info = "已经删除";
        echo $info;
    }
    
    
}