<?php
class Ship_ShippingMethodController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "ship/views/";
        $this->serviceClass = new Service_ShippingMethod();
    }

    public function listAction()
    {
        $status=Common_Status::SMStatus('auto');
        $smClass=Common_Type::SMClass('auto');
        $smFeeType=Common_Type::SMFeeType('auto');
        $smCalcFeeType=Common_Type::SMCountryMapType('auto');
        $warehouse=Common_DataCache::getWarehouseSimple();
        $spArr=Common_DataCache::getProvider();
        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',
                'sm_name_cn',
                'sm_name',
                'sm_status',
                'sm_class_code',
                'sm_limit_weight',
                'warehouse_id',
                'sm_fee_type',
                'sm_calc_type',
                'sm_id',
                'sm_channel',		
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('sm_code','sm_sort'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['status'] =$status;
                $return['warehouse']=$warehouse;
                $return['FeeType'] =$smFeeType;
                $return['smClass'] = $smClass;
                $return['smCalcFeeType'] = $smCalcFeeType;
                $return['spArr'] = $spArr;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->warehouse=$warehouse;
        $this->view->status=$status;
        $this->view->smClass=$smClass;
        $this->view->smFeeType=$smFeeType;
        $this->view->smCalcFeeType=$smCalcFeeType;
        $this->view->spArr=$spArr;
        $this->view->YesOrNo=Common_Status::YesOrNo('auto');
        echo Ec::renderTpl($this->tplDirectory . "shipping_method_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        $sm_channel = $this->_request->getParam('E30','0'); //运输方式是否自有运输方式
        if ($this->_request->isPost()) {
        	//echo $sm_channel;
        	if($sm_channel=='0'){
        		//普通运输方式添加
        		$params = $this->_request->getParams();
        		$row = array(
        		
        				'sm_id'=>'',
        				'sm_code'=>'',
        				'sm_name_cn'=>'',
        				'sm_name'=>'',
        				'sm_mp_fee'=>'',
        				'sm_reg_fee'=>'',
        				'sm_addons'=>'',
        				'sm_discount'=>'',
        				'sm_delivery_time_min'=>'',
        				'sm_delivery_time_max'=>'',
        				'sm_delivery_time_avg'=>'',
        				'sm_is_volume'=>'',
        				'sm_vol_rate'=>'',
        				'sm_status'=>'',
        				'sm_class_code'=>'',
        				'sm_logo'=>'',
        				'sm_return_address'=>'',
        				'sm_discount_min'=>'',
        				'sm_mp_fee_min'=>'',
        				'sm_reg_fee_min'=>'',
        				'sm_limit_volume'=>'',
        				'sm_limit_weight'=>'',
        				'sm_sort'=>'',
        				'sm_is_tracking'=>'',
        				'sm_is_validate_remote'=>'',
        				'warehouse_id'=>'',
        				'sm_fee_type'=>'',
        				'sm_calc_type'=>'',
        				'sm_baf'=>'',
        				'sm_return_recipient'=>'',
        				'sp_code'=>'',
        				'sm_channel'=>'0',
        				'packet_type'=>'0',
                        'sm_is_piece'=>'',
        		);
        		$row=$this->serviceClass->getMatchEditFields($params,$row);
        		unset($params);
        		$paramId = $row['sm_id'];
        		if (!empty($row['sm_id'])) {
        			unset($row['sm_id']);
        		}
        		$errorArr = $this->serviceClass->validator($row);
    			/*$shipCheck = Service_ShippingMethod::getByField($row['sm_code'],'sm_code');
    			if (!empty($paramId)){
    				if(!empty($shipCheck) && $shipCheck['sm_id']!=$paramId){
    					$errorArr[] = "系统已存在运输方式代码:{$row['sm_code']}";
    				}
    			}else{
                    if(!empty($shipCheck)){
                        $errorArr[] = "系统已存在运输方式代码:{$row['sm_code']}";
                    }
    			}*/
                if ($row['sm_is_volume']=='1'&&$row['sm_is_piece']=='1') {
                    $errorArr[] = "不能同时计量体积和件数";
                }
                $condition = array(
                    'sm_code'=>$row['sm_code'],
                    'warehouse_id'=>$row['warehouse_id'],
                );
                $exitShip = Service_ShippingMethod::getByCondition($condition,"*");
                if(!empty($paramId)){
                    //修改
                    $sm = Service_ShippingMethod::getByField($paramId,'sm_id',"*");
                    if($sm['warehouse_id']==$row['warehouse_id']){

                    }else{
                        //不修改仓库选项
                        if(!empty($exitShip)){
                            $errorArr[] = "仓库已存在运输方式代码:{$row['sm_code']}";
                        }
                    }
                }else{
                    //新增
                    if($row['warehouse_id']=="0"){
                        $condition = array(
                            'sm_code'=>$row['sm_code'],
                            //'warehouse_id_arr'=>array(0,$row['warehouse_id']),
                        );
                    }else{
                        $condition = array(
                            'sm_code'=>$row['sm_code'],
                            'warehouse_id_arr'=>array(0,$row['warehouse_id']),
                        );
                    }

                    $exitShip = Service_ShippingMethod::getByCondition($condition,"*");
                    if(!empty($exitShip)){
                        $errorArr[] = "仓库已存在运输方式代码:{$row['sm_code']}";
                    }
                }

        		//$shipCheck = 
        		if (!empty($errorArr)) {
        			$return = array(
        					'state' => 0,
        					'message'=>'',
        					'errorMessage' => $errorArr
        			);
        			die(Zend_Json::encode($return));
        		}
        		
        		if (!empty($paramId)) {
        			$result = $this->serviceClass->update($row, $paramId);
        		} else {
        			$result = $this->serviceClass->add($row);
        		}
        		if ($result) {
        			$return['state'] = 1;
        			$return['message'] = array('Success.');
        		}
        	}elseif($sm_channel=='1'){
        		//自有运输方式添加
        		$params = $this->_request->getParams();
        		$row = array(
        		
        				'sm_id'=>'',
        				'sm_code'=>'',
        				'sm_name_cn'=>'',
        				'sm_name'=>'',
        				'sm_mp_fee'=>'0.00',
        				'sm_reg_fee'=>'0.00',
        				'sm_addons'=>'0.00',
        				'sm_discount'=>'1.00',
        				'sm_delivery_time_min'=>'0',
        				'sm_delivery_time_max'=>'0',
        				'sm_delivery_time_avg'=>'',
        				'sm_is_volume'=>'',
        				'sm_vol_rate'=>'',
        				'sm_status'=>'',
        				'sm_class_code'=>'',
        				'sm_logo'=>'',
        				'sm_return_address'=>'',
        				'sm_discount_min'=>'',
        				'sm_mp_fee_min'=>'',
        				'sm_reg_fee_min'=>'',
        				'sm_limit_volume'=>'',
        				'sm_limit_weight'=>'',
        				'sm_sort'=>'',
        				'sm_is_tracking'=>'',
        				'sm_is_validate_remote'=>'',
        				'warehouse_id'=>'',
        				'sm_fee_type'=>'0',
        				'sm_calc_type'=>'0',
        				'sm_baf'=>'',
        				'sp_code'=>'',
        				'sm_return_recipient'=>'',
        				'sm_channel'=>'1',
        				'packet_type'=>'0',
                        'sm_is_piece'=>'',
        		);
        		$row=$this->serviceClass->getMatchEditFields($params,$row);
        		//print_r($row);
        		unset($params);
        		$paramId = $row['sm_id'];
        		if (!empty($row['sm_id'])) {
        			unset($row['sm_id']);
        		}
        		$errorArr = $this->serviceClass->validatorzy($row);
        		//print_r($errorArr);
        		//exit;
        		/*$shipCheck = Service_ShippingMethod::getByField($row['sm_code'],'sm_code');
        		if (!empty($paramId)){
        			if(!empty($shipCheck) && $shipCheck['sm_id']!=$paramId){
        				$errorArr[] = "系统已存在运输方式代码:{$row['sm_code']}";
        			}
        		}else{
                    if(!empty($shipCheck)){
                        $errorArr[] = "系统已存在运输方式代码:{$row['sm_code']}";
                    }
        		}*/
                if ($row['sm_is_volume']=='1'&&$row['sm_is_piece']=='1') {
                    $errorArr[] = "不能同时量体积和计件";
                }
                $condition = array(
                    'sm_code'=>$row['sm_code'],
                    'warehouse_id'=>$row['warehouse_id'],
                );
                $exitShip = Service_ShippingMethod::getByCondition($condition,"*");
                if(!empty($paramId)){
                    //修改
                    //if(!empty($exitShip)){
                    //    $errorArr[] = "仓库已存在运输方式代码:{$row['sm_code']}";
                    //}
                }else{
                    //新增
                    $condition = array(
                        'sm_code'=>$row['sm_code'],
                        'warehouse_id_arr'=>array(0,$row['warehouse_id']),
                    );
                    $exitShip = Service_ShippingMethod::getByCondition($condition,"*");
                    if(!empty($exitShip)){
                        $errorArr[] = "仓库已存在运输方式代码:{$row['sm_code']}";
                    }
                }
        		if (!empty($errorArr)) {
        			$return = array(
        					'state' => 0,
        					'message'=>'',
        					'errorMessage' => $errorArr
        			);
        			die(Zend_Json::encode($return));
        		}
        		/* $db = Common_Common::getAdapter();
        		$db->beginTransaction(); */
        		
        		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, 'sm_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));
    }
    /**
     * @author william-fan
     * @todo 用于得到运输方式信息
     */
    public function getByCodeAction(){
    	$_userAuth = new Zend_Session_Namespace('userAuthorization');
    	$warehouseId=$_userAuth->warehouseId;
    	$result = array('state' => 0, 'message' => 'Fail', 'data' => array());
    	$sm_code = trim($this->_request->getParam('sm_code', ''));
    	$userAuth = new Zend_Session_Namespace('userAuthorization');
    	$warehouseId=$userAuth->warehouseId;
    	/* echo "<pre>";
    	print_r($se); */
    	if(!empty($sm_code)){
    		$smCondition = array(
    				'sm_code'=>$sm_code,
    				'warehouse_id_arr'=>array('0',$warehouseId)
    		);
    		$rows = $this->serviceClass->getByCondition($smCondition,'*',1,1,'warehouse_id desc');
    		if(!empty($rows)){
    			$row = $rows[0];
    			$result = array('state' => 1, 'message' => '', 'data' => $row);
    		}
    	}
    	die(Zend_Json::encode($result));
    }

    public function getShipMethodAction(){
        $warehouse_id = $this->_request->getParam("warehouse_id","");
        $condition = array(
            'warehouse_id'=>$warehouse_id
        );
        $shipMethod = Service_ShippingMethod::getByCondition($condition,"*");
        $shipMethod = Common_Common::multisort($shipMethod);
        die(Zend_Json::encode($shipMethod));
    }
    public function getOrderAction(){
        $ship_code = $this->_request->getParam("ship_code","");
        $condition = array(
            'ref_tracking_number'=>$ship_code
        );
        $Orders = Service_Orders::getByCondition($condition,"*");
        if(!empty($Orders)){
          $order=$Orders[0];  
        }else{
            $order='';
        }
            
        die(Zend_Json::encode($order));
    }
}