<?php
class Service_LogisticsProcess
{
	private static $shipMethods = array(
			'BH-MMP'=>'瑞典小包挂号',
			'SWPT'=>'瑞典小包平邮',
	);
	public static $checkRemoteCode=array('HKDHL');
	public static function getShipMethods($customer_code='') {
		$shipMethods = self::$shipMethods;
		//针对环球易购特殊处理
		
		if($customer_code=='E0213'){
			$shipMethods['HQSWGH'] = '环球易购瑞典小包挂号';
		}		
		return $shipMethods;
	}
	
	/**
     * @todo 新增物流发运订单
     * @author solar<solarzheng@cargofe.com.cn>
     * @param array $data
     * @return string
     */
    public static function addLogisticsOrder($data)
    {
    	$logistics_code = Common_GetOmsNumbers::getCode('logistics', '', 'LO');
    	//订单信息		
    	$data['order']['logistics_code'] = $logistics_code;
    	$session = new Zend_Session_Namespace("customerAuth");   
    	$data['order']['lo_create_time'] = date('Y-m-d H:i:s');
    	if($data['order']['sm_code']!='HQSWGH') {//不是环球易购
    		$data['order']['ref_tracking_number'] = '';
    	}
     
    	Service_LogisticsOrder::add($data['order']);
    	//收件人信息
    	$data['address']['logistics_code'] = $logistics_code;
    	Service_LogisticsOrderAddress::add($data['address']);
    	//海关申报信息
    	foreach($data['hs_list'] as $hs_row) {
    		unset($hs_row['loh_id']);
    		$hs_row['logistics_code'] = $logistics_code;
    		$hs_row['loh_total_price'] = $hs_row['loh_price'] * $hs_row['loh_quantity'];
    		Service_LogisticsOrderHs::add($hs_row);
    	}
    	//日志
    	$log['logistics_code'] = $logistics_code;
        $log['order_status_from'] = "0";
        $log['order_status_to'] = "0";
    	$log['lol_comment'] = '新增订单';
    	$log['lol_create_time'] = date('Y-m-d H:i:s');
    	$log['lol_operator'] = 0;
    	$log['lol_ip'] = Common_Common::getIP();
    	Service_LogisticsOrderLog::add($log);
    	return $logistics_code;
    }
    
    public static function editLogisticsOrder($logistics_code, $data)
    {
    	if($data['order']['sm_code']!='HQSWGH') {//不是环球易购
    		$data['order']['ref_tracking_number'] = '';
    	}
    	$data['order']['lo_update_time'] = date('Y-m-d H:i:s');
    	Service_LogisticsOrder::update($data['order'], $logistics_code, 'logistics_code');
    	$result = Service_LogisticsOrderAddress::update($data['address'], $logistics_code, 'logistics_code');
    	$hsKeyArr = Service_LogisticsOrderHs::getKeyArray($logistics_code);
    	foreach($data['hs_list'] as $hs_row) {
    		if($hs_row['loh_id']==0) {
    			unset($hs_row['loh_id']);
    			$hs_row['logistics_code'] = $logistics_code;
    			$hs_row['loh_total_price'] = $hs_row['loh_price'] * $hs_row['loh_quantity'];
    			Service_LogisticsOrderHs::add($hs_row);
    		} else {
    			$loh_id = $hs_row['loh_id'];
    			unset($hs_row['loh_id']);
    			$hs_row['loh_total_price'] = $hs_row['loh_price'] * $hs_row['loh_quantity'];
    			Service_LogisticsOrderHs::update($hs_row, $loh_id);
    			unset($hsKeyArr[$loh_id]);
    		}
    	}
    	foreach($hsKeyArr as $row) {
    		Service_LogisticsOrderHs::delete($row['loh_id']);
    	}
    	//日志
    	$log['logistics_code'] = $logistics_code;
    	$log['lol_comment'] = '修改订单';
    	$log['lol_create_time'] = date('Y-m-d H:i:s');
    	$log['lol_operator'] = 0;
    	$log['lol_ip'] = Common_Common::getIP();
    	Service_LogisticsOrderLog::add($log);
    }
    
    public static function validator(&$data,$logistics_code="") {
    	
		$result = array();		
    	//订单
    	if(isset($data['order']) && is_array($data['order'])) {
    		$order = $data['order'];			
			if(!$order['customer_code']){ 
				$result['customer_code'] = '请输入客户代码';	
			}else{			     				
				 $customer = Service_Customer::getByField($order['customer_code'],'customer_code');
				 if(!$customer){
				 	$result[] = '客户代码错误，没有对应客户信息';
				 }else{
				 	  if($customer['customer_status']!=2){
					  		$result[] = '此客户属于非正式账户';
					  }else{
				 		$data['customer_id'] = $customer['customer_id'];
					  }
				 }
				 
			}
			
			
			
    		if(!isset($order['reference_no']) || empty($order['reference_no'])){
				$result['reference_no'] = '请输入客户参考号';			
			}else{
				if($customer){
				$where['customer_id'] = $customer['customer_id'];
				$where['reference_no'] = $order['reference_no'];
				$logistics = Service_LogisticsOrder::getByWhere($where);
				if($logistics) {
					if($logistics_code) {
						if($logistics_code!=$logistics['logistics_code']) $result['reference_no'] = '客户参考号已存在';	
					} else {
						$result['reference_no'] = '客户参考号['.$order['reference_no'].']已存在';
					}
				}}
			}
    		if(!isset($order['sm_code']) || empty($order['sm_code'])){
    			$result['sm_code'] = '请输入运输方式';
			}	
    		elseif($order['customer_code']!='E0213' && $order['sm_code']=='HQSWGH'){   
				$result['error_sm_code'] = '只有特定用户才能使用HQSWGH运输方式';
			}else{
    			$shipMethods = self::getShipMethods($order['customer_code']);
    			if(!isset($shipMethods[$order['sm_code']])){
    				$result['sm_code'] = '运输方式['.$order['sm_code'].']不存在';
				} else {//运输方式合法
					if($order['sm_code']=='HQSWGH'){
						if(!isset($order['ref_tracking_number']) || empty($order['ref_tracking_number'])){
							$result['ref_tracking_number'] = '请输入跟踪号';
						}	
					}				
				}
    		}	
    		if(!isset($order['lo_weight']) || empty($order['lo_weight'])){
				$result['lo_weight'] = '请输入重量';
			}else{
			        if(!(is_numeric($order['lo_weight']) && $order['lo_weight']>0)){
						$result['lo_weight'] = '重量必须为正数';
					}
			}			
    	} else {
    		$result['order'] = '数据错误';
    	}

    	//地址
    	if(isset($data['address']) && is_array($data['address'])) {
    		$address = $data['address'];
    		if(!isset($address['loa_name']) || empty($address['loa_name']))
    			$result['loa_name'] = '请输入收件人姓名';
    		if(!isset($address['loa_country']) || empty($address['loa_country']))
    			$result['loa_country'] = '请输入收件人国家';
    		if(!isset($address['loa_address']) || empty($address['loa_address']))
    			$result['loa_address'] = '请输入收件人地址';
            if(preg_match('/[~`@#$%^&*?<>+=]+/u',$address['loa_address'])){
                $result['loa_address'] = '收件人地址不能有特殊字符';
            }
    	} else {
    		$result['address'] = '数据错误';
    	}
    	//海关信息
    	if(isset($data['hs_list']) && is_array($data['hs_list'])) {
    		$hs_list = $data['hs_list'];
    		if(count($hs_list)==0) {
    			$result['hs_list'] = '至少需要一条海关申报信息';
    		} else {
    			foreach($hs_list as $i=>$hs_info) {
    				$line = $i + 1;
    				if(!isset($hs_info['loh_hs_name']) || empty($hs_info['loh_hs_name'])) {
    					$result['hs_list'] = '第['.$line.']条申报信息 ：请输入申报英文品名';
    					break;
    				}
                    if(preg_match("/[\x{4e00}-\x{9fa5}]+/u",$hs_info['loh_hs_name'])){
                        $result['hs_list'] = '第['.$line.']条申报信息 ：申报英文品名不能有汉字';
                        break;
                    }
                    if(preg_match('/[~`@#$%^&*?<>+=]+/u',$hs_info['loh_hs_name'])){
                        $result['hs_list'] = '第['.$line.']条申报信息 ：申报英文品名不能有特殊字符';
                        break;
                    }
    				if(!isset($hs_info['loh_unit']) || empty($hs_info['loh_unit'])) {
    					$result['hs_list'] = '第['.$line.']条申报信息 ：请输入单位';
    					break;
    				}
    				if(!isset($hs_info['loh_price']) || empty($hs_info['loh_price'])) {
    					$result['hs_list'] = '第['.$line.']条申报信息 ：请输入单价';
    					break;
    				}else{
						if (!(is_numeric($hs_info['loh_price']) && $hs_info['loh_price'] >0 )) {
    						$result['hs_list'] = '第['.$line.']条申报信息 ：单价必须为数值';
    						break;	
						}
					}
					
    				if(!isset($hs_info['loh_quantity']) || empty($hs_info['loh_quantity'])) {
    					$result['hs_list'] = '第['.$line.']条申报信息 ：请输入数量';
    					break;
    				}else{
					
						 if (!(preg_match("/^[0-9]+$/",$hs_info['loh_quantity']) && is_numeric($hs_info['loh_quantity']) && $hs_info['loh_quantity'] >0 )) {
						 	$result['hs_list'] = '第['.$line.']条申报信息 ：数量必须为正整数';
							break;
						 }
					
					}
    			}
    		}
    	} else {
    		$result['hs_list'] = '数据错误';
    	}
    	return empty($result) ? true : $result;
    }
	
	/*判断运输方式和国家字段的合法性
	LogisticsProcess::checksmcode()
	*/
	public static function checksmcode($country_id,$sm_code,$warehouse_code,$lo_weight){
			
			$sm_array= Service_ShippingMethod::getByField($sm_code,'sm_code');
			
			if(!$country_id||!$sm_code){
				return "订单信息没有国家信息或没有运输方式";				
			}
						
			$sm_array = Service_ShippingMethod::getByField($sm_code,'sm_code');
			if(!$sm_array){
				return "不存在的运输方式";
			}
						
			$sm_country_arrays = Service_SmCountryMap::getByCondition(array('country_id'=>$country_id,'sm_code'=>$sm_code));
			if(!$sm_country_arrays){
					return "非法的运输方式";					
			}
			$sm_country_array = $sm_country_arrays[0];
			
			if($sm_array['sm_calc_type']=='0'){/*区间重量*/				
				$price_array = Service_ShipPrice::getByCondition(array('sm_code'=>$sm_array['sm_code'],'area'=>$sm_country_array['area'],'warehouse_code'=>$warehouse_code));
				
			}
			if($lo_weight>$sm_array['sm_limit_weight']){ return "超重.";}	
			if($sm_array['sm_calc_type']=='1'){/*首续重*/				
				$price_array=Service_ShipWeightPrice::getByCondition(array('sm_code'=>$sm_array['sm_code'],'area'=>$sm_country_array['area'],'warehouse_code'=>$warehouse_code));
			}	
			//print_r(array('sm_code'=>$sm_array['sm_code'],'area'=>$sm_country_array['area'],'warehouse_code'=>$warehouse_code));exit;
			if(!$price_array){ return "运输方式的价格未设置.";}	
				
			//sm_limit_weight
			return '';		
	
	}
	
	/**
	 * @todo 验证Excel
	 * @author solar
	 * @param array $excelData
	 * @return array
	 */
	public static function validateExcel(&$excelData) {
		$result = array('ask'=>0);
		$aError = array();
		//表头
		$excelHead = array_shift($excelData);
		$vHead = self::validateHead($excelHead);
		//如果表头有错，返回错误
		if($vHead!==true) {
			$result['error'] = $vHead;
			return $result;
		}
		//表体
		$kvCountry = Service_Country::getNameIdKV();
		$kvUnit = Service_ProductUom::getNameCodeKV();
		$line = 1;
		$aData = array();
		$aReferenceNO = array();
		foreach($excelData as $excelRow) {
			++$line;
			$aInfo = array();
			//订单
			$order = array();
			$customer_code = trim($excelRow[0]);
			$reference_no =  trim($excelRow[1]);
			$sm_code = trim($excelRow[2]);
			$ref_tracking_number = trim($excelRow[3]);
			$lo_weight = trim($excelRow[4]);
			$warehouse_id = 3;
			$loa_name = trim($excelRow[5]);
			$loa_company = trim($excelRow[6]);
			$country_name = trim($excelRow[7]);
			$loa_zipcode = trim($excelRow[8]);
			$loa_phone = trim($excelRow[9]);
			$loa_address = trim($excelRow[10]);


			$order['customer_code'] = $customer_code;//客户代码
			if(!$order['customer_code']){
				$aError['no_customer_code'] = '客户代码不能为空';
			}else{
				 $customer = Service_Customer::getByField($order['customer_code'],'customer_code');
				 if(!$customer){
				 	$aError['no_customer'] = '客户代码是错误的';
				 }else{
				 	$order['customer_id'] =  $customer['customer_id'];
				 }
			}
			
			 
			
			$order['ref_tracking_number'] = $ref_tracking_number;
			$order['reference_no'] = $reference_no;//客户参考号
			if(in_array($order['reference_no'], $aReferenceNO)) {
				$aError['reference_no'] = '客户参考号['.$order['reference_no'].']不能重复';
				break;
			}
			$aReferenceNO[] = $order['reference_no'];
			
			$order['sm_code'] = $sm_code;//运输方式
			
			$order['lo_weight'] = $lo_weight;
			$order['warehouse_id'] = $warehouse_id;	//区外仓
			$aInfo['order'] = $order;
			//地址
			$address = array();
			$address['loa_name'] = $loa_name;
			$address['loa_company'] = $loa_company;
			
			if(!isset($kvCountry[$country_name])) {
				$aError['loa_country'] = '第'.$line.'行的国家['.$country_name.']不存在';
				break;
			}
			$address['loa_country'] = $kvCountry[$country_name];			
			$address['loa_zipcode'] = $loa_zipcode;
			$address['loa_phone'] = $loa_phone;
			$address['loa_address'] = $loa_address;
			
			$aInfo['address'] = $address;
			//海关信息
			$aKey = array(1=>'loh_hs_name',2=>'loh_unit',3=>'loh_price',4=>'loh_quantity',5=>'loh_hs_code',6=>'loh_name',7=>'loh_note');
			$hs_list = array();
			$hs_info = array();
			$j = 0;
			$isEmpty = true;
			$isBreak = false;
			for($i=11; $i<=46; $i++) {
				++$j;
				$cell = trim($excelRow[$i]);
				$hs_info[$aKey[$j]] = $cell;
				if(!empty($cell)) {
					$isEmpty = false;
					if($j==2) {	//单位
						if(!isset($kvUnit[$cell])) {
							$aError['loh_unit'] = '第'.$line.'行的单位['.$cell.']不存在';
							$isBreak = true;
							break;
						}
						$hs_info['loh_unit'] = $kvUnit[$cell];
					}
				}
				if($j==7) {
					if($isEmpty == false) $hs_list[] = $hs_info;
					$hs_info = array();
					$j = 0;
					$isEmpty = true;
				}
			}
			if($isBreak === true) break;	//错误，退出循环
			
			$aInfo['hs_list'] = $hs_list;
			//验证
			$vBody = self::validator($aInfo);
			if($vBody!==true) {
				/* array_unshift($vBody, '第'.$line.'行的错误信息如下所示：');
				$aError = array_merge($aError, $vBody); */
				$aError[] = '第'.$line.'行错误：' . implode('；',$vBody) . '。';
				//break;
			}
			$aData[] = $aInfo;
		}//for		
		//返回结果
		if(!empty($aError)) {
			$result['error'] = $aError;
		} else {
			$result['body'] = $aData;
			$result['ask'] = 1;
		}
		return $result;
	}
	
	public static function validateHead($excelHead) {
		$aError = array();
		$i = 0;
		
		if(trim($excelHead[$i++]) != '客户代码') $aError[] = '表头错误：A1单元格应该为[客户代码]';
		if(trim($excelHead[$i++]) != '客户参考号') $aError[] = '表头错误：B1单元格应该为[客户参考号]';
		if(trim($excelHead[$i++]) != '运输方式') $aError[] = '表头错误：C1单元格应该为[运输方式]"';
		if(trim($excelHead[$i++]) != '跟踪号') $aError[] = '表头错误：D1单元格应该为[跟踪号]';
		if(trim($excelHead[$i++]) != '重量（KG）') $aError[] = '表头错误：D1单元格应该为[重量（KG）]';
		if(trim($excelHead[$i++]) != '收件人姓名') $aError[] = '表头错误：E1单元格应该为[收件人姓名]';
		if(trim($excelHead[$i++]) != '收件人公司名') $aError[] = '表头错误：F1单元格应该为[收件人公司名]';
		if(trim($excelHead[$i++]) != '收件人国家') $aError[] = '表头错误：G1单元格应该为[收件人国家]"';
		if(trim($excelHead[$i++]) != '收件人邮编') $aError[] = '表头错误：H1单元格应该为[收件人邮编]';
		if(trim($excelHead[$i++]) != '收件人电话') $aError[] = '表头错误：I1单元格应该为[收件人电话]';
		if(trim($excelHead[$i++]) != '收件人地址') $aError[] = '表头错误：J1单元格应该为[收件人地址]';
		if(trim($excelHead[$i++]) != '申报英文品名') $aError[] = '表头错误：K1单元格应该为[申报英文品名]';
		if(trim($excelHead[$i++]) != '单位') $aError[] = '表头错误：L1单元格应该为[单位]';
		if(trim($excelHead[$i++]) != '单价（USD）') $aError[] = '表头错误：M1单元格应该为[单价（USD）]';
		if(trim($excelHead[$i++]) != '数量') $aError[] = '表头错误：N1单元格应该为[数量]';
		if(trim($excelHead[$i++]) != '海关编码') $aError[] = '表头错误：O1单元格应该为[海关编码]';
		if(trim($excelHead[$i++]) != '配货名称') $aError[] = '表头错误：P1单元格应该为[配货名称]';
		if(trim($excelHead[$i++]) != '配货备注') $aError[] = '表头错误：Q1单元格应该为[配货备注]';
		if(trim($excelHead[$i++]) != '申报英文品名2') $aError[] = '表头错误：R1单元格应该为[申报英文品名2]';
		if(trim($excelHead[$i++]) != '单位2') $aError[] = '表头错误：S1单元格应该为[单位2]';
		if(trim($excelHead[$i++]) != '单价（USD）2') $aError[] = '表头错误：T1单元格应该为[单价（USD）2]';
		if(trim($excelHead[$i++]) != '数量2') $aError[] = '表头错误：U1单元格应该为[数量2]';
		if(trim($excelHead[$i++]) != '海关编码2') $aError[] = '表头错误：V1单元格应该为[海关编码2]';
		if(trim($excelHead[$i++]) != '配货名称2') $aError[] = '表头错误：W1单元格应该为[配货名称2]';
		if(trim($excelHead[$i++]) != '配货备注2') $aError[] = '表头错误：X1单元格应该为[配货备注2]';
		if(trim($excelHead[$i++]) != '申报英文品名3') $aError[] = '表头错误：Y1单元格应该为[申报英文品名3]';
		if(trim($excelHead[$i++]) != '单位3') $aError[] = '表头错误：Z1单元格应该为[单位3]';
		if(trim($excelHead[$i++]) != '单价（USD）3') $aError[] = '表头错误：AA1单元格应该为[单价（USD）3]';
		if(trim($excelHead[$i++]) != '数量3') $aError[] = '表头错误：AB1单元格应该为[数量3]';
		if(trim($excelHead[$i++]) != '海关编码3') $aError[] = '表头错误：AC1单元格应该为[海关编码3]';
		if(trim($excelHead[$i++]) != '配货名称3') $aError[] = '表头错误：AD1单元格应该为[配货名称3]';
		if(trim($excelHead[$i++]) != '配货备注3') $aError[] = '表头错误：AE1单元格应该为[配货备注3]';
		if(trim($excelHead[$i++]) != '申报英文品名4') $aError[] = '表头错误：AF1单元格应该为[申报英文品名4]';
		if(trim($excelHead[$i++]) != '单位4') $aError[] = '表头错误：AG1单元格应该为[单位4]';
		if(trim($excelHead[$i++]) != '单价（USD）4') $aError[] = '表头错误：AH1单元格应该为[单价（USD）4]';
		if(trim($excelHead[$i++]) != '数量4') $aError[] = '表头错误：AI1单元格应该为[数量4]';
		if(trim($excelHead[$i++]) != '海关编码4') $aError[] = '表头错误：AJ1单元格应该为[海关编码4]';
		if(trim($excelHead[$i++]) != '配货名称4') $aError[] = '表头错误：AK1单元格应该为[配货名称4]';
		if(trim($excelHead[$i++]) != '配货备注4') $aError[] = '表头错误：AL1单元格应该为[配货备注4]';
		if(trim($excelHead[$i++]) != '申报英文品名5') $aError[] = '表头错误：AM1单元格应该为[申报英文品名5]';
		if(trim($excelHead[$i++]) != '单位5') $aError[] = '表头错误：AN1单元格应该为[单位5]';
		if(trim($excelHead[$i++]) != '单价（USD）5') $aError[] = '表头错误：AO1单元格应该为[单价（USD）5]';
		if(trim($excelHead[$i++]) != '数量5') $aError[] = '表头错误：AP1单元格应该为[数量5]';
		if(trim($excelHead[$i++]) != '海关编码5') $aError[] = '表头错误：AQ1单元格应该为[海关编码5]';
		if(trim($excelHead[$i++]) != '配货名称5') $aError[] = '表头错误：AR1单元格应该为[配货名称5]';
		if(trim($excelHead[$i++]) != '配货备注5') $aError[] = '表头错误：AS1单元格应该为[配货备注5]';
		return empty($aError) ? true : $aError;
	}
	
}