<?php
class Ship_CustomerFeeController extends Ec_Controller_Action{
	public function preDispatch()
	{
		$this->tplDirectory = "ship/views/";
		$this->serviceClass = new Service_CustomerOtherFee();
	}
	/**
	 * @author william-fan
	 * @todo 用于显示列表
	 */
	public function listAction(){
		$otherFees = Service_OtherFee::getAll();
		$customer = Service_Customer::getAll();
		$otherFeesKey = array();
		if(!empty($otherFees)){
			foreach ($otherFees as $key=>$fee){
				$otherFeesKey[$fee['fee_id']] = $fee;
			}
		}
		$status=Common_Status::SMStatus('auto');
		/* echo "<pre>";
		print_r($otherFeesKey); */
		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(
						'cof_id',
						'fee_id',
						'customer_code',
						'discount',
                        'fee_value',
                        'limit_time',
						'status'
				);
				$showFields = $this->serviceClass->getFieldsAlias($showFields);
				$rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('fee_id desc'));
				if(!empty($rows)){
					foreach($rows as $key=>$value){
						$otherfee=Service_OtherFee::getByField($value['E1']);
						$rows[$key]['fee_name'] = $otherfee['fee_name'];
					}
				}
				$return['data'] = $rows;
				$return['state'] = 1;
				$return['status'] = $status;
				
				$return['message'] = "";
			}
			die(Zend_Json::encode($return));
		}
		$cus=array();
		foreach ($customer as $key => $value) {
			if ($value['customer_status']==2) {
				$cus[]=$value;
			}
		}
		$this->view->customer = $cus;
		$this->view->otherfees = $otherFeesKey;
		$this->view->status= $status;
		
		echo Ec::renderTpl($this->tplDirectory . "customer_fee_index.tpl", 'layout');
	}
	public function editAction(){
		$return = array(
				'state' => 0,
				'message' => '',
				'errorMessage'=>array('Fail.')
		);
		
		if ($this->_request->isPost()) {
			$params = $this->_request->getParams();
			$row = array(
					'cof_id'=>'',
					'fee_id'=>'',
					'customer_code'=>'',
					'discount'=>'',
					'status'=>'',
                    'fee_value'=> '',
                    'limit_time'=> ''
			);
			$row=$this->serviceClass->getMatchEditFields($params,$row);
			$customer=Service_Customer::getByField($row['customer_code'],'customer_code');
			if(empty($customer)){
				$return['message'] = '客户不存在';
				$errorMessage = $return['errorMessage'];
				$errorMessage[] = array('客户不存在');
				$return[errorMessage] = $errorMessage;
				die(Zend_Json::encode($return));
			}
			unset($params);
			$paramId = $row['cof_id'];
			if (!empty($row['cof_id'])) {
				unset($row['cof_id']);
			}
			$errorArr = $this->serviceClass->validator($row);
		    $row['customer_code'] = strtoupper($row['customer_code']);
		    //
		    $otherfeeCondition = array(
		    	'fee_id'=>$row['fee_id'],	
		    	'customer_code'=>$row['customer_code']
		    );
		    if(!empty($paramId)){
		    	//
		    	$customerotherfee=Service_CustomerOtherFee::getByField($paramId);
		    	if($customerotherfee['fee_id']==$row['fee_id']){
		    		
		    	}else{
		    		$numberotherfees=Service_CustomerOtherFee::getByCondition($otherfeeCondition,'count(*)');
		    		if($numberotherfees>0){
		    			$errorArr[]="改客户该费用已经存在,不能改成该费用";
		    		}
		    	}
		    }else{
		    	$numberotherfees=Service_CustomerOtherFee::getByCondition($otherfeeCondition,'count(*)');
		    	if($numberotherfees>0){
		    		$errorArr[]="改客户该费用已经存在,不能重复添加";
		    	}
		    }
		    $otherfee = Service_OtherFee::getByField($row['fee_id']);
		    if(!empty($otherfee)){
		    	if($otherfee['fee_discount']>$row['discount']){
		    		$errorArr[] = '您设置的折扣必须大于该费用的最低折扣';
		    	}
		    }else{
		    	$errorArr[] = '您选择的费用不存在';
		    }
		    if($row['fee_value'] == ''){//费用输入为空，则直接取杂费配置中费用
		        $row['fee_value'] = $otherfee['fee_value'];
		    }else{
		        if(!(preg_match('/^\d+\.\d+$ || ^\d+$/',$row['fee_value']) && is_numeric($row['fee_value']))){
		            $errorArr[] = '您输入的费用取值应为数字';
		        }
		    }
			if (!empty($errorArr)) {
				$return = array(
						'state' => 0,
						'message'=>'',
						'errorMessage' => $errorArr
				);
				die(Zend_Json::encode($return));
			}
			$conditionOtherFee = array(
					'fee_code'=>$row['fee_code'],
			);
			$otherfeeRows=Service_OtherFee::getByCondition($conditionOtherFee);
			if(!empty($otherfeeRows)){
				$otherfeeRow = $otherfeeRows[0];
			}
			//$smRow=Service_ShippingMethod::getByField($row['sm_code'],'sm_code');
			//$row['fee_id']=$otherfeeRow['fee_id'];
			unset($smRow);
			if (!empty($paramId)) {
				$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, 'cof_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 downBatchImportTemplateAction(){
	    $fullPath = APPLICATION_PATH."/../data/xls".'/batch-customer-other-fee.xlsx';
	    Common_Common::downloadFile($fullPath);
	}
	
	public function batchImportAction(){
	     $response = array('status'=>'0','message'=>'','error'=>'');
	     if ($this->_request->isPost()) {
	         $fileInfo = $_FILES['customer_other_fee'];
	         if (0 !== $fileInfo['error']) {
	             $error = '上传订单数据文件失败';
	             switch ($fileInfo['error']) {
	                 case UPLOAD_ERR_INI_SIZE:
	                     $error .= '：文件大小超过系统配置指定值' . ini_get('upload_max_filesize');
	                     break;
	                 case UPLOAD_ERR_FORM_SIZE:
	                     $error .= '：文件大小超过表单指定值（MAX_FILE_SIZE）';
	                     break;
	                 case UPLOAD_ERR_PARTIAL:
	                     $error .= '：文件上传不完整';
	                     break;
	                 case UPLOAD_ERR_NO_FILE:
	                     $error .= '：没有文件上传';
	                     break;
	                 case UPLOAD_ERR_NO_TMP_DIR:
	                     $error .= '：找不到临时目录';
	                     break;
	                 case UPLOAD_ERR_CANT_WRITE:
	                     $error .= '：文件写入失败';
	                     break;
	                 default:
	                     break;
	             }
	             if(!empty($error)){
	                 $response['error'] = $error;
	             }
	         }else{
	             //读取excel文件
	             //var_dump($_FILES);
	             $ext = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
	             if (!in_array(strtoupper($ext), array('XLS', 'XLSX'), TRUE)) {
	                 $error = '不受支持的文件类型：' . $ext;
	                 $response['error'] = $error;
	             }else{
	                 @$importData = Common_Common::getXLSDataNew($_FILES,'customer_other_fee');
	                 unset($importData[0]); //删除表头
	                 $error = $this->serviceClass->validatorAndTransfer($importData);
	                 $response['status'] = '1';
	                 $response['error'] = $error;
	             }
	        }
            if(empty($error)){
                $insertResult = array();
                $insertQuantity = count($importData);
                foreach($importData as $key=>$row){
                    $insertReturn = $this->serviceClass->add($row);
                    $insertResult[$key] = array('msg'=>'添加成功！');
                }
                $response['status'] = '1';
                $response['message'] = '<font color="green">批量导入维护成功,共['.$insertQuantity.']条杂费客户配置数据!!</font>';
            }
            die(Zend_Json::encode($response));
            
	     }
	}
}