<?php

class Financial_FeePaymentRecordsController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "financial/views/payment/";
        $this->serviceClass = new Service_FeePaymentRecords();
    }

    public function listAction()
    {
        $feePaymentRecordsStatus = Process_BillConfig::feePaymentRecordsStatus('auto');
        $settlementCode = Process_BillConfig::settlementCode('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();
            $condition['payer_code'] = trim($this->_request->getParam('payer_code', ''));
            $condition['so_code'] = trim($this->_request->getParam('so_code', ''));
            $condition['fpr_status'] = trim($this->_request->getParam('fpr_status', ''));
            $condition['fpr_transaction_no'] = trim($this->_request->getParam('fpr_transaction_no', ''));
            $condition['dateFor'] = isset($params['dateFor']) ? $params['dateFor'] : '';
            $condition['dateTo'] = isset($params['dateTo']) ? $params['dateTo'] : '';

            $count = $this->serviceClass->getSearchByCondition($condition, 'count(*)');

            $return['total'] = $count;
            if ($count) {
                $showFields = array(
                    'payer_code',
                    'so_code',
                    'pm_code',
                    'fpr_transaction_no',
                    'fpr_payment_account',
                    'fpr_transaction_date',
                    'fpr_status',
                    'ft_code',
                    'ba_id',
                    'fpr_amount',
                    'fpr_currency_code',
                    'fpr_confirm_time',
                    'fpr_payin_time',
                    'fpr_dishonour_time',
                    'fpr_add_time',
                    'fpr_id',
                    'fpr_note',
                	'bill_id',
                	'bill_id_all'
                );
                $rows = $this->serviceClass->getSearchByCondition($condition, $showFields, $pageSize, $page, array('fee_payment_records.fpr_id desc'));
				if(!empty($rows) && is_array($rows)){
					foreach ($rows as $k=>$v){
						//多条
                        $v['bill_id'] = trim($v['bill_id'], ',');
						if(strpos($v['bill_id'], ',')){
							$billIds = explode(',', trim($v['bill_id'], ','));
							foreach ($billIds as $billId){
								$bsbData = Service_BilServeBill::getByField($billId);
								$rows[$k]['bsb_code'] .= '<br><a href="javascript:viewBillDetail('.$billId.')">'.$bsbData['bsb_code'].'</a>';
								$rows[$k]['bsb_no'] .= '<br>'.$bsbData['bsb_no'];
								$rows[$k]['bsb_id'] .= ','.$bsbData['bsb_id'];
							}
						//单条
						}else{
							$bsbData = Service_BilServeBill::getByField($v['bill_id']);
							$rows[$k]['bsb_code'] = $bsbData['bsb_code'];
							$rows[$k]['bsb_no'] = $bsbData['bsb_no'];
							$rows[$k]['bsb_id'] = $bsbData['bsb_id'];
						}
					}
					foreach ($rows as $sk=>$sv){
					//	$rows[$sk]['bsb_code'] = trim($sv['bsb_code'], '<br>');
						$rows[$sk]['bsb_no'] = trim($sv['bsb_no'], '<br>');
						$rows[$sk]['bsb_id'] = trim($sv['bsb_id'], ',');
					}
				}
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['status'] = $feePaymentRecordsStatus;
            }
            die(Zend_Json::encode($return));
        }
        unset($settlementCode['cm']);
        $this->view->dateFor = date("Y-m-d H:i:s", strtotime("-32 days"));
        $this->view->dateTo = date("Y-m-d H:i:s");
        $this->view->feePaymentRecordsStatus = $feePaymentRecordsStatus;
        $this->view->settlementCode = $settlementCode;
        $this->view->paymentMethod = Service_PaymentMethod::getByCondition(array(), array("pm_code", "title"));
        echo Ec::renderTpl($this->tplDirectory . "fee_payment_records_index.tpl", 'layout');
    }

    /**
     * @desc 详细
     */
    public function viewAction()
    {
        $paramId = $this->_request->getParam("paramId", '0');
        if (empty($paramId)) {
            die("no data");
        }
        $row = Service_FeePaymentRecords::getByField($paramId, 'fpr_id');
        if (empty($row)) {
            die("no data");
        }
        $row['short'] = '';
        $row['company'] = '';
        $row['settlementType'] = '';

        $feePaymentRecordsStatus = Process_BillConfig::feePaymentRecordsStatus('auto');

        $row['fpr_status_text'] = $feePaymentRecordsStatus[$row['fpr_status']];

        $pmRow = Service_PaymentMethod::getByField($row['pm_code'], 'pm_code');

        $row['pm_code_text'] = isset($pmRow['title']) ? $pmRow['title'] : '';
        $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
        switch ($row['so_code']) {
            case 'cm':
                $cRow = Service_Customer::getByField($row['payer_code'], 'customer_code', array('cash_type', 'customer_short', 'customer_company_name'));
                $row['short'] = $cRow['customer_short'];
                $row['company'] = $cRow['customer_company_name'];;
                $row['settlementType'] = isset($customerSettlementType[$cRow['cash_type']]) ? $customerSettlementType[$cRow['cash_type']] : '';
                break;
            case 'sp':
                $cRow = Service_ServiceProvider::getByField($row['payer_code'], 'sp_code', array('sp_settlement_type as cash_type', 'sp_name'));
                $row['company'] = $cRow['sp_name'];;
                $row['settlementType'] = isset($customerSettlementType[$cRow['cash_type']]) ? $customerSettlementType[$cRow['cash_type']] : '';
                break;
        }

        $settlementCode = Process_BillConfig::settlementCode('auto');
        $row['settlementCode'] = isset($settlementCode[$row['so_code']]) ? $settlementCode[$row['so_code']] : '';


        $row['fpra_payee_bank_name'] = '';
        $row['fpra_payee_account_name'] = '';
        $row['fpra_payee_account'] = '';


        $userRow = Service_User::getByField($row['fpr_creator_id'], 'user_id', array('user_name'));
        $userArr[$row['fpr_creator_id']] = isset($userRow['user_name']) ? $userRow['user_name'] : '系统';


        $row['creatorName'] = $userArr[$row['fpr_creator_id']];

        if (!isset($userArr[$row['fpr_payer_id']])) {
            $userRow = Service_User::getByField($row['fpr_payer_id'], 'user_id', array('user_name'));
            $userArr[$row['fpr_payer_id']] = isset($userRow['user_name']) ? $userRow['user_name'] : '系统';
        }

        if (!isset($userArr[$row['fpr_confirm_id']])) {
            $userRow = Service_User::getByField($row['fpr_confirm_id'], 'user_id', array('user_name'));
            $userArr[$row['fpr_confirm_id']] = isset($userRow['user_name']) ? $userRow['user_name'] : '系统';
        }

        if (!isset($userArr[$row['fpr_dishonour_id']])) {
            $userRow = Service_User::getByField($row['fpr_dishonour_id'], 'user_id', array('user_name'));
            $userArr[$row['fpr_dishonour_id']] = isset($userRow['user_name']) ? $userRow['user_name'] : '系统';
        }

        $row['confirmName'] = $userArr[$row['fpr_confirm_id']];
        $row['payerName'] = $userArr[$row['fpr_payer_id']];
        $row['dishonourName'] = $userArr[$row['fpr_dishonour_id']];

        $row['ba_code'] = '';
        $row['ba_shortcode'] = '';
        $row['ba_name'] = '';
        $row['ba_bankname'] = '';

        //付款信息
        $attrRow = Service_FeePaymentRecordAttach::getByField($row['fpr_id'], 'fpr_id');
        if (!empty($attrRow)) {
            $row = array_merge($row, $attrRow);
        }

        $bankRow = Service_BankAccount::getByField($row['ba_id'], 'ba_id');
        if (!empty($bankRow)) {
            $row = array_merge($row, $bankRow);
        }
		if(strpos(trim($row['bill_id'],','), ',') && !empty($row['bill_id_all']) && strpos($row['bill_id_all'], ',')){
			$billIds = explode(',', trim($row['bill_id'], ','));
			//多个账单
			$bsbCode = array();
			foreach ($billIds as $billId){
				$bsbData = Service_BilServeBill::getByField($billId);
				$bsbCode[] = $bsbData['bsb_code'];
			}
			$row['bsb_code'] = join(',', $bsbCode);
		}
        $this->view->data = $row;
        echo Ec::renderTpl($this->tplDirectory . "detail.tpl", 'layout');
    }

    /**
     * @desc 审核费用 转支付
     */
    public function verifyAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $param = array(
                'desc' => $this->_request->getParam("desc", 0),
                'fpr_id' => $this->_request->getParam("fpr_id", 0),
                'opType' => $this->_request->getParam("opType", 0),
            );
            $obj = new Process_Financial();
            $result = $obj->paymentRecordsVerifyTransaction($param);
        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 付款申请
     */
    public function receiptAction()
    {
        $paramId = $this->_request->getParam('paramId', '0');
        $rpType = Process_BillConfig::rpType('auto');
        $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
        $settlementCode = Process_BillConfig::settlementCode('auto');

        $row = array(
            'bi_id' => '',
            'bb_id' => '',
            'bb_refer_code' => '',
            'customer_code' => '',
            'customer_name' => '',
            'ft_code' => '',
            'bi_amount' => '',
            'currency_code' => '',
            'bi_note' => '',
            'cash_type_text' => '',
            'cb_value' => '',
            'bi_rp_type' => '',
            'rpType_text' => '',
            "cash_type" => '', "customer_short" => '', "customer_currency" => ''
        );
        if (!empty($paramId)) {
            $row = Service_BilIncome::getByField($paramId);
            $bbaRow = Service_BilBusinessAttach::getByField($row['bb_id'], 'bb_id');
            $cRow = Service_Customer::getByField($row['customer_code'], 'customer_code');
            $cbRow = Service_CustomerBalance::getByField($row['customer_code'], 'customer_code');
            $row = array_merge($row, $cRow, $cbRow);
            $row['bb_refer_code'] = $bbaRow['bb_refer_code'];
            $row['customer_name'] = $cRow['customer_firstname'] . " " . $cRow['customer_lastname'];
            $row['cash_type_text'] = isset($customerSettlementType[$row['cash_type']]) ? $customerSettlementType[$row['cash_type']] : '未绑定';
            $row['rpType_text'] = isset($rpType[$row['bi_rp_type']]) ? $rpType[$row['bi_rp_type']] : '异常';
        }

        $this->view->feeType = Service_FeeType::getByCondition(array(), '*', 0);
        $this->view->currency = Service_Currency::getByCondition(array(), '*', 0);

        $this->view->title = !empty($row['bb_refer_code']) ? "编辑费用：" . $row['bb_refer_code'] : '新增费用';

        $this->view->data = $row;
        $this->view->settlementCode = $settlementCode;
        $this->view->paymentMethod = Service_PaymentMethod::getByCondition(array(), array("pm_code", "title"));
        $this->view->bankAccount = Service_BankAccount::getByCondition(array(), "*", 0, 0, array("ba_shortcode", "bk_id"));

        echo Ec::renderTpl($this->tplDirectory . "receipt.tpl", 'layout');
    }

    /**
     * @desc 确认提交 产生付款通知
     */
    public function confirmPaymentAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );

        if ($this->_request->isPost()) {
            $paymentMethod = $this->_request->getParam("paymentMethod", '');
            $params = $this->_request->getParams();
            $attach = $param = array();
            if (strtolower($paymentMethod) == 'cash') {
                $param = array(
                    "payer_code" => $params['payerCode'],
                    "so_code" => $params['payerTypeCode'],
                    "pm_code" => 'CASH',
                    "fpr_transaction_no" => $params['cash_transaction_no'],
                    "fpr_transaction_date" => $params['cash_payin_time'],

                    "fpr_status" => '1',
                    "ft_code" => $params['cash_ft_code'],
                    "ba_id" => '',
                    "fpr_amount" => $params['cash_amount'],
                    "fpr_currency_code" => $params['cash_currency_code'],
                    "fpr_note" => $params['cash_note'],
                    "bill_id" => '',
                    "fpr_payin_time" => $params['cash_payin_time'],
                );
            } else {
                $param = array(
                    "payer_code" => $params['payerCode'],
                    "so_code" => $params['payerTypeCode'],
                    "pm_code" => 'BANK',
                    "fpr_transaction_no" => $params['bank_transaction_no'],
                    "fpr_transaction_date" => $params['bank_payin_time'],

                    "fpr_status" => '1',
                    "ft_code" => $params['bank_ft_code'],
                    "ba_id" => $params['bank_ba_id'],
                    "fpr_amount" => $params['bank_amount'],
                    "fpr_currency_code" => $params['bank_currency_code'],
                    "fpr_note" => $params['bank_note'],
                    "bill_id" => '',
                    "fpr_payin_time" => $params['bank_payin_time'],
                );
                $attach = array(
                    'fpa_id' => $params['fpa_id'],
                    'save_payment_account' => (isset($params['save_payment_account']) ? 1 : 0),
                    'ftra_payer_bank_name' => $params['ftra_payer_bank_name'],
                    'ftra_payer_account_name' => $params['ftra_payer_account_name'],
                    'ftra_payer_account' => $params['ftra_payer_account'],
                );
            }
            $obj = new Process_Financial();
            $result = $obj->paymentTransaction($param, $attach);
        }
        die(Zend_Json::encode($result));
    }

}