<?php

class Financial_AccountPaymentRecordsController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "financial/views/account/";
        $this->serviceClass = new Service_AccountPaymentRecords();
    }

    public function listAction()
    {
        $settlementCode = Process_BillConfig::settlementCode('auto');
        $sign = Process_BillConfig::sign('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"
            );

            $condition['so_code'] = trim($this->getRequest()->getParam("so_code", ""));
            $condition['pm_code'] = trim($this->getRequest()->getParam("pm_code", ""));
            $condition['payer_code'] = trim($this->getRequest()->getParam("payer_code", ""));
            $condition['ftr_transaction_no'] = trim($this->getRequest()->getParam("transaction_no", ""));
            $condition['dateFor'] = ($this->getRequest()->getParam("dateFor", ""));
            $condition['dateTo'] = ($this->getRequest()->getParam("dateTo", ""));
            $condition['dateFor'] = !empty($condition['dateFor']) ? $condition['dateFor'] . ' 00:00:00' : '';
            $condition['dateTo'] = !empty($condition['dateTo']) ? $condition['dateTo'] . ' 23:59:59' : '';
            //收款类型
            $condition['apr_type'] = 1;
            $count = $this->serviceClass->getAllByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields = array(

                    'account_payment_records.payer_code',
                    'account_payment_records.so_code',
                    'account_payment_records.pm_code',
                    'account_payment_records.ba_id',
                    'apr_amount',
                    'apr_org_amount',
                    'apr_writeoff_amount',
                    'apr_currency_code',
                    'apr_currency_rate',
                    'apr_note',
                    'apr_creator_id',
                    'bill_id',
                    'apr_create_type',
                    'apr_settle_sign',
                    'apr_writeoff_sign',
                    'apr_inneroffset_sign',
                    'apr_transaction_time',
                    'apr_add_time',
                    'account_payment_records.apr_id as apr_ids',
                    'fee_transfer_records.ftr_transaction_no',
                );
                // $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getAllByCondition($condition, $showFields, $pageSize, $page, array('apr_transaction_time desc'));
                 foreach ($rows as $key => $value) {
                    /*print_r($value);exit;*/
                    $bill_code = '';
                    $records = Service_BilCustomerBillBalanceRecords::getByCondition(array('apr_id'=>$value['apr_ids']),array('bcb_id'));
                    if(!empty($records)){
                        foreach ($records as $k => $val) {
                            $bilRow = Service_BilCustomerBill::getByField($val, 'bcb_id');
                            $bill_code .= '<br/>'.$bilRow['bcb_code'];
                        }
                        
                    }
                    $rows[$key]['bill_code'] = $bill_code;
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['settlementCode'] = $settlementCode;
                $return['sign'] = $sign;
            }
            die(Zend_Json::encode($return));
        }
        $this->view->dateFor = "";
        $this->view->dateTo = "";
        $this->view->settlementCode = $settlementCode;
        $this->view->sign = $sign;
        $this->view->paymentMethod = Service_PaymentMethod::getByCondition(array(), array("pm_code", "title"));
        echo Ec::renderTpl($this->tplDirectory . "account_payment_records_index.tpl", 'layout');
    }

    /**
     * @desc 获取费用信息、未出帐列表
     */
    public function getDetailAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'apr_id', array('apr_id', 'so_code', 'payer_code', 'apr_amount', 'apr_writeoff_amount', 'apr_writeoff_sign'))) {

            if ($rows['apr_writeoff_sign'] == 'y') {
                $result = array('state' => 0, 'message' => '此收款记录已被核销');
            } else {
                $rows['amount'] = $rows['apr_amount'] - $rows['apr_writeoff_amount'];

                $result = array('state' => 1, 'message' => '', 'data' => $rows, "billData" => array());

                //writeoff_amount
                switch (strtolower($rows['so_code'])) {
                    case 'cm':
                        $condition = array(
                            'bcb_status' => '3',
                            'bcb_writeoff_sign_neq' => 'y', //未核销
                            'customer_code' => $rows['payer_code'],
                        );
                        $type = array(
                            'bcb_code as code',
                            'bcb_reference_no as refer_no',
                            'bcb_amount as amount',
                            'bcb_bill_date as bill_date',
                            'bcb_id as bill_id',
                        );
                        $billRows = Service_BilCustomerBill::getByCondition($condition, $type, 0, 0, array("bcb_bill_date", "bcb_writeoff_sign desc"));
                        if (empty($billRows)) {
                            $result = array('state' => 0, 'message' => '未找到未核销帐单', 'data' => $rows, "billData" => array());
                        } else {
                            foreach ($billRows as $key => $row) {
                                $total = Service_BilCustomerBillBalanceRecords::getTotalAmount($row['bill_id']);
                                $billRows[$key]['writeoff_amount'] = empty($total) ? $row['amount'] : $row['amount'] - $total;
                            }


                            $result['state'] = 1;
                            $result['data'] = $rows;
                            $result['billData'] = $billRows;
                        }
                        break;
                    case 'su':
                        $result = array('state' => 0, 'message' => '未找到未核销帐单', 'data' => $rows, "billData" => array());
                        break;
                    case 'sp':
                        $result = array('state' => 0, 'message' => '未找到未核销帐单', 'data' => $rows, "billData" => array());
                        break;
                }
            }
        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 手工核销帐单
     */
    public function writeOffBillAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("bill_ids", array());
            $op_apr_id = $this->_request->getParam("op_apr_id", "");
            if (is_array($codes) && !empty($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_CustomerBill();
                foreach ($codes as $code) {
                    $param['code'] = $code;
                    $param['apr_id'] = $op_apr_id;
                    $result['data'][] = $obj->writeOffBillTransaction($param);
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @desc 自动核销帐单
     */
    public function autoWriteOffBillAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $so_code = $this->_request->getParam("awob_so_code", "cm");
            $awob_payer_code = $this->_request->getParam("awob_payer_code", array());
            $awob_payer_code = preg_replace('/[^a-zA-Z0-9_\-]/', ' ', $awob_payer_code);
            $awob_payer_code = preg_replace('/\s+/', ' ', $awob_payer_code);
            $awob_payer_code = trim($awob_payer_code);
            if ($awob_payer_code) {
                $awob_payer_code = explode(' ', $awob_payer_code);
            } else {
                $awob_payer_code = array();
            }
            switch (strtolower($so_code)) {
                case 'cm':
                    $condition = array(
                        'customer_code_arr' => $awob_payer_code,
                        'bcb_status_arr' => array(3, 4),
                        'bcb_writeoff_sign_neq' => 'y', //未核销
                    );
                    $billRows = Table_BilCustomerBill::getInstance()->getBillByCondition($condition, array("bcb_code"), 0, 0, array("customer_code", "bcb_id"));
                    if (!empty($billRows)) {
                        $result['state'] = 1;
                        $result['message'] = '';
                        $obj = new Process_CustomerBill();
                        foreach ($billRows as $row) {
                            $param['code'] = $row['bcb_code'];
                            $param['apr_id'] = '';
                            $result['data'][] = $obj->writeOffBillTransaction($param);
                        }
                    }
                    break;
                case 'su':
                    break;
                case 'sp':

                    break;
                default:
                    break;
            }

        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 详细
     */
    public function viewAction()
    {
        $paramId = $this->_request->getParam("paramId", '0');
        if (empty($paramId)) {
            die("no data");
        }
        $row = Service_AccountPaymentRecords::getByField($paramId, 'apr_id');
        if (empty($row)) {
            die("no data");
        }
        $row['short'] = '';
        $row['company'] = '';
        $row['settlementType'] = '';
        $row['currency'] = '';

        $sign = Process_BillConfig::sign('auto');

        $pmRow = Service_PaymentMethod::getByField($row['pm_code'], 'pm_code');

        $row['pm_code_text'] = isset($pmRow['title']) ? $pmRow['title'] : '';

        if ($row['so_code'] == 'cm') {
            $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
            $cRow = Service_Customer::getByField($row['payer_code'], 'customer_code', array('cash_type', 'customer_short', 'customer_company_name', 'customer_currency'));
            $row['short'] = $cRow['customer_short'];
            $row['currency'] = $cRow['customer_currency'];
            $row['company'] = $cRow['customer_company_name'];;
            $row['settlementType'] = isset($customerSettlementType[$cRow['cash_type']]) ? $customerSettlementType[$cRow['cash_type']] : '';
        }
        $settlementCode = Process_BillConfig::settlementCode('auto');
        $row['settlementCode'] = isset($settlementCode[$row['so_code']]) ? $settlementCode[$row['so_code']] : '';


        $row['ftra_payer_bank_name'] = '';
        $row['ftra_payer_account_name'] = '';
        $row['ftra_payer_account'] = '';


        $userRow = Service_User::getByField($row['apr_creator_id'], 'user_id', array('user_name'));
        $userArr[$row['apr_creator_id']] = isset($userRow['user_name']) ? $userRow['user_name'] : '系统';


        $row['creatorName'] = $userArr[$row['apr_creator_id']];

        $row['ftr_verify_id'] = 0;
        $row['ftr_transaction_no'] = '';
        //来自收款通知
        if ($row['ftr_id'] != '') {
            $ftrRow = Service_FeeTransferRecords::getByField($row['ftr_id'], 'ftr_id');
            if (!empty($ftrRow)) {
                unset($ftrRow['ba_id']);
                $row = array_merge($ftrRow, $row);
            }
        }


        if (!isset($userArr[$row['ftr_verify_id']])) {
            $userRow = Service_User::getByField($row['ftr_verify_id'], 'user_id', array('user_name'));
            $userArr[$row['ftr_verify_id']] = isset($userRow['user_name']) ? $userRow['user_name'] : '系统';
        }


        $row['verifyName'] = $userArr[$row['ftr_verify_id']];


        $row['ba_code'] = '';
        $row['ba_shortcode'] = '';
        $row['ba_name'] = '';
        $row['ba_bankname'] = '';

        //付款信息
        $attrRow = Service_AccountPaymentRecordsAttach::getByField($row['apr_id'], 'apr_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);
        }
        //账单信息
        $bill_code='';
        $bcb_amount="";
        $currency='';
        $records=Service_BilCustomerBillBalanceRecords::getByCondition(array('apr_id'=>$row['apr_id']));
        if (!empty($records)) {
           foreach ($records as $key => $value) {
                 $bilRow = Service_BilCustomerBill::getByField($value['bcb_id'], 'bcb_id');
                    $bill_code .= '<br/>'.$bilRow['bcb_code'];
                    $bcbbr_amount.= '<br/>'.$value['bcbbr_amount'];
                    $bcb_amount .= '<br/>'.$bilRow['bcb_amount'];
                    $currency .='<br/>'.$bilRow['currency_code'];
            }   
        }
        $row['bill_code']=$bill_code;
        $row['bcbbr_amount']=$bcbbr_amount;
        $row['bcb_amount']=$bcb_amount;
        $row['currency_code']=$currency;
        $this->view->data = $row;
        echo Ec::renderTpl($this->tplDirectory . "detail.tpl", 'layout');
    }


}