<?php

class Financial_IncomeController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "financial/views/income/";
    }

    /**
     * @desc 未出帐订单费用
     */
    public function listAction()
    {
        $businessType = Process_BillConfig::businessType('auto');
        $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
        $return = array(
            "state" => 0,
            "message" => "No Data"
        );
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $condition['customer_code'] = trim($this->_request->getParam("customerCode", ""));
            $condition['cash_type'] = trim($this->_request->getParam("customerSettlementType", ""));
            $condition['ds_code'] = trim($this->_request->getParam("businessType", ""));
            $condition['billDate'] = trim($this->_request->getParam("billDate", ""));
            $condition['ft_code'] = trim($this->_request->getParam("ft_code", ""));
            $condition['billDateFrom'] = trim($this->_request->getParam("billDateFrom", ""));

            if (isset($condition['billDateFrom'])) {
                $condition['bi_chargeable_time_start'] = date("Y-m-d H:i:s", strtotime($condition['billDateFrom']));
            }
            if (isset($condition['billDate']) && !empty($condition['billDate'])) {
                $condition['bi_chargeable_time'] = date("Y-m-d H:i:s", strtotime($condition['billDate']));
            }

            $count = Service_BilIncome::getNotAuditOrderGroupByCondition($condition, 'count(*)');

            $return['total'] = $count;

            if ($count) {
                $type = array(
                    'bil_income.bb_id',
                    'bil_income.bi_id',
                    'bil_income.bi_chargeable_time',
                    'bil_income.customer_code',
                    'bil_income.ft_code',
                    'bil_income.sm_code',
                    'sum(bil_income.bi_amount) as bi_amount',
                    'bil_business.ds_code',
                    'customer.cash_type',
                    'customer.customer_currency',
                    'bil_business.ds_code',
                    //  'fee_type.ft_name_cn',
                );
                $rows = Service_BilIncome::getNotAuditOrderGroupByCondition($condition, $type, $pageSize, $page, array("bil_income.bi_chargeable_time"));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['businessType'] = $businessType;
                $return['customerSettlementType'] = $customerSettlementType;
            }
            die(Zend_Json::encode($return));
        }
        $this->view->businessType = $businessType;
        $this->view->customerSettlementType = $customerSettlementType;
        $this->view->billDate = '';
        $this->view->feeType = Service_FeeType::getByCondition();
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }


    /**
     * @desc 按搜索条件导出费用
     */
    public function exportAction()
    {
        if ($this->_request->isPost()) {
            require_once("PHPExcel.php");
            require_once("PHPExcel/Reader/Excel2007.php");
            require_once("PHPExcel/Reader/Excel5.php");
            require_once('PHPExcel/IOFactory.php');
            $codesStr = "F1_" . date("Y-m-d");
            $objExcel = new PHPExcel();
            $objProps = $objExcel->getProperties();
            $objProps->setCreator('EC');
            $objProps->setTitle('Template');
            $objExcel->setActiveSheetIndex(0);

            $objActSheet = $objExcel->getActiveSheet();

            $condition['customer_code'] = trim($this->_request->getParam("customerCode", ""));
            $condition['cash_type'] = trim($this->_request->getParam("customerSettlementType", ""));
            $condition['ds_code'] = trim($this->_request->getParam("businessType", ""));
            $condition['billDate'] = trim($this->_request->getParam("billDate", ""));
            $condition['ft_code'] = trim($this->_request->getParam("ft_code", ""));


            if (isset($condition['billDate']) && !empty($condition['billDate'])) {
                $condition['bi_chargeable_time'] = date("Y-m-d H:i:s", strtotime($condition['billDate']));
            }


            $feeData = Service_BilIncome::getAllFeeData($condition);


            if (!empty($feeData)) {
                //表头
                $ExcelKey = $feeData[1];
                foreach ($ExcelKey as $key => $val) {
                    $objActSheet->setCellValue($key . '1', $val);
                }
                //费用
                foreach ($feeData as $key => $orderArr) {
                    foreach ($ExcelKey as $k => $v) {
                        $val = isset($orderArr[$k]) ? $orderArr[$k] : '';
                        $objActSheet->setCellValue($k . $key, $val);
                    }
                }
            } else {

                $objActSheet->setCellValue('A1', "没有找到匹配的数据");
            }

            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name="' . $codesStr . '.xls');
            header("Content-Disposition:inline;filename=" . $codesStr . '.xls');
            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
            $objWriter->save('php://output');
        }
    }

    /**
     * @desc 获取费用明细信息
     */
    public function detailAction()
    {
        $paramId = $this->_request->getParam('paramId', '0');

        $return = array(
            "state" => 0,
            "message" => "No Data"
        );
        $businessType = Process_BillConfig::businessType('auto');
        $customerSettlementType = Process_BillConfig::customerSettlementType('auto');

        //业务
        $row = Service_BilBusiness::getAttrByField($paramId, 'bb_id');
        //客户
        $cRow = Service_Customer::getByField($row['customer_code'], 'customer_code', array('customer_short', 'customer_currency', 'cash_type'));

        $row = array_merge($row, $cRow);

        if (empty($row)) {
            die("not data");
        }

        if ($this->_request->isPost()) {

            $condition['bb_id'] = $paramId;

            if (empty($condition['bb_id'])) {
                die(Zend_Json::encode($return));
            }

            $count = Service_BilIncome::getFeeDetailByBusinessCondition($condition, 'count(*)');

            $return['total'] = $count;

            if ($count) {
                $rows = Service_BilIncome::getFeeDetailByBusinessCondition($condition, '*', 0, 0);
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        //是否支持重新计费
        $codeArr = Process_Business::readjustment();
        $readjustment = isset($codeArr[$row['ds_code']]) ? 1 : 0;

        $row['ds_code_text'] = isset($businessType[$row['ds_code']]) ? $businessType[$row['ds_code']] : '';
        $row['cash_type_text'] = isset($customerSettlementType[$row['cash_type']]) ? $customerSettlementType[$row['cash_type']] : '';
        $this->view->data = $row;
        $this->view->paramId = $paramId;
        $this->view->readjustment = $readjustment;
        echo Ec::renderTpl($this->tplDirectory . "detail.tpl", 'layout');
    }

    /**
     * @desc 重新计费
     */
    public function readjustmentAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );

        if ($this->_request->isPost()) {
            $refer_code = $this->_request->getParam('refer_code', '');
            $ds_code = $this->_request->getParam('ds_code', '');
            $param = array(
                'refer_code' => $refer_code,
                'ds_code' => $ds_code,
            );
            $obj = new Process_BusinessIncome();
            $result = $obj->readjustmentTransaction($param);
        }
        die(Zend_Json::encode($result));
    }
    /**
     * @todo 逻辑重新计费
     */
    public function refeeAction(){
        /*if ($this->_request->isPost()) {
            $refer_code = $this->_request->getParam('refer_code', '');
            $ds_code = $this->_request->getParam('ds_code', '');
            $param = array(
                'refer_code' => $refer_code,
                'ds_code' => $ds_code,
            );
            $obj = new Process_BusinessIncome();
            $result = $obj->readjustmentTransaction($param);
        }*/
        echo Ec::renderTpl($this->tplDirectory . "refee.tpl", 'layout');
    }
    /**
     * @todo 批量重新计费
     */
    public function batchrefeeAction(){
        $orderUpload = new Zend_Session_Namespace('orderRefee');
        $field = 'batchfee';
        $type = $this->_request->getParam('ds_code','');

        $xlsData = Service_BilIncome::getData($field,$type);

        if(isset($xlsData['ask']) && $xlsData['ask']=='0'){
            //echo 'sss';
            $this->view->uploadinfo = $xlsData;
            echo Ec::renderTpl($this->tplDirectory . "refee.tpl",'layout');
        }else{
            $orderRows = Service_BilIncome::getDataArr($xlsData,$type);
            //print_r($orderRows);

            $orderUpload->uploadData = $orderRows;
            $doupload=true;
            if(!empty($orderRows)){
                foreach($orderRows as $key=>$order){
                    if($order['is_valid']=='0'){
                        $doupload = false;
                    }
                }
            }
            $this->view->doupload=false;
            $this->view->uploadData=$orderRows;
            $this->view->ds_code=$type;

            echo Ec::renderTpl($this->tplDirectory . "refeecheck.tpl",'layout');
        }
    }
    /**
     * @todo 批量重新计费
     */
    public function importfeeAction(){
        set_time_limit(900);
        ini_set('memory_limit', '2048M');
        //预定义变量
        $message = '';
        $success = 0;
        $faise = 0;        
        $orderUpload = new Zend_Session_Namespace('orderRefee');
        $sessionData = $orderUpload->uploadData;
        $ds_code = $this->_request->getParam('ds_code','');
        $select = $this->_request->getParam('select','');
		if(!empty($select)){
	        if(!empty($sessionData)){
	        	foreach($sessionData as $key=>$value){
	        		if(!in_array($value['order_code'], $select)){
	        			$message .= '<div>单号：'.$value['order_code'].': 未选择</div>';
	        			continue;
	        		}
	        		if($value['is_valid']=='1'){
	        			$param = array(
	        					'refer_code' => $value['order_code'],
	        					'ds_code' => $ds_code,
	        			);
	        			//print_r($param);
	        			$obj = new Process_BusinessIncome();
	        			$result = $obj->readjustmentTransaction($param, '1');
	        			if($result['state'] == '1'){
	        				$message.='<div>单号：'.$value['order_code']." : ".$result['message'].'</div>';
	        				$success++;
	        			}else{
	        				$message.='<div>单号：'.$value['order_code']." : ".$result['message'].'</div>';
	        				$faise++;
	        			}
	        		}
	        	}
	        	$message.="<div>合计：成功{$success}个,失败{$faise}个</div>";
	        }else{
	        	$message .= '<div>数据失效</div>';
	        }
		}else{
			$message .= '<div>未选择数据</div>';
		}
        $this->view->uploadResult=$message;
        echo Ec::renderTpl($this->tplDirectory . "refee.tpl",'layout');
    }
    /**
     * @author william-fan
     * @todo 下载模板
     */
    public function downtempleAction(){
        $file = $this->_request->getParam('file','');
        $fullPath = APPLICATION_PATH."/../data/file".'/batchfee.xls';
        //echo $fullPath;exit;
        //方法2
        $filename = basename($fullPath);

        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        // 	header("Content-Transfer-Encoding: binary");
        // 	header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

}