<?php
class Customer_CustomerController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "customer/views/default/";
        $this->serviceClass = new Service_Customer();
    }

    public function listAction()
    {	
        $customerStatus = Common_Status::customerStatus('auto');
        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();
            $operationType = isset($params['operationType']) ? $params['operationType'] : '';
            $operationCode = isset($params['operationCode']) ? $params['operationCode'] : '';
            if (!empty($operationCode)) {
                $params[$operationType] = $operationCode;
            }
            $condition = $this->serviceClass->getMatchFields($params);
            if(isset($params['company'])){
                $condition['company']=trim($params['company']);
            }
            $condition['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
            $condition['dateTo'] = isset($params['dateTo']) ? $params['dateTo'] : '';
            $condition['cash_type'] = isset($params['cash_type']) ? $params['cash_type'] : '';
            $condition['is_frozen'] = isset($params['is_frozen']) ? $params['is_frozen'] : 0;
            $condition['form_type'] = isset($params['form_type']) ? $params['form_type'] : '';
            $condition['customer_platform'] = isset($params['platform']) ? $params['platform'] : '';
            if($condition['is_frozen'] == 'all'){
                unset($condition['is_frozen']);
            }
            $count = $this->serviceClass->getLeftJoinByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count) {
                $showFields = array(
                    'customer_code',
                    'customer_firstname',
                    'customer_lastname',
                    'customer_email',
                    'customer_telephone',
                    'customer_fax',
                    'customer_status',
                    'customer_saler_user_id',
                    'customer_cser_user_id',
                    'customer_reg_time',
                    'customer_id',
                    'last_login_time',
                    'customer_company_name',
                    'cash_type',
                    'is_frozen',
                    'form_type'
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getLeftJoinByCondition($condition, $showFields, $pageSize, $page, array('customer_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['customerStatus'] = $customerStatus;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->customerStatus = $customerStatus;
        $this->view->formType = Service_CustomerProcess::$formType;
        $this->view->signCompany = Service_CustomerProcess::getDefaultSignCompany();
        $this->view->platform = Service_CustomerProcess::getPlatform();
        $sellerService = new Service_UserPosition();
        $sellerPosition = $sellerService->getByCondition(array('up_name'=>'销售'),"*");
        $seller = array();
        $userService = new Service_User();
        foreach($sellerPosition as $key=>$value){
            $userList  = $userService->getByCondition(array('up_id'=>$value['up_id']),"*");
            foreach($userList as $k=>$v){
                if(!in_array($v,$seller)) $seller[] = $v;
            }
        }
        $this->view->seller = $seller;

        $serverPosition = $sellerService->getByCondition(array('up_name'=>'客服'),"*");
        $server = array();
        foreach($serverPosition as $key=>$value){
            $userList = $userService->getByCondition(array('up_id'=>$value['up_id']),"*");
            foreach($userList as $k=>$v){
                if(!in_array($v,$server)) $server[] = $v;
            }
        }
        $this->view->server = $server;
        echo Ec::renderTpl($this->tplDirectory . "customer_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage' => array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'customer_id' => '',
                'customer_firstname' => '',
                'customer_lastname' => '',
                'customer_email' => '',
                'customer_telephone' => '',
                'customer_fax' => '',
                'customer_status' => '',
                'customer_saler_user_id' => '',
                'customer_cser_user_id' => '',
				'customer_update_time'=>date('Y-m-d H:i:s',time())
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            $paramId = $row['customer_id'];
            if (!empty($row['customer_id'])) {
                unset($row['customer_id']);
            }
            $errorArr = $this->serviceClass->validator($row);

            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.');
            }

        }
        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, 'customer_id')) {
            $rows = $this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function getInfoByIdAction(){
        $id = $this->_request->getParam('id',"");
        $getBy = $this->_request->getParam('getBy','');
        $customerService = new Service_Customer();
        if($getBy=='customer_code'){
        	$customerRow = $customerService->getByField($id,'customer_code',"*");
        	if(empty($customerRow)){
        		$result = array(
        				'state'=>'0',
        				'message'=>'客户无效',
        				'data'=>$customerRow
        		);
        		//die(Zend_Json::encode($result));
        	}
        }else{
        	$customerRow = $customerService->getByField($id,'customer_id',"*");
        }
        if(!empty($customerRow)){
        	//获取客户的余额
        	$balance = Service_CustomerBalance::getByField($customerRow['customer_code'],'customer_code');
        	//print_r($balance);
        	if(!empty($balance)){
        		$customerRow['cb_value'] = $balance['cb_value'];
        	}else{
        		$customerRow['cb_value'] = '0';
        	}
            //取签约主体
            $customerRow['sign_company'] = Service_CustomerProcess::getSignCompany( $customerRow['customer_code'] );
            //获取冻结的税金
            $customerRow['frozen_tax_amount'] = $balance['frozen_tax_amount'];
        }
        $result = array(
            'state'=>'1',
            'message'=>'',
            'data'=>$customerRow
        );
        die(Zend_Json::encode($result));
    }
	/*修改客户信息*/
    public function changeAction(){
        $params = $this->_request->getParams();
        $params['files'] = $_FILES;
        $obj = new Service_CustomerProcess();
        $result = $obj->edit( 'edit', $params );
        die(Zend_Json::encode( $result ) );
    }

    public function allocationAction(){
        $customer_id = $this->_request->getParam('c_id',"");
        $customer_cser_user_id = $this->_request->getParam('customer_cser_user_id',"0");
        $customer_saler_user_id = $this->_request->getParam('customer_saler_user_id',"0");
        $customerService = new Service_Customer();
        if($customerService->update(array('customer_cser_user_id'=>$customer_cser_user_id),$customer_id,'customer_id')&&
            $customerService->update(array('customer_saler_user_id'=>$customer_saler_user_id),$customer_id,'customer_id')){
            $result = array(
                'state'=>'1',
                'message'=>'allocation Success.',
            );
            die(Zend_Json::encode($result));
        }else{
            die(0);
        }
    }
	/*客户资料详情*/
    public function detailAction(){
        $customer_code = $this->_request->getParam('customer_code',"");
        $customer = Service_Customer::getByField($customer_code,"customer_code","*");
		
		if($customer['customer_country']){
			$country_array = Service_Country::getByField($customer['customer_country']);
			$customer['customer_country'] =  $country_array['country_name'];			
		}
        $formType = Service_CustomerProcess::$formType;
        $customer['form_type_text'] = isset( $formType[ $customer['form_type'] ] ) ? $formType[ $customer['form_type'] ] : '';
        $defaultSignCompany = Service_CustomerProcess::getDefaultSignCompany();
        $signCompany = Service_CustomerProcess::getSignCompany( $customer_code );
        $customer['sign_company_text'] = $defaultSignCompany[$signCompany];
        $this->view->customer = $customer;
		
        $this->view->seller = Service_User::getByField($customer['customer_saler_user_id'],"user_id","*");
        $this->view->server = Service_User::getByField($customer['customer_cser_user_id'],"user_id","*");
		
		
		$this->view->currency	= Common_DataCache::getCurrency();
		$country	= Common_DataCache::getCountry();
		$this->view->country	= $country;
        $this->view->signCompany = $defaultSignCompany;
		//print_r(Common_DataCache::getCountry());exit;
		$this->view->sellerList = Service_User::getByCondition(array("ud_id"=>5));//销售代表
        $this->view->serverList = Service_User::getByCondition(array("ud_id"=>4));//客服
        //0:未注册完成;1:已注册完成;2:已激活;3:停用
        $this->view->statusArr = array(
            '0'=>'未完成注册',
            '1'=>'待审核',
            '2'=>'正常',
            '3'=>'停用'
        );
        $this->view->regStatus = array(
            '0'=>'初始状态',
            '1'=>'未完成',
            '2'=>'未完成',
            '3'=>'完成'
        );
        $this->view->balance = Service_CustomerBalance::getByField($customer['customer_code'],"customer_code","*");
        //1:收件人;2:发件人;3:回邮地址;4:公司地址
        $this->view->addressTypeArr = array(
            '1'=>'收件人',
            '2'=>'发件人',
            '3'=>'回邮地址',
            '4'=>'公司地址'
        );
        $addressList = Service_CustomerAddressBook::getByCondition(array('customer_code'=>$customer['customer_code']),"*");
        foreach($addressList as $key=>$value){
            //$country = Service_Country::getByField($value['cab_country_id'],"country_id","*");
            $addressList[$key]['country_name'] = $country[$value['cab_country_id']]['country_name'];
        }
        $this->view->addressList = $addressList;
        $customerLogs = Service_CustomerLog::getByCondition(array('cl_customer_code'=>$customer_code),"*");
        if(!empty($customerLogs) && is_array($customerLogs)){
            foreach ($customerLogs as $key => $customerLogRow) {
                $userRow = Service_User::getByField($customerLogRow['cl_user_id'], 'user_id', array('user_name'));
                $customerLogs[$key]['cl_user_name'] = $userRow['user_name'];
            }
        }
        $this->view->customerLogs = $customerLogs;
       /*
	    $balanceLog = Service_CustomerBalanceLog::getByCondition(array('customer_code'=>$customer['customer_code']),"*");
		foreach($balanceLog as $k=>$v){
            if($v['user_id']==-1){
			$balanceLog[$k]['user_code'] = $balanceLog[$k]['customer_code'];
			}else{
			$user = Service_User::getByField($v['user_id'],'user_id',"*");
            $balanceLog[$k]['user_code'] = $user['user_code'];
			}
			$balanceLog[$k]['cbl_type'] = Service_CustomerBalanceLog::getTypeText($v['cbl_type']);
        }
        $this->view->balanceLog = $balanceLog;
		*/
        $this->view->formType = $formType;
        echo Ec::renderTpl($this->tplDirectory . "customer_detail.tpl", 'layout');
    }
    
    
    /**
     * @author william-fan
     * @todo 客户充值
     */
    public function balanceAction(){
    	if($this->_request->isPost()){
    		//print_r($this->_request->getParams());
    		$customerCode 			= $this->_request->getParam('customer_code','');
    		$chongzhiCurrencyCode 	= $this->_request->getParam('chongzhi_currency_code','');
    		$arriveMoney			= $this->_request->getParam('arriveMoney','');
    		$currencyRate			= $this->_request->getParam('currency_rate','');
    		$transactionNumber		= $this->_request->getParam('transaction_number','');
			$type					= $this->_request->getParam('type','');
			$cbl_note				= $this->_request->getParam('cbl_note','');
			$arrive_time			= $this->_request->getParam('arrive_time','');
    		$balanceRow = array(
    			'customer_code'=>$customerCode,
    			'currency_code'=>$chongzhiCurrencyCode,
    			'cbl_value'=>$arriveMoney,
    			'currency_rate'=>$currencyRate,
    			'transaction_number'=>$transactionNumber,
    			'cbl_type'=>$type,
    			'cbl_note'=>$cbl_note,
    			'arrive_time'=>$arrive_time,								
    		);
    		$result = Service_CustomerBalanceProcess::chongzhi($balanceRow);
    		die(Zend_Json::encode($result));
    	}
		
    	echo Ec::renderTpl($this->tplDirectory . "customer-balance.tpl", 'layout');
    }
    
    /**
     * 审核
     * @author solar
     */
    public function verifyAction(){
        $params = $this->_request->getParams();
        $obj = new Service_CustomerProcess();
        $result = $obj->edit( 'audit', $params );
        die(Zend_Json::encode( $result ) );
    }
	
  /*获取客户交易记录*/
  public function getTransactionRecordAction(){
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);

        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 20;

        $customerCode = trim($this->_request->getParam("customer_code",""));
		$cbl_type = trim($this->_request->getParam("cbl_type",""));
		$cbl_refer_code = trim($this->_request->getParam("cbl_refer_code",""));
		
		$dateFor = trim($this->_request->getParam("dateFor",""));
		$dateTo = trim($this->_request->getParam("dateTo",""));
	
		$cbl_refer_type = trim($this->_request->getParam("cbl_refer_type",""));
		$cbl_fee_name = trim($this->_request->getParam("cbl_fee_name",""));

        $condition = array(
            'customer_code'=>$customerCode,
			'cbl_type'=>$cbl_type,
			'cbl_refer_code'=>$cbl_refer_code,
			'dateFor'=>$dateFor,
			'dateTo'=>$dateTo,
        );
		
		/*参考类型*/
		switch($cbl_refer_type){
			case '1'://订单
				//普通+默认物流
				$application = Service_Application::getByCondition(array('application_code'=>'order','customer_code_empty'=>'','customer_id_empty'=>0));
				$fee_id_array[] = 0;				
				if($application && sizeof($application)==1){
					$fee_id_array[] = $application[0]['application_id'];								
				}				
				$condition['fee_id_array1'] = $fee_id_array;					
			break;
			case '2'://ASN			
				$fee_array = Service_OtherFee::getJoinApplicationByCondition(array('application_code'=>'ASN'));
				$fee_id_array = array();
				if($fee_array){
					foreach($fee_array as $row){
						$fee_id_array[] = 	$row['fee_id'];
					}			
				}
				$condition['fee_id_array1'] = $fee_id_array;	
			
			break;		
		}		
		/*费用名称*/
		if($cbl_fee_name){
			switch($cbl_fee_name){
				case '物流费':
				$fees = Service_OtherFee::getByCondition(array('fee_name'=>'物流费'));
				$fee_id_array[] = 0;				
				if($fees){
					foreach($fees as $row){
						$fee_id_array[] = $row['fee_id'];
					}								
				}				
				$condition['fee_id_array'] = $fee_id_array;	
				break;			
				default:
				$fees = Service_OtherFee::getByCondition(array('fee_name'=>$cbl_fee_name));
				$fee_id_array = array();	
				if($fees){
					foreach($fees as $row){
						$fee_id_array[] = $row['fee_id'];
					}	
					
					$condition['fee_id_array'] = $fee_id_array;									
				}else{
					$condition['fee_id_array'] = array('-1');	
				}				
							
				
			}
		}
		
        $count = Service_CustomerBalanceLog::getByCondition($condition,'count(*)');
        $balanceLog = Service_CustomerBalanceLog::getByCondition($condition,"*",$pageSize,$page,'cbl_id desc');
        foreach($balanceLog as $k=>$v){
            $user = Service_User::getByField($v['user_id'],'user_id',"*");
            $balanceLog[$k]['user_code'] = $user['user_code'];
			if($balanceLog[$k]['application_code'] == ''){$balanceLog[$k]['application_code'] = 'order';}
            if($v['fee_id']>0){
            	$otherfee=Service_OtherFee::getByField($v['fee_id']);				
            	if(!empty($otherfee)){
            		$balanceLog[$k]['fee_name'] = $otherfee['fee_name'];
            		$application = Service_Application::getByField($otherfee['fee_application_id']);
            		$balanceLog[$k]['application_name'] = $application['application_name'];
					$balanceLog[$k]['application_code'] = $application['application_code'];
            	}else{
            		$balanceLog[$k]['fee_name'] = '物流费';
            		$balanceLog[$k]['application_name'] = '订单';
            	}
            }else{
            	$balanceLog[$k]['fee_name'] = '物流费';
            	$balanceLog[$k]['application_name'] = '订单';
            }	
			
			$balanceLog[$k]['cbl_type'] = Service_CustomerBalanceLog::getTypeText($v['cbl_type']);
        }
		//print_r($balanceLog);exit;
        $return['data'] = $balanceLog;
        $return['state'] = 1;
        //$return['customerStatus'] = $customerStatus;
        $return['message'] = "";
        $return['total'] = $count;
        die(json_encode($return));
    } 
 
 
	/*交易记录导出*/
    public function exportTransactionRecordsAction(){

		set_time_limit(0);
		$customerCode = $this->_request->getParam("customer_code","");
		if(!$customerCode){echo "必须提供客户代码";exit;}
        $condition = array(
            'customer_code'=>$customerCode
        );
    	
		$customer = Service_Customer::getByField($customerCode,'customer_code');
		if(!$customer){echo "客户代码是错误的";exit;}		
 	
    	$cb_arr = $this->_request->getParam('cb_arr','');    	
    	$exportformat = 'xls';
    	$fileName = 'finance'.date('Y-m-d-H-i-s').'.'.$exportformat;	
		
    	
    	if(!empty($cb_arr)){		//通过选择的订单获取
					
    		if($exportformat=='xls'){
    			$orderHtml = '<table border="1"><tr>';	
				$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 .= '<td>客户币种</td>';
    			$htmlTitle .= '<td>可用余额</td>';
				$htmlTitle .= '<td>冻结余额</td>';
    			$htmlTitle .= '<td>时间</td>'; 
				
    			$titlesku = '';
    			$orderContent = '';
    			$max = 1;				
    			foreach($cb_arr as $key=>$cb_id){
    				 $customerBalanceLog = Service_CustomerBalanceLog::getByField($cb_id, 'cbl_id');
					 if(!$customerBalanceLog){continue;}
					// $customerBalanceLog['cbl_type_text'] = Service_CustomerBalanceLog::getTypeText($customerBalanceLog['cbl_type']);
					// $customerBalanceLog['cbl_refer_type_text'] = Service_CustomerBalanceLog::getCblReferTypeText($customerBalanceLog['cbl_refer_type']); 
        			$user = Service_User::getByField($customerBalanceLog['user_id'],'user_id',"*");
            		$customerBalanceLog['user_code'] = $user['user_code'];
					if($customerBalanceLog['application_code'] == ''){$customerBalanceLog['application_code'] = 'order';}            		
					if($customerBalanceLog['fee_id']>0){
            			$otherfee=Service_OtherFee::getByField($customerBalanceLog['fee_id']);								
            			if(!empty($otherfee)){
            				$customerBalanceLog['fee_name'] = $otherfee['fee_name'];
            				$application = Service_Application::getByField($otherfee['fee_application_id']);
            				$customerBalanceLog['application_name'] = $application['application_name'];
							$customerBalanceLog['application_code'] = $application['application_code'];
							
            			}else{
            				$customerBalanceLog['fee_name'] = '物流费';
            				$customerBalanceLog['application_name'] = '订单';
            			}
            		}else{
            			$customerBalanceLog['fee_name'] = '物流费';
            			$customerBalanceLog['application_name'] = '订单';
            		}	
			
					$customerBalanceLog['cbl_type_text'] = Service_CustomerBalanceLog::getTypeText($customerBalanceLog['cbl_type']);

					
    				 $orderContent.="<tr>";
					 //客户代码
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['customer_code']}</td>";
					 //费用名称
 					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['fee_name']}</td>"; 
					 
					 //参考号
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_refer_code']}</td>";					 
					
					 //参考类型
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['application_name']}</td>";
					 //交易类型				 
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_type_text']}</td>";	 
    				 //金额    				 
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_value']}</td>";
    				 //汇率
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['currency_rate']}</td>";
    				 //币种
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['currency_code']}</td>";
    				 //折合客户币种
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_transaction_value']}</td>";
    				 //客户币种
					 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customer['customer_currency']}</td>"; 
					 //可用余额
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_current_value']}</td>";
    				 //冻结金额
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_current_hold_value']}</td>";					 
    				 //时间
    				 $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_add_time']}</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{		
				$customer_code = trim($this->_request->getParam('customer_code','')); 
				$cbl_type = $this->_request->getParam('cbl_type','');  
				$dateFor = $this->_request->getParam('dateFor','');  
				$dateTo = $this->_request->getParam('dateTo','');
				
				$cbl_refer_type = trim($this->_request->getParam("cbl_refer_type",""));
				$cbl_fee_name = trim($this->_request->getParam("cbl_fee_name",""));								
        		
				$condition	= array(
            		'customer_code'=>$customerCode,
					'cbl_type'=>$cbl_type,
					'dateFor'=>$dateFor,
					'dateTo'=>$dateTo,				
					'cbl_refer_code'=>$cbl_refer_code,								
        		);
        	
        	
				/*参考类型*/
				switch($cbl_refer_type){
					case '1'://订单
						//普通+默认物流
						$application = Service_Application::getByCondition(array('application_code'=>'order','customer_code_empty'=>'','customer_id_empty'=>0));
						$fee_id_array[] = 0;				
						if($application && sizeof($application)==1){
							$fee_id_array[] = $application[0]['application_id'];								
						}				
						$condition['fee_id_array1'] = $fee_id_array;					
					break;
					case '2'://ASN			
						$fee_array = Service_OtherFee::getJoinApplicationByCondition(array('application_code'=>'ASN'));
						$fee_id_array = array();
						if($fee_array){
							foreach($fee_array as $row){
								$fee_id_array[] = 	$row['fee_id'];
							}			
						}
						$condition['fee_id_array1'] = $fee_id_array;	
					
					break;		
				}		
				/*费用名称*/
				if($cbl_fee_name){
					switch($cbl_fee_name){
						case '物流费':
						$fees = Service_OtherFee::getByCondition(array('fee_name'=>'物流费'));
						$fee_id_array[] = 0;				
						if($fees){
							foreach($fees as $row){
								$fee_id_array[] = $row['fee_id'];
							}								
						}				
						$condition['fee_id_array'] = $fee_id_array;	
						break;			
						default:
						$fees = Service_OtherFee::getByCondition(array('fee_name'=>$cbl_fee_name));
						$fee_id_array = array();	
						if($fees){
							foreach($fees as $row){
								$fee_id_array[] = $row['fee_id'];
							}	
							$condition['fee_id_array'] = $fee_id_array;									
						}else{
							$condition['fee_id_array'] = array('-1');	
						}					
									
						
					}
				}				   		
					
    		$count = Service_CustomerBalanceLog::getByCondition($condition, 'count(*)');
    		if($count>0){
    			$pageSize = 20;
    			$pages = ceil($count/20);

    			$orderHtml = '<table border="1"><tr>';
				$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 .= '<td>客户币种</td>';
    			$htmlTitle .= '<td>可用余额</td>';
				$htmlTitle .= '<td>冻结余额</td>';
    			$htmlTitle .= '<td>时间</td>'; 
    			$titlesku = '';
    			$orderContent = '';

    			$max = 1;

    			for($page=1;$page<=$pages;$page++){
    				$rows = Service_CustomerBalanceLog::getByCondition($condition, '*', $pageSize,$page,'cbl_id desc');
					if(!$rows){continue;}
					
    				foreach($rows as $keyo=>$customerBalanceLog){ 

        				$user = Service_User::getByField($customerBalanceLog['user_id'],'user_id',"*");
            			$customerBalanceLog['user_code'] = $user['user_code'];
						if($customerBalanceLog['application_code'] == ''){$customerBalanceLog['application_code'] = 'order';}            		
						if($customerBalanceLog['fee_id']>0){
            				$otherfee=Service_OtherFee::getByField($customerBalanceLog['fee_id']);								
            				if(!empty($otherfee)){
            					$customerBalanceLog['fee_name'] = $otherfee['fee_name'];
            					$application = Service_Application::getByField($otherfee['fee_application_id']);
            					$customerBalanceLog['application_name'] = $application['application_name'];
								$customerBalanceLog['application_code'] = $application['application_code'];
							
            				}else{
            					$customerBalanceLog['fee_name'] = '物流费';
            					$customerBalanceLog['application_name'] = '订单';
            				}
            			}else{
            				$customerBalanceLog['fee_name'] = '物流费';
            				$customerBalanceLog['application_name'] = '订单';
            			}	
			
						$customerBalanceLog['cbl_type_text'] = Service_CustomerBalanceLog::getTypeText($customerBalanceLog['cbl_type']);

  					
    					 $orderContent.="<tr>";					 	 
						//客户ID												
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['customer_code']}</td>";
						//费用名称
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['fee_name']}</td>";
						//参考号
					 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_refer_code']}</td>";	
					    //参考类型
						$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['application_name']}</td>";				
										
						//交易类型 
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_type_text']}</td>";

    				 	//金额    				 
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_value']}</td>";
    				 	//汇率
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['currency_rate']}</td>";
    					 //币种
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['currency_code']}</td>";
    				 	//折合客户币种
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_transaction_value']}</td>";
	    				 // 客户币种
					    $orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customer['customer_currency']}</td>";					
    				 	
						//可用余额
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_current_value']}</td>";
    				 	//冻结金额
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_current_hold_value']}</td>";					 
    				 	//时间
    				 	$orderContent.="<td style='vnd.ms-excel.numberformat:@;'>{$customerBalanceLog['cbl_add_time']}</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;

    }   
    /**
     * @desc 导出客户
     */
    public function exportAction()
    {
        if ($this->_request->isPost()) {
            $codes =$this->_request->getParam('codes',array());
            if (!empty($codes)) {

            }else{
            $params = $this->_request->getParams();
            $operationType = isset($params['operationType']) ? trim($params['operationType']) : '';
            $operationCode = isset($params['operationCode']) ? trim($params['operationCode']) : '';
            if (!empty($operationCode)) {
                $params[$operationType] = $operationCode;
            }
            $condition = $this->serviceClass->getMatchFields($params);
            if(isset($params['company'])){
                $condition['company']=trim($params['company']);
            }
            $condition['dateFor'] = isset($params['dateFor'])?$params['dateFor']:'';
            $condition['dateTo'] = isset($params['dateTo'])?$params['dateTo']:'';
            $condition['cash_type'] = isset($params['cash_type'])?$params['cash_type']:'';
            $condition['is_frozen'] = isset($params['is_frozen']) ? $params['is_frozen'] : 0;
            $condition['customer_platform'] = isset($params['platform']) ? $params['platform'] : '';
            $rows = $this->serviceClass->getLeftJoinByCondition($condition);
                if (!empty($rows)) {
                    $codes=array();
                    foreach ($rows as $key => $value) {
                        $codes[]=$value['customer_code'];
                    }
                }
            }
            
            $filename = "customer".date("YmdHis");
            require_once("PHPExcel.php");
            require_once("PHPExcel/Reader/Excel2007.php");
            require_once("PHPExcel/Reader/Excel5.php");
            require_once ('PHPExcel/IOFactory.php');

            $objExcel = new PHPExcel();
            $objProps = $objExcel->getProperties();
            $objProps->setCreator('EC');
            $objProps->setTitle('Template');
            $objExcel->setActiveSheetIndex(0);

            $objActSheet = $objExcel->getActiveSheet();

            $objActSheet->getColumnDimension('A')->setWidth(15);
            $objActSheet->getColumnDimension('B')->setWidth(25);
            $objActSheet->getColumnDimension('C')->setWidth(20);
            $objActSheet->getColumnDimension('D')->setWidth(20);
            $objActSheet->getColumnDimension('E')->setWidth(20);
            $objActSheet->getColumnDimension('F')->setWidth(25);
            $objActSheet->getColumnDimension('G')->setWidth(15);
            $objActSheet->getColumnDimension('H')->setWidth(20);
            $objActSheet->getColumnDimension('I')->setWidth(20);
            $objActSheet->getColumnDimension('J')->setWidth(20);
            $objActSheet->setCellValue('A1','客户代码');
            $objActSheet->setCellValue('B1','公司名称');
            $objActSheet->setCellValue('C1','NAME');
            $objActSheet->setCellValue('D1','签约主体');
            $objActSheet->setCellValue('E1','客户平台');
            $objActSheet->setCellValue('F1','邮箱');
            $objActSheet->setCellValue('G1','电话');
            $objActSheet->setCellValue('H1','传真');
            $objActSheet->setCellValue("I1",'状态');
            $objActSheet->setCellValue('J1','注册时间');

            $dataList = array();
            foreach($codes as $k=>$code){
                $customerRow = Service_Customer::getByField($code,"customer_code","*");
                $customerStatus = Common_Status::customerStatus('auto');
                $defaultSignCompany = Service_CustomerProcess::getDefaultSignCompany();
                $signCompany = Service_CustomerProcess::getSignCompany($code);
                $signCompanyText = $defaultSignCompany[$signCompany];
         
                $dataList[$k]['customer_code'] = $code;
                $dataList[$k]['customer_company_name']= $customerRow['customer_company_name'];
                $dataList[$k]['name'] = trim($customerRow['customer_lastname']).trim($customerRow['customer_firstname']);
                $dataList[$k]['sign_company_text'] = $signCompanyText;
                $dataList[$k]['customer_platform'] = $customerRow['customer_platform'];
                $dataList[$k]['customer_email'] = $customerRow['customer_email'];
                $dataList[$k]['customer_telephone'] = $customerRow['customer_telephone'];
                $dataList[$k]['customer_fax'] = $customerRow['customer_fax'];
                $dataList[$k]['customer_status'] = $customerStatus[$customerRow['customer_status']];
                $dataList[$k]['customer_reg_time'] = $customerRow['customer_reg_time'];

            }
           
            $index = 2;
            foreach($dataList as $key=>$value){
                $objActSheet->setCellValue("A".$index,$value['customer_code']);
                $objActSheet->setCellValue("B".$index,$value['customer_company_name']);
                $objActSheet->setCellValueExplicit("C".$index,$value['name'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValue("D".$index,$value['sign_company_text']);
                $objActSheet->setCellValue("E".$index,$value['customer_platform']);
                $objActSheet->setCellValue("F".$index,$value['customer_email']);
                $objActSheet->setCellValueExplicit("G".$index,$value['customer_telephone'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValueExplicit("H".$index,$value['customer_fax'],PHPExcel_Cell_DataType::TYPE_STRING);
                $objActSheet->setCellValue("I".$index,$value['customer_status']);
                $objActSheet->setCellValue("J".$index,$value['customer_reg_time']);
                $index++;
            }

            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name="' . $filename . '.xls');
            header("Content-Disposition:inline;filename=" . $filename . '.xls');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
        }
    }
    
}