<?php
class Ship_WeightTempController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "ship/views/";
        $this->serviceClass = new Service_ShipWeightPriceTemp();
    }
	/**
	 * 列表
	 * (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(
					'swp_weight',
	                'swp_exces_weight',
	                'swp_cost',
	                'swp_exces_cost',
	                'currency_code',
	                'swp_price',
	                'swp_exces_price',
	                'area',
	                'sm_code',
	                'swp_fee_type',
	                'warehouse_id',
	                'swp_id',
	                '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', 'swp_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['type'] = $type;
                $return['warehouse'] =$warehouse;
            }
            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 . "weight_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(
					'swp_id' => '',
					'swp_weight' => '',
					'swp_exces_weight' => '',
					'swp_cost' => '',
					'swp_exces_cost' => '',
					'currency_code' => '',
					'area' => '',
					'sm_code' => '',
					'sm_id' => '',
					'swp_fee_type' => '',
					'warehouse_id' => '',
					'swp_price' => '',
					'swp_exces_price' => '',
					'one_ticket_fee' => '',
					'cost_currency_code' => '', // 成本币种
					'one_ticket_cbcost' => '',
					'price_batch_number' => '',
	            	'date_start' => '',
            		'date_end' => ''
            );
            $row = $this->serviceClass->getMatchEditFields($params,$row);
            unset($params);
            $paramId = $row['swp_id'];
            if (!empty($row['swp_id'])) {
                unset($row['swp_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));
            }
            if (!empty($paramId)) {
                unset($row['price_batch_number']); /* price_batch_number 不允许修改 */
                $result = $this->serviceClass->update($row, $paramId);
			//	$result1 = $this->serviceHistoryClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
                //插入的时候自增长id无法保持一致，改在批量拷贝处进行处理
                //$result1 = $this->serviceHistoryClass->add($row);
            }
            $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, 'swp_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_weight_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])!=17 || ($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]!="续重（KG）"||$xlsData[0][8]!="首重价格"||$xlsData[0][9]!="续重价格"|| $xlsData[0][10]!="首重成本"|| $xlsData[0][11]!="续重成本" || $xlsData[0][12]!="单票费用"|| $xlsData[0][13]!="单票成本"||$xlsData[0][14]!="开始时间"||$xlsData[0][15]!="结束时间"||$xlsData[0][16]!="价格编号")){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照仓库,运输代码,成本币种,货币Code,费用类型,运输分区,首重（KG）,续重（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];
			//首重（KG）
			$swp_weight = $value[6];
			//续重（KG）
			$swp_exces_weight = $value[7];
			//首重价格
			$swp_price = $value[8];
			//续重价格
			$swp_exces_price = $value[9];
			//首重成本
			$swp_cost = $value[10];
			//续重成本
			$swp_exces_cost =  $value[11];	
			//单票费用
			$one_ticket_fee =  $value[12];
			//单票成本
            $one_ticket_cbcost = $value[13];
            //有效开始时间
            $date_start=$value[14];
            if(preg_match('/^\d{5}$/',$date_start)){
                	$date_start = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_start));
            }
            //有效结束时间
            $date_end = $value[15];
            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[16];
            
            $resultData = array(
					'warehouse_code'=>$warehouse_code,
					'sm_code'=>$sm_code,
					'cost_currency_code' => $cost_currency_code, // 成本币种
					'currency_code'=>$currency_code,
					'sp_fee_type_text'=>$sp_fee_type_text,
					'area'=>$area,
					'swp_weight'=>$swp_weight,
					'swp_exces_weight'=>$swp_exces_weight,
					'swp_price'=>$swp_price,
					'swp_exces_price'=>$swp_exces_price,
					'swp_cost'=>$swp_cost,
					'swp_exces_cost'=>$swp_exces_cost,
					'one_ticket_fee'=>$one_ticket_fee,
	                '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($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;
					}else{
						$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=='单票计费'){ $swp_fee_type = 0;}
					if($sp_fee_type_text=='总单计费')	{  $swp_fee_type = 1;}			
				}		
			}
			//运输区域
            if($area==""){
                $existError = 1;
                $resultData['message'] .= "运输区域为空;";
            }
            //首重（KG）
            if($swp_weight==""){
                $existError = 1;
                $resultData['message'] .= "首重为空;";
            }else {
        		if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_weight)){
					$resultData['message'] .= "首重必须是不小于0的数值";
					$resultData['ok'] = '0';
					$result['data'][] = $resultData;
					continue;
            	}			
			}
			//续重（KG）
            if($swp_exces_weight==""){
                $existError = 1;
                $resultData['message'] .= "续重为空;";
            }else {		
        		if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_exces_weight)){
					$resultData['message'] .= "续重必须是不小于0的数值";
					$resultData['ok'] = '0';
					$result['data'][] = $resultData;
                    continue;
            	}				
			}
			//首重价格
            if($swp_price===""){
                $existError = 1;
                $resultData['message'] .= "首重价格为空;";
            }else {		
        		if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_price)&&$swp_price!=0){
					$resultData['message'] .= "首重价格必须是0或者不小于0的数值";
					$resultData['ok'] = '0';
					$result['data'][] = $resultData;
					continue;
            	}			
			}	
			//续重价格
            if($swp_exces_price===""){
                $existError = 1;
                $resultData['message'] .= "续重价格为空;";
            }else {	
        		if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_exces_price)&&$swp_exces_price!=0){
                    $resultData['message'] .= "续重价格必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
            	}
			}	
			//首重成本
            if($swp_cost===""){
                $existError = 1;
                $resultData['message'] .= "首重成本为空;";
            }else {
				 if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_cost)&&$swp_cost!=0) {
                    $resultData['message'] .= "首重成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue; 
				 }
        		/*
				if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $swp_cost)){
                    $resultData['message'] .= "首重成本必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
            	}
				*/				
			}
			//续重成本
            if($swp_exces_cost===""){
                $existError = 1;
                $resultData['message'] .= "续重成本为空;";
            }else {
				 if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_exces_cost)&&$swp_exces_cost!=0) {
                    $resultData['message'] .= "首重成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue; 
				 }	
				 /*		
        		if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $swp_exces_cost)){
                    $resultData['message'] .= "续重成本必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
            	}	
				*/			
			}
			//单票费用
            if($one_ticket_fee===""){
                $existError = 1;
                $resultData['message'] .= "单票费用为空;";
            }else {
        		if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $one_ticket_fee)&&$one_ticket_fee!=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;
            	}
            }
			
            //有效截止时间
            if($date_end==""){
            	$existError = 1;
            	$resultData['message'] .= "报价截止日期为空;";
            }else {
            	if(!preg_match($dataFormat, $date_end)){
            		$resultData['message'] .= $date_start."不是日期格式，建议格式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['swp_fee_type'] = $swp_fee_type;			
			$row['area'] = $area;	
			$row['swp_weight'] = $swp_weight;
			$row['swp_exces_weight'] = $swp_exces_weight;
			$row['swp_price'] = $swp_price;
			$row['swp_exces_price'] = $swp_exces_price;			
			$row['swp_cost'] = $swp_cost;
			$row['swp_exces_cost'] = $swp_exces_cost;	
			$row['one_ticket_fee'] = $one_ticket_fee;
            $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_ShipWeightPriceTemp::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 = 'shipweght'.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>续重(KG)</td>';
				$htmlTitle .= '<td>首重价格</td>';
				$htmlTitle .= '<td>续重价格</td>';
				$htmlTitle .= '<td>首重成本</td>';
				$htmlTitle .= '<td>续重成本</td>';
				$htmlTitle .= '<td>单票费用</td>';
                $htmlTitle .= '<td>单票成本</td>';
				$htmlTitle .= '<td>开始时间</td>';
				$htmlTitle .= '<td>结束时间</td>';
                $htmlTitle .= '<td>价格编号</td>';
				$htmlTitle .= '</tr>';					
    			$titlesku = '';
    			$orderContent = '';
    			$max = 1;				
    			foreach($codes as $key=>$id){
    				 $shipWeight = Service_ShipWeightPrice::getByField($id, 'swp_id');
					 if(!$shipWeight){continue;}
					 
					 $shipWeight['swp_fee_type_text'] = Service_ShipWeightPrice::get_sp_fee_type_text($shipWeight['swp_fee_type']);
					 
					 if(!$shipWeight['warehouse_code']){
					 	if($shipWeight['warehouse_id']){						
							 $warehouse = Service_Warehouse::getByField($shipWeight['warehouse_id'],'warehouse_id');
							 if($warehouse){
							 	$shipWeight['warehouse_code'] =  $warehouse['warehouse_code'];
							 }else{
							 	$shipWeight['warehouse_code'] = '全部';
							 }
						}else{
							$shipWeight['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:@;'>{$shipWeight['warehouse_code']}</td>";
					 //运输代码
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['sm_code']}</td>";
		           	// 成本币种
		           $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['cost_currency_code']}</td>";
					 //货币Code
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['currency_code']}</td>";					 
					 //费用类型
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_fee_type_text']}</td>";
					 //运输分区
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['area']}</td>";
					 //首重
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_weight']}</td>";					 
					 //续重
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_exces_weight']}</td>";    				 
					 //首重价格
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_price']}</td>";					 
					 //续重价格 
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_exces_price']}</td>";						    				 
					 //首重成本
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_cost']}</td>";					 
					 //续重成本 
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_exces_cost']}</td>";						 
					 //单票费用 
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['one_ticket_fee']}</td>";
                      $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['one_ticket_cbcost']}</td>";	
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['date_start']}</td>";
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['date_end']}</td>";
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['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('E7','');	
				$warehouse_id = $this->_request->getParam('E10',''); 	
				$currency_code = trim($this->_request->getParam('E5','')); 									
				$area = $this->_request->getParam('E6','');  
        		$condition	= array(            		
					'warehouse_id'=>$warehouse_id,
					'currency_code'=>$currency_code,
					'sm_code'=>$sm_code,
					'area'=>$area,								
        		);
    		$count = Service_ShipWeightPrice::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>续重（KG）</td>';
				$htmlTitle .= '<td>首重价格</td>';
				$htmlTitle .= '<td>续重价格</td>';
				$htmlTitle .= '<td>首重成本</td>';
				$htmlTitle .= '<td>续重成本</td>';
    			$htmlTitle .= '<td>单票费用</td>';
    			$htmlTitle .= '<td>单票成本</td>';
                $htmlTitle .= '<td>开始时间</td>';
                $htmlTitle .= '<td>结束时间</td>';
                $htmlTitle .= '<td>价格编号</td>';
				$htmlTitle .= '</tr>';	
    			$orderContent = '';
    			$max = 1;
    			for($page=1;$page<=$pages;$page++){
    				$rows = Service_ShipWeightPrice::getByCondition($condition, '*', $pageSize,$page,'swp_id desc');
					if(!$rows){continue;}
					
    				foreach($rows as $keyo=>&$row){
					
					 $row['swp_fee_type_text'] = Service_ShipWeightPrice::get_sp_fee_type_text($row['swp_fee_type']);
					 
					 if(!$row['warehouse_code']){
					 	if($row['warehouse_id']){						
							 $warehouse = Service_Warehouse::getByField($row['warehouse_id'],'warehouse_id');
							 if($warehouse){
							 	$row['warehouse_code'] =  $warehouse['warehouse_code'];
							 }else{
							 	$row['warehouse_code'] = '全部';
							 }
						}else{
							$row['warehouse_code'] = '全部';
						}
					 }
					 
						$orderContent.="<tr>";					
						//仓库
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['warehouse_code']}</td>";
						//运输代码
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['sm_code']}</td>";
						// 成本币种
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['cost_currency_code']}</td>";
						//货币Code
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['currency_code']}</td>";					 
						//费用类型
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_fee_type_text']}</td>";
						//运输分区
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['area']}</td>";
						//首重
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_weight']}</td>";					 
						//续重
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_exces_weight']}</td>";    				 
						//首重价格
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_price']}</td>";					 
						//续重价格 
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_exces_price']}</td>";						    				 
						//首重成本
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_cost']}</td>";					 
						//续重成本 
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_exces_cost']}</td>";						 
						//单票费用 
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['one_ticket_fee']}</td>";
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['one_ticket_cbcost']}</td>";    
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['date_start']}</td>";
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['date_end']}</td>";
                     $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['price_batch_number']}</td>";
						$orderContent.="</tr>";
    				}

    			}   			
    	        header('Pragma:public');		
    			header('Content-Type:application/x-msexecl;name="' . $fileName . ".{$exportformat}");
    	        header("Content-Disposition:inline;filename=" . $fileName . ".{$exportformat}");
    			echo $orderHtml.$htmlTitle.$orderContent.'</table>';
    		}
    	}
    	exit;
    } 
	/**
	 * 批量删除
	 */
	public function batchDeleteAction(){
		$info = "系统错误";		
		$codesArray = $this->_request->getParam('codes','');
		if(empty($codesArray) || !is_array($codesArray)){  echo "没有选择待删除记录!!!";exit; }
		Service_ShipWeightPriceTemp::batchDelete($codesArray,'swp_id');
		$info = "已经删除";
		echo $info;
	}  
    /**
     * 批量拷贝到history表
     */
	public function batchCopyToHistoryAction(){
		$info = "系统错误";		
		$codesArray = $this->_request->getParam('codes','');
		if(empty($codesArray) || !is_array($codesArray)){  echo "没有选择待拷贝的记录!!!";exit; }
		Service_ShipWeightPrice::batchCopyToHistory($codesArray,'swp_id');
		$info = "已经拷贝";
		echo $info;
	}

    /**
     * 列表
     * (non-PHPdoc)
     * @see Ec_Controller_Action::listAction()
     */
    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_ShipCustomerWeightPriceTemp();

            $condition = $obj->getMatchFields($params);
            unset($params);
            $count = Service_ShipCustomerWeightPriceTemp::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count) {
                $showFields=array(
                    'scwpt_id',
                    'scwp_weight',
                    'scwp_exces_weight',
                    'scwp_cost',
                    'scwp_exces_cost',
                    'currency_code',
                    'scwp_price',
                    'scwp_exces_price',
                    'area',
                    'sm_code',
                    'scwp_fee_type',
                    'warehouse_id',
                    'one_ticket_cbcost',
                    'price_batch_number',
                    'date_start',
                    'date_end',
                    'customer_code'
                );
                $showFields = $obj->getFieldsAlias($showFields);
                $rows = Service_ShipCustomerWeightPriceTemp::getByCondition($condition,$showFields, $pageSize, $page, array('date_start desc', 'scwpt_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }

        $currency=Common_DataCache::getCurrency();
        $type=Common_Type::SMFeeType('auto');
        $warehouse=Common_DataCache::getWarehouseSimple();

        $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_weight_temp_index.tpl", 'layout');
    }

    /**
     * 导出
     */
    public function exportCustomerPriceAction(){
        set_time_limit(0);
        $codes = $this->_request->getParam('codes','');
        $exportformat = 'xls';
        $fileName = 'shipweght'.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>续重(KG)</td>';
                $htmlTitle .= '<td>首重价格</td>';
                $htmlTitle .= '<td>续重价格</td>';
                $htmlTitle .= '<td>首重成本</td>';
                $htmlTitle .= '<td>续重成本</td>';
                $htmlTitle .= '<td>单票费用</td>';
                $htmlTitle .= '<td>单票成本</td>';
                $htmlTitle .= '<td>开始时间</td>';
                $htmlTitle .= '<td>结束时间</td>';
                $htmlTitle .= '<td>价格编号</td>';
                $htmlTitle .= '</tr>';
                $titlesku = '';
                $orderContent = '';
                $max = 1;
                foreach($codes as $key=>$id){
                    $shipWeight = Service_ShipWeightPrice::getByField($id, 'swp_id');
                    if(!$shipWeight){continue;}

                    $shipWeight['swp_fee_type_text'] = Service_ShipWeightPrice::get_sp_fee_type_text($shipWeight['swp_fee_type']);

                    if(!$shipWeight['warehouse_code']){
                        if($shipWeight['warehouse_id']){
                            $warehouse = Service_Warehouse::getByField($shipWeight['warehouse_id'],'warehouse_id');
                            if($warehouse){
                                $shipWeight['warehouse_code'] =  $warehouse['warehouse_code'];
                            }else{
                                $shipWeight['warehouse_code'] = '全部';
                            }
                        }else{
                            $shipWeight['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:@;'>{$shipWeight['warehouse_code']}</td>";
                    //运输代码
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['sm_code']}</td>";
                    // 成本币种
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['cost_currency_code']}</td>";
                    //货币Code
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['currency_code']}</td>";
                    //费用类型
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_fee_type_text']}</td>";
                    //运输分区
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['area']}</td>";
                    //首重
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_weight']}</td>";
                    //续重
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_exces_weight']}</td>";
                    //首重价格
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_price']}</td>";
                    //续重价格
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_exces_price']}</td>";
                    //首重成本
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_cost']}</td>";
                    //续重成本
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['swp_exces_cost']}</td>";
                    //单票费用
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['one_ticket_fee']}</td>";
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['one_ticket_cbcost']}</td>";
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['date_start']}</td>";
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['date_end']}</td>";
                    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$shipWeight['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('E7','');
            $warehouse_id = $this->_request->getParam('E10','');
            $currency_code = trim($this->_request->getParam('E5',''));
            $area = $this->_request->getParam('E6','');
            $condition	= array(
                'warehouse_id'=>$warehouse_id,
                'currency_code'=>$currency_code,
                'sm_code'=>$sm_code,
                'area'=>$area,
            );
            $count = Service_ShipWeightPrice::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>续重（KG）</td>';
                $htmlTitle .= '<td>首重价格</td>';
                $htmlTitle .= '<td>续重价格</td>';
                $htmlTitle .= '<td>首重成本</td>';
                $htmlTitle .= '<td>续重成本</td>';
                $htmlTitle .= '<td>单票费用</td>';
                $htmlTitle .= '<td>单票成本</td>';
                $htmlTitle .= '<td>开始时间</td>';
                $htmlTitle .= '<td>结束时间</td>';
                $htmlTitle .= '<td>价格编号</td>';
                $htmlTitle .= '</tr>';
                $orderContent = '';
                $max = 1;
                for($page=1;$page<=$pages;$page++){
                    $rows = Service_ShipWeightPrice::getByCondition($condition, '*', $pageSize,$page,'swp_id desc');
                    if(!$rows){continue;}

                    foreach($rows as $keyo=>&$row){

                        $row['swp_fee_type_text'] = Service_ShipWeightPrice::get_sp_fee_type_text($row['swp_fee_type']);

                        if(!$row['warehouse_code']){
                            if($row['warehouse_id']){
                                $warehouse = Service_Warehouse::getByField($row['warehouse_id'],'warehouse_id');
                                if($warehouse){
                                    $row['warehouse_code'] =  $warehouse['warehouse_code'];
                                }else{
                                    $row['warehouse_code'] = '全部';
                                }
                            }else{
                                $row['warehouse_code'] = '全部';
                            }
                        }

                        $orderContent.="<tr>";
                        //仓库
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['warehouse_code']}</td>";
                        //运输代码
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['sm_code']}</td>";
                        // 成本币种
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['cost_currency_code']}</td>";
                        //货币Code
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['currency_code']}</td>";
                        //费用类型
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_fee_type_text']}</td>";
                        //运输分区
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['area']}</td>";
                        //首重
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_weight']}</td>";
                        //续重
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_exces_weight']}</td>";
                        //首重价格
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_price']}</td>";
                        //续重价格
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_exces_price']}</td>";
                        //首重成本
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_cost']}</td>";
                        //续重成本
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['swp_exces_cost']}</td>";
                        //单票费用
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['one_ticket_fee']}</td>";
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['one_ticket_cbcost']}</td>";
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['date_start']}</td>";
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['date_end']}</td>";
                        $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$row['price_batch_number']}</td>";
                        $orderContent.="</tr>";
                    }

                }
                header('Pragma:public');
                header('Content-Type:application/x-msexecl;name="' . $fileName . ".{$exportformat}");
                header("Content-Disposition:inline;filename=" . $fileName . ".{$exportformat}");
                echo $orderHtml.$htmlTitle.$orderContent.'</table>';
            }
        }
        exit;
    }

    /**
     * 编辑获取数据
     */
    public function customerPriceGetByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = Service_ShipCustomerWeightPriceTemp::getByField($paramId, 'scwpt_id')) {
            $obj = new Service_ShipCustomerWeightPriceTemp();
            $rows = $obj->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    /**
     * 编辑
     */
    public function customerPriceEditAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'scwpt_id' => '',
                'scwp_weight' => '',
                'scwp_exces_weight' => '',
                'scwp_cost' => '',
                'scwp_exces_cost' => '',
                'currency_code' => '',
                'area' => '',
                'sm_code' => '',
                'sm_id' => '',
                'scwp_fee_type' => '',
                'warehouse_id' => '',
                'scwp_price' => '',
                'scwp_exces_price' => '',
                'one_ticket_fee' => '',
                'cost_currency_code' => '', // 成本币种
                'one_ticket_cbcost' => '',
                'price_batch_number' => '',
                'date_start' => '',
                'date_end' => '',
                'customer_code'=>'',
            );
            $obj = new Service_ShipCustomerWeightPriceTemp();
            $row = $obj->getMatchEditFields($params,$row);
            unset($params);
            $paramId = $row['scwpt_id'];
            if (!empty($row['scwpt_id'])) {
                unset($row['scwpt_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']); /* customer_code 不允许修改 */
                $result = Service_ShipCustomerWeightPriceTemp::update($row, $paramId);
                //	$result1 = $this->serviceHistoryClass->update($row, $paramId);
            } else {
                $result = Service_ShipCustomerWeightPriceTemp::add($row);
                //插入的时候自增长id无法保持一致，改在批量拷贝处进行处理
                //$result1 = $this->serviceHistoryClass->add($row);
            }
            $return['state'] = 1;
            $return['message'] = array('Success.');
        }
        die(Zend_Json::encode($return));
    }

    /**
     * 删除
     */
    public function customerPriceDeleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if (Service_ShipCustomerWeightPriceTemp::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_ShipCustomerWeightPriceTemp::batchDelete($codesArray,'scwpt_id');
        $info = "已经删除";
        echo $info;
    }

    /**
     * 批量导入运输区域模板
     */
    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_weight_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);

        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_SmCustomerMap::getXLSData($_FILES, 'filename');
        if( count($xlsData[0])!=18 || ($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]!="续重（KG）"||$xlsData[0][8]!="首重价格"||$xlsData[0][9]!="续重价格"|| $xlsData[0][10]!="首重成本"|| $xlsData[0][11]!="续重成本" || $xlsData[0][12]!="单票费用"|| $xlsData[0][13]!="单票成本"||$xlsData[0][14]!="开始时间"||$xlsData[0][15]!="结束时间"||$xlsData[0][16]!="价格编号" || $xlsData[0][17] != "客户代码")){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照仓库,运输代码,成本币种,货币Code,费用类型,运输分区,首重（KG）,续重（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];
            //首重（KG）
            $swp_weight = $value[6];
            //续重（KG）
            $swp_exces_weight = $value[7];
            //首重价格
            $swp_price = $value[8];
            //续重价格
            $swp_exces_price = $value[9];
            //首重成本
            $swp_cost = $value[10];
            //续重成本
            $swp_exces_cost =  $value[11];
            //单票费用
            $one_ticket_fee =  $value[12];
            //单票成本
            $one_ticket_cbcost = $value[13];
            //有效开始时间
            $date_start=$value[14];
            if(preg_match('/^\d{5}$/',$date_start)){
                $date_start = gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($date_start));
            }
            //有效结束时间
            $date_end = $value[15];
            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[16];
            $customerCode = $value[17];

            $resultData = array(
                'warehouse_code'=>$warehouse_code,
                'sm_code'=>$sm_code,
                'cost_currency_code' => $cost_currency_code, // 成本币种
                'currency_code'=>$currency_code,
                'sp_fee_type_text'=>$sp_fee_type_text,
                'area'=>$area,
                'swp_weight'=>$swp_weight,
                'swp_exces_weight'=>$swp_exces_weight,
                'swp_price'=>$swp_price,
                'swp_exces_price'=>$swp_exces_price,
                'swp_cost'=>$swp_cost,
                'swp_exces_cost'=>$swp_exces_cost,
                'one_ticket_fee'=>$one_ticket_fee,
                '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($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;
                    }else{
                        $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=='单票计费'){ $swp_fee_type = 0;}
                    if($sp_fee_type_text=='总单计费')	{  $swp_fee_type = 1;}
                }
            }
            //运输区域
            if($area==""){
                $existError = 1;
                $resultData['message'] .= "运输区域为空;";
            }
            //首重（KG）
            if($swp_weight==""){
                $existError = 1;
                $resultData['message'] .= "首重为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_weight)){
                    $resultData['message'] .= "首重必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //续重（KG）
            if($swp_exces_weight==""){
                $existError = 1;
                $resultData['message'] .= "续重为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_exces_weight)){
                    $resultData['message'] .= "续重必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //首重价格
            if($swp_price===""){
                $existError = 1;
                $resultData['message'] .= "首重价格为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_price)&&$swp_price!=0){
                    $resultData['message'] .= "首重价格必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //续重价格
            if($swp_exces_price===""){
                $existError = 1;
                $resultData['message'] .= "续重价格为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_exces_price)&&$swp_exces_price!=0){
                    $resultData['message'] .= "续重价格必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
            }
            //首重成本
            if($swp_cost===""){
                $existError = 1;
                $resultData['message'] .= "首重成本为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_cost)&&$swp_cost!=0) {
                    $resultData['message'] .= "首重成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
                /*
                if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $swp_cost)){
                    $resultData['message'] .= "首重成本必须是不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
                */
            }
            //续重成本
            if($swp_exces_cost===""){
                $existError = 1;
                $resultData['message'] .= "续重成本为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $swp_exces_cost)&&$swp_exces_cost!=0) {
                    $resultData['message'] .= "首重成本必须是0或者不小于0的数值";
                    $resultData['ok'] = '0';
                    $result['data'][] = $resultData;
                    continue;
                }
                /*
               if (!preg_match("/^[1-9]d*.d*|^[1-9]d*|^0.[0-9]*[1-9]d*$/", $swp_exces_cost)){
                   $resultData['message'] .= "续重成本必须是不小于0的数值";
                   $resultData['ok'] = '0';
                   $result['data'][] = $resultData;
                   continue;
               }
               */
            }
            //单票费用
            if($one_ticket_fee===""){
                $existError = 1;
                $resultData['message'] .= "单票费用为空;";
            }else {
                if (!preg_match("/^[1-9]\d*.\d*|^[1-9]\d*|^0.[0-9]*[1-9]\d*$/", $one_ticket_fee)&&$one_ticket_fee!=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;
                }
            }

            //有效截止时间
            if($date_end==""){
                $existError = 1;
                $resultData['message'] .= "报价截止日期为空;";
            }else {
                if(!preg_match($dataFormat, $date_end)){
                    $resultData['message'] .= $date_start."不是日期格式，建议格式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($customerCode=='') {
                $existError = 1;
                $resultData['message'] .= "客户代码不能为空;";
            } 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['scwp_fee_type'] = $swp_fee_type;
            $row['area'] = $area;
            $row['scwp_weight'] = $swp_weight;
            $row['scwp_exces_weight'] = $swp_exces_weight;
            $row['scwp_price'] = $swp_price;
            $row['scwp_exces_price'] = $swp_exces_price;
            $row['scwp_cost'] = $swp_cost;
            $row['scwp_exces_cost'] = $swp_exces_cost;
            $row['one_ticket_fee'] = $one_ticket_fee;
            $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_ShipCustomerWeightPriceTemp::add($row);
            if($status){
                $resultData['message'] = "插入临时报价表成功";
            }else{
                $resultData['message'] = "插入临时报价表失败";
            }
            $result['data'][] = $resultData;
        }//foreach
        die(json_encode($result));
    }//function end
}