<?php
/**
 * Created by JetBrains PhpStorm.
 * User: user
 * Date: 13-7-5
 * Time: 下午4:51
 * To change this template use File | Settings | File Templates.
 */
class Merchant_FinanceController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "merchant/views/finance/";
        $params = self::getFrontController()->getRequest()->getParams();
        $this->view->ac = $params['action'];
    }
	/*交易记录*/
    public function listAction(){
        $page		= $this->getRequest()->getParam('page', 1);
        $pageSize	= $this->getRequest()->getParam('pageSize', 20);
        $session	= new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        $currency = Service_Currency::getByField($sessionData['customer_currency'],'currency_code');
        $condition	= array(
            'customer_code'		=> $sessionData['code'],
            'cbl_type'            => $this->_request->getParam('cbl_type',""),
        	'cbl_refer_code'	=> trim($this->_request->getParam('cbl_refer_code','')),
            'add_time_start' => $this->_request->getParam('add_time_start',""),
            'add_time_end' => $this->_request->getParam('add_time_end',""),
            'fee_id' => $this->_request->getParam("fee_id",""),
            'application_name'=> $this->_request->getParam("application_name",""),
        );
        if($condition['application_name']!=""){
            $application = Service_Application::getByField($condition['application_name'],'application_name',"*");
            $otherFee = Service_OtherFee::getByCondition(array('fee_application_id'=>$application['application_id']),'*');
            $feeIdArr = array();
            foreach($otherFee as $key=>$value){
                $feeIdArr[] = $value['fee_id'];
            }
            if($condition['application_name']=="订单"){
                $feeIdArr[] = 0;
            }
            $condition['fee_id_array'] = $feeIdArr;
        }
        $this->view->row = Service_CustomerBalance::getByField($sessionData['code'],"customer_code","*");
        $count = Service_CustomerBalanceLog::getByCondition($condition,"count(*)");
        $this->view->count = $count;
        $this->view->condition		= $condition;
        $this->view->pageSize	= $pageSize;
        $this->view->page		= $page;
        $this->view->currency = $currency;
        $result = Service_CustomerBalanceLog::getByCondition($condition,"*",$pageSize,$page,"cbl_id DESC");
        foreach($result as $key=>$value){
            $user = Service_User::getByField($value['user_id'],"user_id","*");
            $result[$key]['user_code'] = $user['user_code'];
			if($result[$key]['application_code'] == ''){$result[$key]['application_code'] = 'order';}
            if($value['fee_id']>0){
            	$otherfee=Service_OtherFee::getByField($value['fee_id']);
				
            	if(!empty($otherfee)){
            		$result[$key]['fee_name'] = $otherfee['fee_name'];
            		$application = Service_Application::getByField($otherfee['fee_application_id']);
            		$result[$key]['application_name'] = $application['application_name'];
					$result[$key]['application_code'] = $application['application_code'];
            	}else{
                    $feeType = Service_FeeType::getByField($value['fee_id'],'ft_id');
                    if(!empty($feeType)){
                        $result[$key]['fee_name'] = $feeType['ft_name_cn'];
                    } else {
                        $result[$key]['fee_name'] = '';
                    }
            		$result[$key]['application_name'] = '';
            	}
            }else{
            	$result[$key]['fee_name'] = '';
            	$result[$key]['application_name'] = '';
            }
            if('readjustment' == $value['application_code']){
                $result[$key]['application_name'] = '重新计费';
                $result[$key]['application_code'] = 'readjustment';
            }
        }
		//print_r($result);
        $this->view->result = $result;
        $this->view->cblType = array(
            //0:冻结; 1:解冻; 2:扣款; 3:入款；4:退款
            '0'=>Ec_Lang::getInstance()->getTranslate('Reserved'),//'冻结',
            '1'=>Ec_Lang::getInstance()->getTranslate('Thaw'),//'解冻',
            '2'=>Ec_Lang::getInstance()->getTranslate('Debit'),//'扣款',
            '3'=>Ec_Lang::getInstance()->getTranslate('Depositing'),//'入款'
            '4'=>Ec_Lang::getInstance()->getTranslate('refund'),//退款
            '5'=>Ec_Lang::getInstance()->getTranslate('fronzenTax'),
            '6'=>Ec_Lang::getInstance()->getTranslate('refundTax'),
            '7'=>Ec_Lang::getInstance()->getTranslate('deductTax')
        );
        $this->view->fee = Service_OtherFee::getAll();
        echo Ec::renderTpl($this->tplDirectory . "finance-list.tpl",'noleftlayout');
    }

    public function depositListAction(){
        $page		= $this->getRequest()->getParam('page', 1);
        $pageSize	= $this->getRequest()->getParam('pageSize', 20);
        $session	= new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        $condition	= array(
            'customer_code'		=> $sessionData['code'],
            'cdo_payment_status'            => $this->_request->getParam('cdo_payment_status',""),
        );
        $this->view->condition		= $condition;
        $this->view->pageSize	= $pageSize;
        $this->view->page		= $page;
        $count = Service_CustomerDepositOrder::getByCondition($condition,"count(*)");
        $this->view->count = $count;
        $this->view->result = Service_CustomerDepositOrder::getByCondition($condition,"*",$pageSize,$page,"");
		
        echo Ec::renderTpl($this->tplDirectory . "deposit-list.tpl",'noleftlayout');
    }

    public function rechargeAction(){
        $session	= new Zend_Session_Namespace('customerAuth');
        $sessionData = $session->data;
        $customer = Service_Customer::getByField($sessionData['code'],'customer_code',"*");
        $balance = Service_CustomerBalance::getByField($sessionData['code'],"customer_code","*");
        $this->view->customer = $customer;
        $this->view->balance = $balance;
        echo Ec::renderTpl($this->tplDirectory . "recharge.tpl",'noleftlayout');
    }

    public function exportAction(){
        set_time_limit(0);
        $orderArr = $this->_request->getParam('orderArr','');
        $exportType = $this->_request->getParam("exportType","");

        $customer = $this->_customerAuth;
        $customerId = $customer['id'];
        $customerRow = Service_Customer::getByField($customerId);

        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name=CustomerBalanceLog.xls');
        header("Content-Disposition:inline;filename=CustomerBalanceLog.xls");
        $html = "<table border='1'>";
        $html.="<tr>";
        $html.="<td>客户代码</td>";
        $html.="<td>费用名称</td>";
        $html.="<td>参考号</td>";
        $html.="<td>参考类型</td>";
        $html.="<td>交易类型</td>";
        $html.="<td>金额</td>";
        $html.="<td>汇率</td>";
        $html.="<td>币种</td>";
        $html.="<td>折合客户币种</td>";
        $html.="<td>客户币种</td>";
        $html.="<td>可用余额</td>";
        $html.="<td>冻结余额</td>";
        $html.="<td>时间</td>";
        $html.="</tr>";
        $cblType = array(
            '0'=>'冻结',
            '1'=>'解冻',
            '2'=>'扣款',
            '3'=>'入款',
            '4'=>'退款',
        );
        if(!empty($orderArr)&&$exportType=="1"){
            foreach($orderArr as $val){
                $customerBalanceLog = Service_CustomerBalanceLog::getByField($val,'cbl_id',"*");
                $html.='<tr>';
                $html.="<td>".$customerBalanceLog['customer_code']."</td>";
                $fee = Service_OtherFee::getByField($customerBalanceLog['fee_id'],'fee_id',"*");
                if($customerBalanceLog['fee_id']>0){
                    if(!empty($fee)){
                        $html.="<td>".$fee['fee_name']."</td>";
                    } else {
                        $feeType = Service_FeeType::getByField($customerBalanceLog['fee_id'],'ft_id');
                        if(!empty($feeType)){
                            $html.="<td>".$feeType['ft_name_cn']."</td>";
                        } else {
                            $html.="<td>物流费</td>";
                        }
                    }
                }else{
                    $html.="<td>物流费</td>";
                }
                $html.="<td>".$customerBalanceLog['cbl_refer_code']."</td>";
                if($customerBalanceLog['fee_id']>0){
                    if(!empty($fee)){
                        $application = Service_Application::getByField($fee['fee_application_id']);
                        $html.="<td>".$application['application_name']."</td>";
                    } else{
                        if('readjustment' == $customerBalanceLog['application_code']){
                            $html.="<td>重新计费</td>";
                        } else{
                            $html.="<td>订单</td>";
                        }
                    }
                }else{
                    $html.="<td>订单</td>";
                }
                $html.="<td>".$cblType[$customerBalanceLog['cbl_type']]."</td>";
                $html.="<td>".$customerBalanceLog['cbl_value']."</td>";
                $html.="<td>".$customerBalanceLog['currency_rate']."</td>";
                $html.="<td>".$customerBalanceLog['currency_code']."</td>";
                $html.="<td>".$customerBalanceLog['cbl_transaction_value']."</td>";
                $html.="<td>".$customerRow['customer_currency']."</td>";
                $html.="<td>".$customerBalanceLog['cbl_current_value']."</td>";
                $html.="<td>".$customerBalanceLog['cbl_current_hold_value']."</td>";
                $html.="<td>".$customerBalanceLog['cbl_add_time']."</td>";
                $html.="</tr>";
            }
            $html.="</table>";
            echo $html;
            exit;
        }else{
            $session	= new Zend_Session_Namespace('customerAuth');
            $sessionData = $session->data;
            $condition	= array(
                'customer_code'		=> $sessionData['code'],
                'cbl_type'            => $this->_request->getParam('cbl_type',""),
                'cbl_refer_code'	=> trim($this->_request->getParam('cbl_refer_code','')),
                'add_time_start' => $this->_request->getParam('add_time_start',""),
                'add_time_end' => $this->_request->getParam('add_time_end',""),
                'fee_id' => $this->_request->getParam("fee_id",""),
                'application_name'=> $this->_request->getParam("application_name",""),
            );
            if($condition['application_name']!=""){
                $application = Service_Application::getByField($condition['application_name'],'application_name',"*");
                $otherFee = Service_OtherFee::getByCondition(array('fee_application_id'=>$application['application_id']),'*');
                $feeIdArr = array();
                foreach($otherFee as $key=>$value){
                    $feeIdArr[] = $value['fee_id'];
                }
                if($condition['application_name']=="订单"){
                    $feeIdArr[] = 0;
                }
                $condition['fee_id_array'] = $feeIdArr;
            }
            $count = Service_CustomerBalanceLog::getByCondition($condition,"count(*)");
            $pageSize = 20;
            $totalPage = ceil($count/$pageSize);
            for($i=1;$i<=$totalPage;$i++){
                $customerBalanceList = Service_CustomerBalanceLog::getByCondition($condition,"*",$pageSize,$i,"cbl_id DESC");
                foreach($customerBalanceList as $customerBalanceLog){
                    $html.='<tr>';
                    $html.="<td>".$customerBalanceLog['customer_code']."</td>";
                    $fee = Service_OtherFee::getByField($customerBalanceLog['fee_id'],'fee_id',"*");
                    if($customerBalanceLog['fee_id']>0){
                        $html.="<td>".$fee['fee_name']."</td>";
                    }else{
                        $html.="<td>物流费</td>";
                    }
                    $html.="<td>".$customerBalanceLog['cbl_refer_code']."</td>";
                    if($customerBalanceLog['fee_id']>0){
                        $application = Service_Application::getByField($fee['fee_application_id']);
                        $html.="<td>".$application['application_name']."</td>";
                    }else{
                        $html.="<td>订单</td>";
                    }
                    $html.="<td>".$cblType[$customerBalanceLog['cbl_type']]."</td>";
                    $html.="<td>".$customerBalanceLog['cbl_value']."</td>";
                    $html.="<td>".$customerBalanceLog['currency_rate']."</td>";
                    $html.="<td>".$customerBalanceLog['currency_code']."</td>";
                    $html.="<td>".$customerBalanceLog['cbl_transaction_value']."</td>";
                    $html.="<td>".$customerRow['customer_currency']."</td>";
                    $html.="<td>".$customerBalanceLog['cbl_current_value']."</td>";
                    $html.="<td>".$customerBalanceLog['cbl_current_hold_value']."</td>";
                    $html.="<td>".$customerBalanceLog['cbl_add_time']."</td>";
                    $html.="</tr>";
                }
            }
            $html.="</table>";
            echo $html;
            exit;
        }
    }

    public function aliChargeAction(){
        $customer_code = $this->_request->getParam("customer_code","");
        $amount = $this->_request->getParam("amount","");
        $customerRow = Service_Customer::getByField($customer_code,'customer_code',"*");
        $subject = "保宏客户【".$customer_code."】充值【".$amount."RMB】";
        $body = "保宏客户【".$customer_code."】【".$customerRow['customer_company_name']."】充值【".$amount."RMB】";
        $existCharge = Service_Charge::getByCondition(array('customer_code'=>$customer_code),"*",1,1,'charge_id desc');
        if(!empty($existCharge)){
            $timeNow = date("Y-m-d H:i:s");
            $addTime = $existCharge[0]['charge_add_time'];
            $minute=floor((strtotime($timeNow)-strtotime($addTime))%86400/60);
            if($minute<5){
                echo "请勿频繁充值,前后两次充值不要少于5分钟!";
                exit;
            }
            //echo $minute;
        }
        //exit;
        $charge_code = Common_GetNumbers::getOnlyCode('PAYONLY', '', "CPA".$customer_code);
        $chargeRow = array(
            'charge_code'=>$charge_code,
            'customer_id'=>$customerRow['customer_id'],
            'customer_code'=>$customer_code,
            'amount'=>$amount,
            'charge_status'=>0,
            'charge_add_time'=>date("Y-m-d H:i:s"),
            //'to_time',
            'charge_platform'=>'支付宝',
            'charge_content'=>'',
            'charge_subject'=>$subject,
            'charge_body'=>$body,
        );

        Service_Charge::add($chargeRow);

        require_once APPLICATION_PATH . '/../libs/Alipay/alipay.config.php';
        require_once APPLICATION_PATH . '/../libs/Alipay/lib/alipay_submit.class.php';

        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type"	=> $alipay_config['payment_type'],
            "notify_url"	=> $alipay_config['notify_url'],
            "return_url"	=> $alipay_config['return_url'],

            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
            "out_trade_no"	=> $charge_code,
            "subject"	=> $subject,
            "total_fee"	=> $amount,
            "body"	=> $body,
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
            //如"参数名"=>"参数值"

        );
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;
    }
}
