<?php

class Financial_BilCustomerBillController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "financial/views/customer_bill/";
        $this->serviceClass = new Service_BilCustomerBill();
    }

    public function listAction()
    {
        $bilCustomerBillStatus = Process_BillConfig::bilCustomerBillStatus('auto');
        $bilWriteOffSign = Process_BillConfig::bilWriteOffSign('auto');
        $businessType = Process_BillConfig::businessType('auto');
        $bilReviewSign = Process_BillConfig::bilReviewSign('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 = $this->serviceClass->getMatchFields($params);

            $condition['dateFor'] = (isset($params['dateFor']) && !empty($params['dateFor'])) ? $params['dateFor'] . ' 00:00:00' : '';
            $condition['dateTo'] = (isset($params['dateTo']) && !empty($params['dateTo'])) ? $params['dateTo'] . ' 23:59:59' : '';
            $userName = trim($this->_request->getParam('saler_user', ''));

            if (!empty($userName)) {
                $userRow = Service_User::getByField($userName, 'user_name', array('user_id'));
                $condition['user_id'] = isset($userRow['user_id']) ? $userRow['user_id'] : '-1';
            }

            $count = $this->serviceClass->getJoinLeftByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields = array(

                    'customer_code',
                    'bcb_status',
                    'bcb_code',
                    'bcb_reference_no',
                    'bcb_amount',
                    'bcb_bill_date',
                    'bcb_writeoff_sign',
                    'sm_code',
                    'bcb_note',
                    'bcb_creator_id',
                    'bcb_add_time',
                    'bcb_review_sign',
                    'bcb_delete_id',
                    'bcb_confirm_id',
                    'bcb_verifier_id',
                    'bcb_delete_time',
                    'bcb_confirm_time',
                    'bcb_verify_time',
                    'bcb_id',
                    'currency_code',
                    'bcb_bill_start_date',
                    'ds_code',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getJoinLeftByCondition($condition, $showFields, $pageSize, $page, array('bcb_add_time desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['bilCustomerBillStatus'] = $bilCustomerBillStatus;
                $return['bilReviewSign'] = $bilReviewSign;
                $return['businessType'] = $businessType;
                $return['bilWriteOffSign'] = $bilWriteOffSign;
            }
            die(Zend_Json::encode($return));
        }
        $this->view->businessType = $businessType;
        $this->view->bilWriteOffSign = $bilWriteOffSign;
        $this->view->bilCustomerBillStatus = $bilCustomerBillStatus;
        $this->view->bilReviewSign = $bilReviewSign;
        $this->view->dateFor = date("Y-m-d", strtotime("-32 days"));
        $this->view->dateTo = date("Y-m-d");
        $this->view->SM=Common_DataCache::getShippingMethodSimple();
        $condition = Service_ShippingMethod::getByCondition();

        echo Ec::renderTpl($this->tplDirectory . "bil_customer_bill_index.tpl", 'layout');
    }

    /**
     * @desc 审核费用
     */
    public function verityFeeAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("codes", array());
            $note = $this->_request->getParam("note", "");
            $opType = $this->_request->getParam("opType", "");
            if (is_array($codes) && !empty($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_Business();
                foreach ($codes as $code) {
                    $param['bi_id'] = $code;
                    $param['note'] = $note;
                    $param['opType'] = $opType;
                    $result['data'][] = $obj->verifyBusinessFeeTransaction($param);
                }
            }
        }

        die(Zend_Json::encode($result));
    }


    /**
     * @desc 客户帐单确认
     */
    public function confirmAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("codes", array());
            $note = $this->_request->getParam("note", "");
            $opType = $this->_request->getParam("opType", "1");
            if (!empty($codes) && is_array($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_CustomerBill();
                foreach ($codes as $code) {
                    $param = array(
                        'opType' => 1,
                        'code' => $code,
                        'note' => $note,
                        'is_sales_verify' => true,
                    );
                    $result['data'][] = $obj->checkCustomerBillTransaction($param);
                }
            }
        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 客户帐单提审
     */
    public function verityAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("codes", array());
            $note = $this->_request->getParam("note", "");
            $opType = $this->_request->getParam("opType", "1");
            if (!empty($codes) && is_array($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_CustomerBill();
                foreach ($codes as $code) {
                    $param = array(
                        'opType' => 2,
                        'code' => $code,
                        'note' => $note,
                        'is_sales_verify' => false,
                    );
                    $result['data'][] = $obj->checkCustomerBillTransaction($param);
                }
            }
        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 客户帐单回退
     */
    public function rollbackAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("codes", array());
            $note = $this->_request->getParam("note", "");
            //    $opType = $this->_request->getParam("opType", "1");
            if (!empty($codes) && is_array($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_CustomerBill();
                foreach ($codes as $code) {
                    $param = array(
                        'opType' => 4,
                        'code' => $code,
                        'note' => $note,
                        'is_sales_verify' => false,
                    );
                    $result['data'][] = $obj->checkCustomerBillTransaction($param);
                }
            }
        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 客户帐单作废
     */
    public function cancelAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("codes", array());
            $note = $this->_request->getParam("note", "");
            $opType = $this->_request->getParam("opType", "1");
            if (!empty($codes) && is_array($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_CustomerBill();
                foreach ($codes as $code) {
                    $param = array(
                        'opType' => 0,
                        'code' => $code,
                        'note' => $note,
                        'is_sales_verify' => false,
                    );
                    $result['data'][] = $obj->checkCustomerBillTransaction($param);
                }
            }
        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 批量导出客户帐单费用明细
     */
    public function exportAction()
    {
        error_reporting(E_ALL);
        set_time_limit(3600);
        ini_set('memory_limit', '2048M');
        if ($this->_request->isPost()) {
            $modelus = $this->_request->getParam('accountModules', '');
            $codesStr = $this->_request->getParam('codesStr', '');
            if($modelus == 'shangjia'){
                //暂时只提供单个导出
                $data = Process_CustomerBill3::getsjBillDetailData($codesStr);
                //$this->shangjiaExcel($data);
                //$this->csvExport($data,'shangjia');
            }else if($modelus == 'saiwei'){

                $data = Process_CustomerBill::getswBillDetailData($codesStr);
                //$this->saiweiExcel($data);
                $this->csvExport($data,'saiwei');
            }
            exit;
            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();

            //暂时只提供单个导出
            //$codesStr = $this->_request->getParam('codesStr', '');
            if (!empty($codesStr)) {
                //$data = Process_CustomerBill::getBillData($codesStr);
                $data = Process_CustomerBill::getBillDetailData($codesStr);
                //表头
                $ExcelKey = $data[1];
                foreach ($ExcelKey as $key => $val) {
                    $objActSheet->setCellValue($key . '1', $val);
                }
                //订单
                foreach ($data as $key => $orderArr) {
                    foreach ($ExcelKey as $k => $v) {
                        $val = isset($orderArr[$k]) ? $orderArr[$k] : '';
                        $objActSheet->setCellValue($k . $key, $val);
                    }
                }
            } else {
                $codesStr = "Bill_" . date("Y-m-d");
                $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');
        }
    }
    private function csvExport($data, $type = 'shangjia'){
        if($type == 'shangjia'){
            $title[] = array(
                "A" => 0,//'序号',
                "B" => 1,//'集货模式',
                "C" => 2,//'订单号',
                "D" => 3,//'交易订单号',
                "E" => 4,//'服务商单号',
                "F" => 5,//'交货日期',
                "G" => 6,//'出货日期',
                "H" => 7,//'收货类型',
                "I" => 8,//'出货件数',
                "J" => 9,//'产品数量',
                "K" => 10,//'出货重量（KG）',
                "L" => 11,//'计费重量（KG）',
                "M" => 12,//'目的国家',
                "N" => 13,//'走货渠道',
                "O" => 14,//'分区',
                "P" => 15,//'提货费（RMB）',              //TIHUO
                "Q" => 16,//'库内拣货费',                 //取的操作费，caozuo
                "R" => 17,//'入库费',                     //RUKU
                'S' => 18,//'仓租',                       //取仓储，CANGCHU
                'T'=> 19,//'报关费（RMB）',               //BAOGUAN
                'U'=> 20,//'集中申报费（RMB）',           //JZSBF
                'V'=> 21,//'香港派送费（RMB）',           //PAISONG,PAISONG2
                "W" => 22,//'物流运输费（RMB）',          //重量费用+燃油费+偏远费+单票费
                "X" => 23,//'中港运输费',                 //取的中转运输费，yunshu
                "Y"=> 24,//'监管车费',                    //取的监管运输，jianguanyunshu
                "Z"=> 25,//'其他费用（RMB）',
                'AA'=>26,//'其他费用备注',
                'AB'=>27,//'合计收费（原币种）',
                'AC'=>28,//'合计收费（客户币种）'
                'AD'=>29,//'备注'
                );
            $title[] = array(
                "A" => '序号',
                "B" => '集货模式',
                "C" => '订单号',
                "D" => '交易订单号',
                "E" => '服务商单号',
                "F" => '交货日期',
                "G" => '出货日期',
                "H" => '收货类型',
                "I" => '出货件数',
                "J" => '产品数量',
                "K" => '出货重量（KG）',
                "L" => '计费重量（KG）',
                "M" => '目的国家',
                "N" => '走货渠道',
                "O" => '分区',
                "P" => '提货费（RMB）',              //TIHUO
                "Q" => '库内拣货费',                 //取的操作费，caozuo
                "R" => '入库费',                     //RUKU
                'S' => '仓租',                       //取仓储，CANGCHU
                'T'=> '报关费（RMB）',               //BAOGUAN
                'U'=> '集中申报费（RMB）',           //JZSBF
                'V'=> '香港派送费（RMB）',           //PAISONG,PAISONG2
                "W" => '物流运输费（RMB）',          //重量费用+燃油费+偏远费+单票费
                "X" => '中港运输费',                 //取的中转运输费，yunshu
                "Y"=> '监管车费',                    //取的监管运输，jianguanyunshu
                "Z"=> '其他费用（RMB）',
                'AA'=> '其他费用备注',
                'AB'=> '合计收费(RMB)',
                'AC'=> '合计收费（客户币种）',
                'AD'=> '备注'
                );
        }else{
            $title[] = array(
                "A" => 0,//'序号',
                "B" => 1,//'模式',             //区外
                "C" => 2,//'客户单号',
                "D" => 3,//'订单号',
                "E" => 4,//'服务商单号',
                "F" => 5,//'出货日期',         //取收货时间，receiving_batch_order表add_time
                "G" => 6,//'客户重量',
                "H" => 7,//'目的国家',
                "I" => 8,//'分区',
                "J" => 9,//'走货渠道',
                "K" => 10,//'提货费',           //空
                "L" => 11,//'运费',
                "M" => 12,//'挂号费',
                "N" => 13,//'其他费',           //空
                "O" => 14,//'合计费用（RMB）',
                "P" => 15,//'合计费用（HKD）',  //空
                "Q" => 16,//'备注1',            //空
                "R" => 17,//'备注2',            //空                    
                );
            $title[] = array(
                "A" => '序号',
                "B" => '模式',             //区外
                "C" => '客户单号',
                "D" => '订单号',
                "E" => '服务商单号',
                "F" => '出货日期',         //取收货时间，receiving_batch_order表add_time
                "G" => '客户重量',
                "H" => '目的国家',
                "I" => '分区',
                "J" => '走货渠道',
                "K" => '提货费（RMB）',           //空
                "L" => '运费（RMB）',
                "M" => '挂号费（RMB）',
                "N" => '其他费（RMB）',           //空
                "O" => '合计费用（RMB）',
                "P" => '合计费用（客户币种）',  //空
                "Q" => '备注1',            //空
                "R" => '备注2',            //空                    
                );                             
        }
        if($type == 'shangjia'){
            $floatFiledKey = array('I','J','K','L','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB');
        }else{
            $floatFiledKey = array('G','K','L','M','N','O','P');
        }
        $name = array_shift($data);
        $content = '';      
        if(count($data) > 3){
            $list = array_slice($data, 0, -3);
            foreach ($list as $key => $value) {
                $tempArr = array();
                foreach ($title[0] as $k => $val) {
                    if(in_array($k, $floatFiledKey)){
                        $tempArr[$val] = isset($list[$key][$k]) ? $list[$key][$k] : '';
                    }else{
                        $tempArr[$val] = isset($list[$key][$k]) ? $list[$key][$k]."\t" : '';
                    }
                }
                $content .= implode(',', $tempArr)."\n";
            }
            $end = array_slice($data, -3, 3);
            for ($i=0; $i < 3; $i++) {
                $tempArr = array();
                if($i == 0){
                    foreach ($title[0] as $k => $val) {
                        $tempArr[$val] = isset($end[$i][$k]) ? $end[$i][$k] : '';
                    }
                    $tempArr[0] = '小计';                    
                    $content .= implode(',', $tempArr)."\n";                 
                }else if($i == 1){
                    if($type == 'shangjia'){
                        foreach ($title[0] as $k => $val) {
                            $tempArr[$val] = isset($tempArr[$k]) ? $tempArr[$k] : '';
                        }
                        $tempArr[0] = '税金（税点：6%）';
                        $tempArr[27] = $end[$i]['tallage']['rmb'];
                        $tempArr[28] = $end[$i]['tallage']['cCurrency'];
                        $content .= implode(',', $tempArr)."\n";                            
                    }else{
                        foreach ($title[0] as $k => $val) {
                            $tempArr[$val] = isset($tempArr[$k]) ? $tempArr[$k] : '';
                        }
                        $tempArr[14] = $end[$i]['tallage']['rmb'];
                        $tempArr[15] = $end[$i]['tallage']['cCurrency'];
                        $tempArr[0] = '税金（税点：6%）';
                        $content .= implode(',', $tempArr)."\n";                        
                    }
                }else if($i == 2){
                    if($type == 'shangjia'){
                        foreach ($title[0] as $k => $val) {
                            $tempArr[$val] = isset($tempArr[$k]) ? $tempArr[$k] : '';
                        }
                        $tempArr[0] = '合计';
                        $tempArr[27] = $end[$i]['all']['rmb'];
                        $tempArr[28] = $end[$i]['all']['cCurrency'];
                        $content .= implode(',', $tempArr)."\n";                            
                    }else{
                        foreach ($title[0] as $k => $val) {
                            $tempArr[$val] = isset($tempArr[$k]) ? $tempArr[$k] : '';
                        }
                        $tempArr[0] = '合计';
                        $tempArr[14] = $end[$i]['all']['rmb'];
                        $tempArr[15] = $end[$i]['all']['cCurrency'];
                        $content .= implode(',', $tempArr)."\n";                        
                    }                    
                }
            }
        }
        header('Pragma:public');
        header('Content-Type:application/csv;name="' . $name['code'] . '.csv');
        header("Content-Disposition:attachment;filename=" . $name['code'] . '.csv');
        echo iconv('UTF-8','GBK',implode(',', $title[1])."\n".$content);
        exit();     
    }
    /**
     * [shangjiaExcel 客户账单选择上佳模板导出]
     * @return [type] [description]
     */
    private function shangjiaExcel($data){
        $templatePath = APPLICATION_PATH . '/../data/xls/shangjiaBill.xls';

        require_once APPLICATION_PATH . '/../libs/PHPExcel1.8/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel1.8/PHPExcel/IOFactory.php';

        $startRow    = 2; // Excel模板中开始写入数据的行号
        $objLoad     = PHPExcel_IOFactory::load($templatePath);
        $objWriter   = PHPExcel_IOFactory::createWriter($objLoad, 'Excel5');
        $objPe       = $objLoad;
        $objSheet    = $objPe->setActiveSheetIndex(0);

        //根据数据量，对需要填写的行进行增减
        $totalRecord = count($data) - 4;

        if ($totalRecord < 1) {
          $objSheet->removeRow($startRow, 1 - $totalRecord);
        }elseif ($totalRecord > 1) {
          $objSheet->insertNewRowBefore($startRow + 1, $totalRecord - 1);
        }

        $footer_index = $totalRecord + $startRow;
        $objSheet->setCellValue('A'.$footer_index, $totalRecord + 1);
        foreach ($data[$totalRecord+1] as $key => $value) {
            $objSheet->setCellValue($key.$footer_index, $value);
        }
        $footer_index++;
        $objSheet->setCellValue('A'.$footer_index, $totalRecord + 2);
        $objSheet->setCellValue('AB'.$footer_index, $data[$totalRecord+2]['tallage']['rmb']);
        $objSheet->setCellValue('AC'.$footer_index, $data[$totalRecord+2]['tallage']['cCurrency']);

        $footer_index++;
        $objSheet->setCellValue('A'.$footer_index, $totalRecord + 3);
        $objSheet->setCellValue('AB'.$footer_index, $data[$totalRecord+3]['all']['rmb']);
        $objSheet->setCellValue('AC'.$footer_index, $data[$totalRecord+3]['all']['cCurrency']);

        $total_fee = array();

        for ($i=1; $i < count($data)-2; $i++) { 
            foreach ($data[$i] as $key => $value) {
                $value = isset($data[$i][$key]) ? $data[$i][$key] : '';
                if(in_array($key, array('C','D','E'))){
                    $objSheet->setCellValueExplicit($key.$startRow, $value, PHPExcel_Cell_DataType::TYPE_STRING);                    
                }else{
                    if(is_numeric($value) && $value != 0){
                        $objSheet->setCellValue($key.$startRow, $value); 
                    }elseif (!is_numeric($value)) {
                        $objSheet->setCellValue($key.$startRow, $value); 
                    }
                }
            }
            $startRow++;
        }

        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="' . $data[0]['code'] . '.xls');
        header("Content-Disposition:inline;filename=" . $data[0]['code'] . '.xls');
        $objWriter->save('php://output');
        exit();             
    }
    private function saiweiExcel($data){
        $templatePath = APPLICATION_PATH . '/../data/xls/saiweiBill.xls';

        require_once APPLICATION_PATH . '/../libs/PHPExcel1.8/PHPExcel.php';
        require_once APPLICATION_PATH . '/../libs/PHPExcel1.8/PHPExcel/IOFactory.php';

        $startRow    = 2; // Excel模板中开始写入数据的行号
        $objLoad     = PHPExcel_IOFactory::load($templatePath);
        $objWriter   = PHPExcel_IOFactory::createWriter($objLoad, 'Excel5');
        $objPe       = $objLoad;
        $objSheet    = $objPe->setActiveSheetIndex(0);

        //根据数据量，对需要填写的行进行增减
        $totalRecord = count($data) - 4;

        if ($totalRecord < 1) {
          $objSheet->removeRow($startRow, 1 - $totalRecord);
        }elseif ($totalRecord > 1) {
          $objSheet->insertNewRowBefore($startRow + 1, $totalRecord - 1);
        }

        $footer_index = $totalRecord + $startRow;
        $objSheet->setCellValue('A'.$footer_index, $totalRecord + 1);
        foreach ($data[$totalRecord+1] as $key => $value) {
            $objSheet->setCellValue($key.$footer_index, $value);
        }
        $footer_index++;
        $objSheet->setCellValue('A'.$footer_index, $totalRecord + 2);
        $objSheet->setCellValue('O'.$footer_index, $data[$totalRecord+2]['tallage']['rmb']);
        $objSheet->setCellValue('P'.$footer_index, $data[$totalRecord+2]['tallage']['cCurrency']);

        $footer_index++;
        $objSheet->setCellValue('A'.$footer_index, $totalRecord + 3);
        $objSheet->setCellValue('O'.$footer_index, $data[$totalRecord+3]['all']['rmb']);
        $objSheet->setCellValue('P'.$footer_index, $data[$totalRecord+3]['all']['cCurrency']);

        $total_fee = array();

        for ($i=1; $i < count($data)-2; $i++) { 
            foreach ($data[$i] as $key => $value) {
                $value = isset($data[$i][$key]) ? $data[$i][$key] : '';
                if(in_array($key, array('C','D','E'))){
                    $objSheet->setCellValueExplicit($key.$startRow, $value, PHPExcel_Cell_DataType::TYPE_STRING);                    
                }else{
                    if(is_numeric($value) && $value != 0){
                        $objSheet->setCellValue($key.$startRow, $value); 
                    }elseif (!is_numeric($value)) {
                        $objSheet->setCellValue($key.$startRow, $value); 
                    }
                }
            }
            $startRow++;
        }

        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="' . $data[0]['code'] . '.xls');
        header("Content-Disposition:inline;filename=" . $data[0]['code'] . '.xls');
        $objWriter->save('php://output');
        exit();             
    }

    /**
     * @desc 批量导出客户帐单
     */
    public function exportBillAction()
    {
        //  if ($this->_request->isPost()) {
        //暂时只提供单个导出
        $codesStr = $this->_request->getParam('codesStr', '');
        //header("Content-type:application/vnd.ms-excel");
        //header("Content-Disposition:filename=" . $codesStr . ".xls");
        if (!empty($codesStr)) {
            require_once('tcpdf/tcpdf.php');
            require_once('fpdi/fpdi.php');
            // $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
            $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
            // set default monospaced font
            $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
            $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
            $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
            $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            $pdf->SetFont('droidsansfallback', '', 12);

// set image scale factor
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
            $pdf->AddPage();
            $billRow = Service_BilCustomerBill::getByField($codesStr, 'bcb_code');
            $currencyRow = Service_Currency::getByField($billRow['currency_code'], 'currency_code', array('currency_name'));

            $customerRow = Service_Customer::getByField($billRow['customer_code'],'customer_code');
            $currencyRow = Service_Currency::getByField($customerRow['customer_currency_bill'], 'currency_code', array('currency_name'));
            $billRow['currency_name'] = $currencyRow['currency_name'];
            $currency_code = $billRow['currency_code'];
            $billRow['currency_code'] = $customerRow['customer_currency_bill'];


            //外币不需要税点
            //外币不需要税点
            $tax = Process_BillConfig::getCustomerTax($customerRow['customer_currency_bill'],strtoupper($billRow['customer_code']));

            $billRow['date'] = date("Y-m-d");
            $billRow['bill_date'] = date("Y-m-d", strtotime($billRow['bcb_bill_date']));
            $this->view->bill = $billRow;
            $converyCurrencyRow = array(
                'currency_code'=>$currency_code,
                'customer_currency_bill'=>$customerRow['customer_currency_bill'],
            );
            $this->view->data = Process_CustomerBill::getBillGroupData($billRow['bcb_id'], $tax,$converyCurrencyRow);
            $html = $this->view->render($this->tplDirectory . "printBill.tpl");
            //  $html=iconv("gb2312//TRANSLIT",'utf-8',$html);
            $pdf->writeHTML($html, true, 0, true, 0);


            $pdf->lastPage();

            $pdf->Output('bill.pdf', 'D');
        }


        // }
    }

    /**
     * @desc 按搜索条件导出费用
     */
    public function exportFeeAction()
    {
        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 = "F_" . 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['bb_refer_code'] = trim($this->_request->getParam("code", ""));
            $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['bi_status'] = trim($this->_request->getParam("E11", ""));

            if (isset($condition['billDate'])) {
                $condition['bi_chargeable_time_gt'] = date("Y-m-d H:i:s", strtotime($condition['billDate']));
            }

            //非逻辑
            $condition['bi_create_type'] = 1;

            $feeData = Service_BilIncome::getFeeData($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 getBasicInfoAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $code = $this->_request->getParam("code", "");

        }
        die(Zend_Json::encode($result));
    }

    /**
     * @desc 批量打印客户帐单
     */
    public function printAction()
    {
        $printType = $this->_request->getParam("printType", 0);
        $opCodes = $this->_request->getParam("codes", '');
        $htmlArr = array();
        $cArr=array();
        foreach ($opCodes as $v) {
            $billRow = Service_BilCustomerBill::getByField($v, 'bcb_code');
            if (!isset($cArr[$billRow['currency_code']])) {
                $currencyRow = Service_Currency::getByField($billRow['currency_code'], 'currency_code', array('currency_name'));
                $cArr[$billRow['currency_code']] = $currencyRow;
            }
            $billRow['currency_name'] = $cArr[$billRow['currency_code']]['currency_name'];
            //外币不需要税点
            $tax = Process_BillConfig::getCustomerTax($billRow['currency_code']);

            $billRow['date'] = date("Y-m-d");
            $billRow['bill_date'] = date("Y-m-d", strtotime($billRow['bcb_bill_date']));
            $this->view->bill = $billRow;
            $this->view->tax = $tax; //税点
            $this->view->data = Process_CustomerBill::getBillGroupData($billRow['bcb_id'], $tax);
            $html = $this->view->render($this->tplDirectory . "printBill.tpl");

            $html = preg_replace('/\s+/', ' ', $html); // 去除换行
            $html = preg_replace('/\'/', '"', $html); // 引号
            $htmlArr[] = array(
                'code' => $v,
                'html' => $html,
            );
        }

        $this->view->htmlArrChunk = $htmlArr;

        $this->view->count = count($htmlArr);
        $this->view->paper = 'A4';
        $this->view->title = '客户帐单-';
        $this->view->w = 210; // A4纸张宽度
        $this->view->h = 297; // A4纸张高度
        echo $this->view->render("financial/views/js/print-bills.js");
    }

    /**
     * @desc 批量打印客户帐单
     */
    public function previewAction()
    {
        $printType = $this->_request->getParam("printType", 0);
        $opCodes = $this->_request->getParam("codes", '');
        if (empty($opCodes) || !is_array($opCodes)) {
            die('no data');
        }
        $cArr = array();
        foreach ($opCodes as $v) {
            $billRow = Service_BilCustomerBill::getByField($v, 'bcb_code');
            if (!isset($cArr[$billRow['currency_code']])) {
                $currencyRow = Service_Currency::getByField($billRow['currency_code'], 'currency_code', array('currency_name'));
                $cArr[$billRow['currency_code']] = $currencyRow;
            }
            $customerRow = Service_Customer::getByField($billRow['customer_code'],'customer_code');
            if (!isset($cArr[$customerRow['customer_currency_bill']])) {
                $currencyRow = Service_Currency::getByField($customerRow['customer_currency_bill'], 'currency_code', array('currency_name'));
                $cArr[$customerRow['customer_currency_bill']] = $currencyRow;
            }
            $currency_code = $billRow['currency_code'];
            $billRow['currency_name'] = $cArr[$customerRow['customer_currency_bill']]['currency_name'];
            $billRow['currency_code'] = $customerRow['customer_currency_bill'];
            //外币不需要税点
            $tax = Process_BillConfig::getCustomerTax($customerRow['customer_currency_bill'],strtoupper($billRow['customer_code']));

            $billRow['date'] = date("Y-m-d");
            $billRow['bill_date'] = date("Y-m-d", strtotime($billRow['bcb_bill_date']));
            $this->view->tax = $tax;
            $this->view->bill = $billRow;
            $converyCurrencyRow = array(
                'currency_code'=>$currency_code,
                'customer_currency_bill'=>$customerRow['customer_currency_bill'],
            );
            $this->view->data = Process_CustomerBill::getBillGroupData($billRow['bcb_id'], $tax,$converyCurrencyRow);
            echo $this->view->render($this->tplDirectory . "printBillA4.tpl");
        }
    }

    public function viewAction()
    {
        $bilCustomerBillStatus = Process_BillConfig::bilCustomerBillStatus('auto');
        $bilReviewSign = Process_BillConfig::bilReviewSign('auto');
        $paramId = $this->_request->getParam("paramId", '0');
        $result = Process_CustomerBill::getBasicInfo($paramId, 'bcb_id');
        if ($result['state'] == '0') {
            die($result['message']);
        }
        $this->view->data = $result['data'];
        $this->view->billStatus = $bilCustomerBillStatus;
        $this->view->billLog = Service_BilCustomerBillLog::getUserByCondition(array('bcb_id' => $paramId), '*', 0, 0, array('bcbl_id desc'));
        echo Ec::renderTpl($this->tplDirectory . "bill_detail.tpl", 'layout');
    }

    /**
     * @desc 获取费用汇总信息(帐单明细页面)
     */
    public function feeListAction()
    {
        $return = array(
            "state" => 0,
            "message" => "No Data"
        );
        if ($this->_request->isPost()) {
            $businessType = Process_BillConfig::businessType('auto');
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
            $billId = $this->_request->getParam('billId', '0');
            $billId = empty($billId) ? '-1' : $billId;
            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $condition['bcb_id'] = $billId;
            $count = Service_BilCustomerBillFee::getJoinLeftFeeTypeByCondition($condition, 'count(*)');

            $return['total'] = $count;

            if ($count) {
                $rows = Service_BilCustomerBillFee::getJoinLeftFeeTypeByCondition($condition, '*', $pageSize, $page, array("ds_code", "sm_code", "bil_customer_bill_fee.ft_code"));

                foreach ($rows as $key => $row) {
                    // $rows[$key]["ds_code_text"] = '';
                    $rows[$key]["ds_code_text"] = isset($businessType[$row['ds_code']]) ? $businessType[$row['ds_code']] : '';
                    $rows[$key]["total_weight"] = 0;
                    $rows[$key]["unit_price"] = 0;
                    if ($row['ds_code'] != "so") {
                        continue;
                    }
                    $condition = array(
                        'bcb_id' => $row['bcb_id'],
                        'ds_code' => $row['ds_code'],
                        'sm_code' => $row['sm_code'],
                        'ft_code' => $row['ft_code'],
                    );
                    //print_r($condition);die;
                    $businessRows = Table_BilCustomerBillMap::getInstance()->getJoinInnerBusinessByCondition($condition, array("sum(bb_charge_weight) as total_weight", "bil_business.ds_code", "bil_income.ft_code"), 0);
                    $totalWeight=empty($businessRows) || !isset($businessRows[0]['total_weight']) || $businessRows[0]['ft_code'] != 'shipping' ? 0 : $businessRows[0]['total_weight'];

                    $rows[$key]["total_weight"] = $totalWeight;

                    $rows[$key]["unit_price"] = $rows[$key]["total_weight"] > 0 ? round($row['bcbf_amount'] / $rows[$key]["total_weight"], 3) : 0;
                }

                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['businessType'] = $businessType;
            }
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @desc 批量生成客户帐单
     */
    public function addCustomerBillAction()
    {
        $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", ""));
            $ds_code_par = $this->_request->getParam("businessType", "");
            $condition['billDate'] = trim($this->_request->getParam("billDate", ""));
            $condition['billDateFrom'] = trim($this->_request->getParam("billDateFrom", ""));
            $condition['sm_code'] = trim($this->_request->getParam("sm_code", "")); //运输方式

            $ds_code_arr = array();
            //赛维区外、区内订单分开出账单
            if(!empty($ds_code_par)){
                foreach($ds_code_par as $key=>$val){
                    if($val!=''){
                        $ds_code_arr[] = $val;
                    }else{
                        $ds_code_arr = array();
                        break;
                    }
                }
            }
            if(!empty($ds_code_arr)){
                $condition['ds_code_arr'] = $ds_code_arr;
            }
            if (isset($condition['billDateFrom'])) {
                $condition['bi_chargeable_time_start'] = date("Y-m-d H:i:s", strtotime($condition['billDateFrom']));
            }
            if (isset($condition['billDate'])) {
                $condition['bi_chargeable_time'] = date("Y-m-d H:i:s", strtotime($condition['billDate']));
            }

            $count = Service_BilIncome::getAllByCondition($condition, 'count(*)');

            $return['total'] = $count;

            if ($count) {
                $type = array(
                    'bil_income.customer_code as customer_code',
                    'sum(bil_income.bi_amount) as amount',
                    'bil_business.ds_code',
                    'customer.cash_type',
                    'customer.customer_short',
                    'customer.customer_currency',
                );
                $rows = Service_BilIncome::getAllByCondition($condition, $type, $pageSize, $page, array("customer.cash_type", "bil_income.customer_code", "bil_business.ds_code", "bil_income.sm_code"));
                $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 = date("Y-m-d H:i", strtotime("-1 days"));
        $this->view->SM = Service_ShippingMethod::getAll();
        echo Ec::renderTpl($this->tplDirectory . "add_customer_bill.tpl", 'layout');
    }


    /**
     * @desc 获取帐单费用明细信息
     */
    public function viewFeeDetailAction()
    {
        $paramId = $this->_request->getParam('paramId', '0');


        $return = array(
            "state" => 0,
            "message" => "No Data"
        );
        $businessType = Process_BillConfig::businessType('auto');
        if ($this->_request->isPost()) {

            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);
            $condition['bcb_id'] = $this->_request->getParam('bcb_id', '0');
            $condition['ds_code'] = $this->_request->getParam('ds_code', '');
            $condition['sm_code'] = $this->_request->getParam('sm_code', '');
            $condition['ft_code'] = $this->_request->getParam('ft_code', '');
            $condition['bb_refer_code'] = $this->_request->getParam('bb_refer_code', '');
            $condition['bb_service_number'] = $this->_request->getParam("bb_service_number",'');
            if (empty($condition['bcb_id'])) {
                die(Zend_Json::encode($return));
            }
            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $count = Service_BilIncome::getFeeDetailByCondition($condition, 'count(*)');

            $return['total'] = $count;

            if ($count) {
                $rows = Service_BilIncome::getFeeDetailByCondition($condition, '*', $pageSize, $page, array("bil_business_attach.bb_refer_code", "bil_business.ds_code", "bil_income.sm_code", "bil_income.ft_code"));
                foreach($rows as $key=>$value){
                    $rows[$key]['weight'] = "";
                    $rows[$key]['op_quantuty'] = "";
                    $shipOrder = Service_ShipOrder::getByField($value['bb_refer_code'],'order_code',"*");
                    if(!empty($shipOrder)){
                        $rows[$key]['bb_service_number'] = $shipOrder['tracking_number'];
                        $rows[$key]['weight'] = $shipOrder['so_weight']>$shipOrder['so_vol_weight']?$shipOrder['so_weight']:$shipOrder['so_vol_weight'];
                        $smRow = Service_ShippingMethod::getByField($shipOrder['sm_code'],"sm_code","*");
                        $Total = 0;
                        if($smRow['sm_is_volume']!="1") {
                            $Total = 1;
                        }else{
                            $sodList = Service_ShipOrderDetail::getByCondition(array('order_code'=>$value['bb_refer_code']),"*");
                            if($smRow['sm_code']=="HKDHL"){
                                $Total = count($sodList);
                            }else{
                                foreach($sodList as $sodRow){
                                    if($sodRow['sub_tracking_number']!="") $Total++;
                                }
                            }
                        }
                        $rows[$key]['op_quantuty'] = $Total;
                        continue;
                    }
                    $receivingRow = Service_Receiving::getByField($value['bb_refer_code'],'receiving_code',"*");
                    if(!empty($receivingRow)&&$receivingRow['is_delivery']=="1"&&$receivingRow['receive_model_type']=="0"){
                        $rows[$key]['weight'] = $receivingRow['netweight'];
                    }
                }
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['businessType'] = $businessType;
            }
            die(Zend_Json::encode($return));
        }
        $row = Service_BilCustomerBillFee::getByField($paramId, 'bcbf_id');
        if (empty($row)) {
            die("no data");
        }
        $row['ds_code_text'] = isset($businessType[$row['ds_code']]) ? $businessType[$row['ds_code']] : '';
        $this->view->data = $row;
        echo Ec::renderTpl($this->tplDirectory . "view_fee_detail.tpl", 'layout');
    }


    /**
     * @desc 查看非逻辑费用
     */
    public function notAuditFeesAction()
    {
        $businessType = Process_BillConfig::businessType('auto');
        $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
        $rpType = Process_BillConfig::rpType('auto');
        $bilIncomeStatus = Process_BillConfig::bilIncomeStatus('auto');
        $withdrawSign = Process_BillConfig::withdrawSign('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['bb_refer_code'] = trim($this->_request->getParam("bb_refer_code", ""));
            $condition['cash_type'] = trim($this->_request->getParam("customerSettlementType", ""));
            //$condition['ds_code'] = trim($this->_request->getParam("businessType", ""));
            $sDate = trim($this->_request->getParam("billDateFrom", ""));
            $tDate = trim($this->_request->getParam("billDateTo", ""));
            $condition['ft_code'] = trim($this->_request->getParam("ft_code", ""));
            $condition['bi_status'] = trim($this->_request->getParam("E11", ""));

            $dateType = trim($this->_request->getParam("searchDateType", ""));

            if ($sDate != '') {
                $sDate = date("Y-m-d 00:00:00", strtotime($sDate));
            }
            if ($tDate != '') {
                $tDate = date("Y-m-d 23:59:59", strtotime($tDate));
            }

            switch($dateType){
                case 'createDate' :
                    $condition['createDateForm'] = $sDate;
                    $condition['createDateTo'] = $tDate;
                    break;
                case 'checkDate' :
                    $condition['bilVerifyDateFrom'] = $sDate;
                    $condition['bilVerifyDateTo'] = $tDate;
                    break;
                case 'chargeDate' :
                    $condition['chargeDateForm'] = $sDate;
                    $condition['chargeDateTo'] = $tDate;
                    break;
                default:
                    $condition['chargeDateForm'] = $sDate;
                    $condition['chargeDateTo'] = $tDate;
                    break;
            }

            //非逻辑
            $condition['bi_create_type'] = 1;
            $condition['ds_code'] = 'ot'; //非逻辑
            $count = Service_BilIncome::getNotAuditFeesByCondition($condition, 'count(*)');

            $return['total'] = $count;

            if ($count) {
                $type = array(
                    'bil_income.bi_id',
                    'bil_income.bi_chargeable_time',
                    'bil_income.ft_code',
                    'bil_income.sm_code',
                    'bil_income.bi_amount',
                    'bil_business.ds_code',
                    'customer.cash_type',
                    'customer.customer_currency',
                    'bil_business.bb_charge_time',
                    'fee_type.ft_name_cn',
                    'bil_income.bi_rp_type',
                    'bil_income.bi_status',
                    'bil_income.bi_verify_time',
                    'bil_income.bi_add_time',
                    'bil_income.customer_code',
                    'bil_income.bi_withdraw_sign',
                    'bil_income.bi_note',
                );
                $rows = Service_BilIncome::getNotAuditFeesByCondition($condition, $type, $pageSize, $page, array("bil_income.bi_chargeable_time desc"));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
                $return['businessType'] = $businessType;
                $return['rpType'] = $rpType;
                $return['bilIncomeStatus'] = $bilIncomeStatus;
                $return['customerSettlementType'] = $customerSettlementType;
                $return['withdrawSign'] = $withdrawSign;
                $editBusinessIncomeFeeConfig = Process_Business::editBusinessIncomeFeeConfig();
                $return['editBusinessIncomeFeeConfig'] = array_flip($editBusinessIncomeFeeConfig);
            }
            die(Zend_Json::encode($return));
        }
        $this->view->businessType = $businessType;
        $this->view->customerSettlementType = $customerSettlementType;
        $this->view->billDateFrom = date("Y-m-d", strtotime("-40 days"));
        $this->view->billDateTo = ''; //date("Y-m-d H:i", strtotime("+1 days"));
        $this->view->feeType = Service_FeeType::getByCondition(array(), array("ft_code", "ft_name_cn"));
        $this->view->bilIncomeStatus = $bilIncomeStatus;
        echo Ec::renderTpl($this->tplDirectory . "not_audit_fees.tpl", 'layout');
    }


    /**
     * @desc 未出帐订单费用
     */
    public function notAuditOrderAction()
    {
        $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['billDateTo'] = trim($this->_request->getParam("billDateTo", ""));
            $condition['billDateFor'] = trim($this->_request->getParam("billDateFor", ""));
             $condition['bb_refer_code'] = trim($this->_request->getParam("bb_refer_code", ""));
            if (empty($condition['customer_code'])) {
                $return['message'] = "请填写客户代码";
                die(Zend_Json::encode($return));
            }   
            if (empty($condition['billDateTo'])) {
                $return['message'] = "帐单日期截止时间不能为空";
                die(Zend_Json::encode($return));
            }

            if (isset($condition['billDateTo'])) {
                $condition['bi_chargeable_time'] = date("Y-m-d H:i:s", strtotime($condition['billDateTo']));
            }
            if(isset($condition['billDateFor'])){
                $condition['bi_chargeable_time_start'] = date("Y-m-d H:i:s", strtotime($condition['billDateFor']));
            }

            $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.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['total'] = count($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 = date("Y-m-d H:i", strtotime("-1 days"));
        $this->view->billNow = date("Y-m-d H:i");
        echo Ec::renderTpl($this->tplDirectory . "not_audit_order.tpl", 'layout');
    }
    /**
    * @根据单号找费用信息
    */
    public function notAuditOrderVerifyAction(){

        $bb_refer_code = trim($this->_request->getParam("bb_refer_code", ""));
        $return = array(
            "state" => 0,
            "message" => "No Data",
            'data'=>''
        );
        if (!empty($bb_refer_code)) {
            $bbAtch=Service_BilBusinessAttach::getByField($bb_refer_code,'bb_refer_code');
            if (!empty($bbAtch)) {
                $bilIncome=Service_BilIncome::getByCondition(array("bb_id"=>$bbAtch['bb_id']),"*");
                if (!empty($bilIncome)&&is_array($bilIncome)) {
                    foreach ($bilIncome as $key => $value) {
                       $feeType=Service_FeeType::getByField($value['ft_code'],'ft_code');
                       $bilIncome[$key]['fee_type']=$feeType['ft_name_cn'];
                       $bilIncome[$key]['bb_refer_code']=$bb_refer_code;
                    }
                    $return['data'] = $bilIncome;
                    $return['state']=1;
                }else{
                    $return['data'] = '';
                    $return['message'] = "订单不存在或者非未出账单号";
                    die(Zend_Json::encode($return));
                }
            }else{
                $return['data'] = '';
                    $return['message'] = "订单不存在或者非未出账单号";
                    die(Zend_Json::encode($return));
            }
        }
        
        die(Zend_Json::encode($return));
    }
    /**
     * @desc 根据费用生成客户帐单
     */
    public function createBillAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $bbIdsArr = $this->_request->getParam("bids", array());
            $reference_no = trim($this->_request->getParam("reference_no", ''));
            $desc = trim($this->_request->getParam("desc", ''));
            $customerCode = trim($this->_request->getParam("customerCode", ''));
            $billDateFor = trim($this->_request->getParam("billDateFor", ''));
            $billDateTo = trim($this->_request->getParam("billDateTo", ''));
            $ds_code = trim($this->_request->getParam("ds_code", ''));
            if (empty($billDateTo)) {
                $result['message'] = "帐单截止日期不能为空";
                die(Zend_Json::encode($result));
            }
            if (empty($bbIdsArr) || !is_array($bbIdsArr) || empty($customerCode)) {
                $result['message'] = "参数异常,请重新提交";
            } else {
                $param = array(
                    'customer_code' => $customerCode,
                    'reference_no' => $reference_no,
                    'note' => $desc,
                    // 'ds_code' => $ds_code,
                    'bcb_bill_start_date' => $billDateFor,
                    'bcb_bill_date' => $billDateTo,
                    'bbIdArr' => $bbIdsArr,
                );
                $obj = new Process_CustomerBill();
                $result = $obj->createCustomerBillTransaction($param);
            }

        }
        die(Zend_Json::encode($result));
    }

    /**
     * @desc 根据客户代码批量生成帐单
     */
    public function batchCreateBillAction()
    {
        set_time_limit(900);
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $customerCodes = $this->_request->getParam("customerCodes", array());
            $billDate = $this->_request->getParam("billDate", "");
            $ds_code = $this->_request->getParam("ds_code", "");
            $desc = $this->_request->getParam("desc", "");
            $reference_no = trim($this->_request->getParam("reference_no", ''));
            $billDateFrom = trim($this->_request->getParam("billDateFrom", ""));
            $sm_code = trim($this->_request->getParam("sm_code", "")); //运输方式

            //$sm_code = sm_code
            if (!empty($customerCodes) && is_array($customerCodes)) {
                $result = array(
                    "state" => 1,
                    "message" => "",
                );
                foreach ($customerCodes as $code) {
                    $param = array(
                        'customer_code' => $code,
                        'reference_no' => $reference_no,
                        'note' => $desc,
                        'ds_code' => $ds_code,
                        'bill_date' => $billDate,
                        'billDateFrom'=>$billDateFrom,
                        'sm_code'=>$sm_code
                    );
                    $obj = new Process_CustomerBill();
                    $result['data'][] = $obj->createBillByCustomerTransaction($param);
                }
            }

        }
        die(Zend_Json::encode($result));
    }


    /**
     * @desc 批量上传费用(非逻辑)
     */
    public function uploadFeeAction()
    {
        if ($this->getRequest()->isPost()) {
            set_time_limit(0);
            ini_set('memory_limit', '500M');
            $return = array(
                'state' => 0,
                'message' => array('Request Method Err')
            );
            $file = $_FILES['fileToUpload'];
            $obj = new Process_Business();
            $return = $obj->uploadFeeTransaction($file);
            die(Zend_Json::encode($return));
        }
    }


    /**
     * @desc 批量删除费用(转到作废)
     */
    public function batchDeleteIncomeFeeAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail.",
            "data" => array()
        );
        if ($this->_request->isPost()) {
            $codes = $this->_request->getParam("codes", array());
            $note = $this->_request->getParam("note", "");
            if (is_array($codes) && !empty($codes)) {
                $result['state'] = 1;
                $result['message'] = '';
                $obj = new Process_Business();
                foreach ($codes as $code) {
                    $param['bi_id'] = $code;
                    $param['note'] = $note;
                    $result['data'][] = $obj->deleteBusinessFeeTransaction($param);
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * @desc 获取帐单费用明细信息
     */
    public function editFeeAction()
    {
        $paramId = $this->_request->getParam('paramId', '0');
        $rpType = Process_BillConfig::rpType('auto');
        $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
        $bt = Process_BillConfig::bt('auto');

        //提交数据
        if ($this->_request->isPost()) {
            $return = array(
                "state" => 0,
                "message" => "error",
                "data" => array()
            );

            $param = array(
                'customer_code' => $this->_request->getParam('customer_code', ''),
                'bi_id' => $this->_request->getParam('bi_id', ''),
                'amount' => $this->_request->getParam('amount', ''),
                'bt_code' => $this->_request->getParam('bt_code', 'EX'),
                'ft_code' => $this->_request->getParam('ft_code', ''),
                'rp_type' => $this->_request->getParam('rp_type', ''),
                'note' => $this->_request->getParam('note', ''),
                'currency_code' => $this->_request->getParam('currency_code', ''),
                'charge_time' => $this->_request->getParam('charge_time', ''),
            );
            $param['charge_time'] = date('Y-m-d H:i:s', strtotime($param['charge_time']));
            $obj = new Process_Business();
            $return = $obj->editBusinessFeeTransaction($param);
            die(Zend_Json::encode($return));
        }
        $row = array(
            'bi_id' => '',
            'bb_id' => '',
            'bt_code' => 'EX',
            '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" => '', 'bb_charge_time' => date('Y-m-d H:i:s')
        );
        $isEdit = 1;
        if (!empty($paramId)) {
            $row = Service_BilIncome::getByField($paramId);
            $ft_code = $row['ft_code'];
            $bbaRow = Service_BilBusinessAttach::getByField($row['bb_id'], 'bb_id');
            $bbRow = Service_BilBusiness::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, $bbRow);
            $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']] : '异常';
            $row['bi_amount'] = abs($row['bi_amount']);
            if($ft_code){
                $ft_name_cn = Service_FeeType::getByField($ft_code,'ft_code','ft_name_cn');
                $row['ft_name_cn'] = $ft_name_cn['ft_name_cn'];
            }else{
                 $row['ft_name_cn'] = '';
            }

            $isEdit = in_array($row['bi_status'], Process_Business::editBusinessIncomeFeeConfig()) ? 1 : 0;
        }

        $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->isEdit = $isEdit;
        $this->view->bt = $bt;
        $this->view->data = $row;
        echo Ec::renderTpl($this->tplDirectory . "edit_fee.tpl", 'layout');
    }

    /**
     * @desc 获取客户信息
     */
    public function getCustomerDataAction()
    {
        $result = array(
            'state' => '0',
            'message' => '数据异常',
            'data' => array()
        );
        if ($this->_request->isPost()) {
            $customerCode = trim($this->_request->getParam('customerCode', ""));
            if (!empty($customerCode)) {
                $customerRow = Service_Customer::getByField($customerCode, 'customer_code', array("customer_id", "customer_code", "cash_type", "customer_short", "customer_firstname", "customer_lastname", "customer_currency"));
                if (empty($customerRow)) {
                    $result['message'] = '客户代码不存在';
                    die(Zend_Json::encode($result));
                } else {
                    $balance = Service_CustomerBalance::getByField($customerCode, 'customer_code');
                    if (!empty($balance)) {
                        $customerRow['cb_value'] = $balance['cb_value'];
                        $customerRow['cb_hold_value'] = $balance['cb_hold_value'];
                    } else {
                        $customerRow['cb_value'] = 0;
                    }
                    $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
                    $customerRow['cash_type_text'] = isset($customerSettlementType[$customerRow['cash_type']]) ? $customerSettlementType[$customerRow['cash_type']] : '未绑定';
                    $result['state'] = 1;
                    $result['message'] = '';
                    $result['data'] = $customerRow;
                    die(Zend_Json::encode($result));
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    /**
     * 根据关键字搜索业务
     */
    public function getUserAction()
    {
        $db = Common_Common::getAdapter();
        $keyword = $this->_request->getParam('term', '');
        $limit = 20;
        $keyword = trim($keyword);
        $sql = "select user_code,user_name,user_name_en from user where user_code like '%" . $keyword . "%' or user_name like '%" . $keyword . "%' or user_name_en like '%" . $keyword . "%' limit " . $limit;
        $result = $db->fetchAll($sql);
        foreach ($result as $k => $v) {
            $t = array(
                'value' => trim($v['user_name']),
                'label' => '[' . $v['user_code'] . ']' . $v['user_name']
            );
            $v = array_merge($v, $t);
            $result[$k] = $v;
        }
        die(Zend_Json::encode($result));
    }


    /**
     * 根据关键字搜索客户
     */
    public function getByKeywordAction()
    {
        $db = Common_Common::getAdapter();
        $keyword = $this->_request->getParam('term', '');

        $limit = $this->_request->getParam('limit', '20');

        $sql = "select customer_code,customer_short from customer where customer_code like '%" . trim($keyword) . "%' or customer_short like '%" . trim($keyword) . "%' limit " . $limit;
        $result = $db->fetchAll($sql);
        foreach ($result as $k => $v) {
            $t = array(
                'value' => trim($v['customer_code']),
                'label' => '[' . $v['customer_code'] . ']' . $v['customer_short']
            );
            $v = array_merge($v, $t);
            $result[$k] = $v;
        }
        die(Zend_Json::encode($result));
    }


    /**
     * 根据关键字搜索客户
     */
    public function getKeywordAction()
    {
        $db = Common_Common::getAdapter();
        $keyword = $this->_request->getParam('term', '');
        $type = $this->_request->getParam('type', 'cm');

        $limit = $this->_request->getParam('limit', '20');
        $result = array();
        switch (strtolower($type)) {
            case 'cm':
                $sql = "select customer_code,customer_short from customer where customer_code like '%" . trim($keyword) . "%' or customer_short like '%" . trim($keyword) . "%' limit " . $limit;
                $result = $db->fetchAll($sql);
                foreach ($result as $k => $v) {
                    $t = array(
                        'value' => trim($v['customer_code']),
                        'label' => '[' . $v['customer_code'] . ']' . $v['customer_short']
                    );
                    $v = array_merge($v, $t);
                    $result[$k] = $v;
                }
                break;
            case 'su':
                $result = Process_SupplierFeeProcess::getKeyword($keyword, $limit);
                break;
            case 'sp':
                $sql = "select sp_code,sp_name from service_provider where sp_code like '%" . trim($keyword) . "%' or sp_name like '%" . trim($keyword) . "%' limit " . $limit;
                $result = $db->fetchAll($sql);
                foreach ($result as $k => $v) {
                    $t = array(
                        'value' => trim($v['sp_code']),
                        'label' => '[' . $v['sp_code'] . ']' . $v['sp_name']
                    );
                    $v = array_merge($v, $t);
                    $result[$k] = $v;
                }
                break;
            default:
                break;
        }

        die(Zend_Json::encode($result));
    }


    /**
     * @desc 获取客户信息
     */
    public function getBasicDataAction()
    {
        $type = $this->_request->getParam('type', 'cm');
        $result = array(
            'state' => '0',
            'message' => '数据异常',
            'type' => $type,
            'data' => array()
        );
        if ($this->_request->isPost()) {
            $code = trim($this->_request->getParam('code', ""));

            switch (strtolower($type)) {
                case 'cm':
                    $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
                    $types = array("customer_id as id", "customer_code as code", "cash_type", "customer_short as short", "customer_firstname", "customer_lastname", "customer_currency as currency_code");
                    $customerRow = Service_Customer::getByField($code, 'customer_code', $types);
                    if (empty($customerRow)) {
                        $result['message'] = '客户代码不存在';
                        die(Zend_Json::encode($result));
                    } else {
                        $balance = Service_CustomerBalance::getByField($code, 'customer_code');
                        if (!empty($balance)) {
                            $customerRow['value'] = $balance['cb_value'];
                            $customerRow['hold_value'] = $balance['cb_hold_value'];
                        } else {
                            $customerRow['value'] = 0;
                            $customerRow['hold_value'] = 0;
                        }
                        //name
                        $customerRow['name'] = $customerRow['customer_firstname'] . ' ' . $customerRow['customer_lastname'];

                        $customerRow['cash_type_text'] = isset($customerSettlementType[$customerRow['cash_type']]) ? $customerSettlementType[$customerRow['cash_type']] : '未绑定';
                        $result['state'] = 1;
                        $result['message'] = '';
                        $result['data'] = $customerRow;
                        $result['data']['type'] = $type;
                    }
                    break;
                case 'su':
                    $result = Process_SupplierFeeProcess::getBasicData($code);
                    $result['data']['type'] = $type;
                    break;
                case 'sp':
                    $spSettlementType = Process_BillConfig::spSettlementType('auto');
                    $types = array(
                        'sp_id as id',
                        'sp_code as code',
                        'sp_name as short',
                        'sp_name as name',
                        'sp_balance as value',
                        'sp_settlement_type',
                        'currency_code',
                    );
                    $row = Service_ServiceProvider::getByField($code, 'sp_code', $types);
                    if (empty($row)) {
                        $result['message'] = '服务商代码不存在';
                        die(Zend_Json::encode($result));
                    } else {
                        $row['hold_amount'] = Table_BilPayment::getInstance()->getTotal($code, 2);
                        $row['hold_value'] = 0;
                        $row['cash_type_text'] = isset($spSettlementType[$row['sp_settlement_type']]) ? $spSettlementType[$row['sp_settlement_type']] : '未绑定';


                        $result['state'] = 1;
                        $result['message'] = '';
                        $result['data'] = $row;
                        $result['data']['type'] = $type;
                        //银行卡
                        $result['data']['bank'] = Service_ServiceBankAccount::getByCondition(array('sp_id' => $row['id']), '*', 0);
                    }

                    break;
                default:
                    break;
            }
        }

        die(Zend_Json::encode($result));
    }


    /**
     * @desc 获取客户历史帐户信息
     */
    public function getAccountAction()
    {
        $type = $this->_request->getParam('type', 'cm');
        $code = $this->_request->getParam('code', '');
        $result = array(
            'state' => '0',
            'message' => '没有找到匹配的信息',
            'data' => array()
        );
        if ($this->_request->isPost()) {
            if (!empty($type) && !empty($code)) {
                if ($type=='sp') {
                $service_provider=Service_ServiceProvider::getByField($code,'sp_code');
                $condition=array(
                    'sp_id'=>$service_provider['sp_id'],
                    ); 
                $rows = Service_ServiceBankAccount::getByCondition($condition, '*', 0);
                foreach ($rows as $key => $value) {
                    $bank=Service_Bank::getByField($value['bk_code'],'bk_code');
                    $rows[$key]['bank']=$bank['bk_name'];
                }
                if (!empty($rows)) {
                    $result = array(
                        'state' => '1',
                        'message' => '',
                        'data' => $rows
                    );
                }
                }
            }
        }
        die(Zend_Json::encode($result));
    }
     /**
     * @desc 修改费用信息
     */
    public function editAmountAction()
    {
        $bbcode = trim($this->_request->getParam('bb_code', ''));
        $amount = $this->_request->getParam('b_amount', '');
        $return = array(
            'state' => 0,
            'message' => '保存成功',
        );
        if ($this->_request->isPost()) {   
            $bbAtch=Service_BilBusinessAttach::getByField($bbcode,'bb_refer_code');
            if (!empty($bbAtch)) {
               $bilIncome=Service_BilIncome::getByCondition(array('bb_id'=>$bbAtch['bb_id']));
               if (!empty($bilIncome)) {
                          foreach ($bilIncome as $k => $v) {
                          Service_BilIncome::update(array('bi_amount'=>trim($amount[$k])),$v['bi_id'],'bi_id');
                        } 
                }
            }
                       

        }
        die(Zend_Json::encode($return));
    }


}