<?php
class Service_BilIncome extends Common_Service
{
    /**
     * @var null
     */
    public static $_modelClass = null;

    /**
     * @return Table_BilIncome|null
     */
    public static function getModelInstance()
    {
        if (is_null(self::$_modelClass)) {
            self::$_modelClass = new Table_BilIncome();
        }
        return self::$_modelClass;
    }

    /**
     * @param $row
     * @return mixed
     */
    public static function add($row)
    {
        $model = self::getModelInstance();
        return $model->add($row);
    }


    /**
     * @param $row
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function update($row, $value, $field = "bi_id")
    {
        $model = self::getModelInstance();
        return $model->update($row, $value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @return mixed
     */
    public static function delete($value, $field = "bi_id")
    {
        $model = self::getModelInstance();
        return $model->delete($value, $field);
    }

    /**
     * @param $value
     * @param string $field
     * @param string $colums
     * @return mixed
     */
    public static function getByField($value, $field = 'bi_id', $colums = "*")
    {
        $model = self::getModelInstance();
        return $model->getByField($value, $field, $colums);
    }

    /**
     * @return mixed
     */
    public static function getAll()
    {
        $model = self::getModelInstance();
        return $model->getAll();
    }

    /**
     * @param array $condition
     * @param string $type
     * @param int $pageSize
     * @param int $page
     * @param string $order
     * @return mixed
     */
    public static function getByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getByCondition($condition, $type, $pageSize, $page, $order);
    }


    public static function getBillByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getBillByCondition($condition, $type, $pageSize, $page, $order);
    }

    /*
     * @desc 批量生成帐单专用
     */
    public static function getAllByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getAllByCondition($condition, $type, $pageSize, $page, $order);
    }

    /*
     * @desc 批量生成帐单专用(请勿修改)
     */
    public static function getJoinInnerBusinessByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getJoinInnerBusinessByCondition($condition, $type, $pageSize, $page, $order);
    }

     /*
     * @desc 批量生成帐单专用(请勿修改)
     */
    public static function getOrderGroupByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getOrderGroupByCondition($condition, $type, $pageSize, $page, $order);
    }

    /*
     * @desc 获取帐单详细单据
     */
    public static function getFeeDetailByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getFeeDetailByCondition($condition, $type, $pageSize, $page, $order);
    }

    /*
     * @desc 获取业务费用详细
     */
    public static function getFeeDetailByBusinessCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getFeeDetailByBusinessCondition($condition, $type, $pageSize, $page, $order);
    }

     /*
     * @desc 查看应收费用
     */
    public static function getNotAuditFeesByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getNotAuditFeesByCondition($condition, $type, $pageSize, $page, $order);
    }

    /*
     * @desc 查看未出帐应收费用
     */
    public static function getNotAuditOrdersByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getNotAuditOrdersByCondition($condition, $type, $pageSize, $page, $order);
    }

    /*
     * @desc 查看未出帐应收费用(按单号汇总)
     */
    public static function getNotAuditOrderGroupByCondition($condition = array(), $type = '*', $pageSize = 0, $page = 1, $order = "")
    {
        $model = self::getModelInstance();
        return $model->getNotAuditOrderGroupByCondition($condition, $type, $pageSize, $page, $order);
    }

    /**
     * @param $val
     * @return array
     */
    public static function validator($val)
    {
        $validateArr = $error = array();
        
        return  Common_Validator::formValidator($validateArr);
    }


    /**
     * @param array $params
     * @return array
     */
    public  function getFields()
    {
        $row = array(
        
              'E0'=>'bi_id',
              'E1'=>'bcb_id',
              'E2'=>'customer_code',
              'E3'=>'bb_id',
              'E4'=>'ft_code',
              'E5'=>'ut_code',
              'E6'=>'sm_code',
              'E7'=>'bi_creator_id',
              'E8'=>'bi_amount',
              'E9'=>'currency_code',
              'E10'=>'currency_rate',
              'E11'=>'bi_status',
              'E12'=>'bi_balance_sign',
              'E13'=>'bi_chargeable_time',
              'E14'=>'bi_add_time',
              'E15'=>'bi_update_time',
        );
        return $row;
    }

    /**
     * @desc 导出非逻辑费用
     * @param $condition
     * @return array
     */
    public static function getFeeData($condition)
    {
        //中英文对应
        $keyMap = array(
            "A" => '客户代码',
            "B" => '结算方式',
            "C" => '业务类型',
            "D" => '收付类型',

            "E" => '状态',
            "F" => '费用类型',
            "G" => '计费金额',
            "H" => '币种',
            "I" => '单号',
            "J" => '创建人',
            "K" => '创建时间',
            "L" => '备注',
        );
        $count = Service_BilIncome::getNotAuditFeesByCondition($condition, 'count(*)');

        $csvData = array();
        $csvData[1] = $keyMap; //Excel 表头
        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.ds_code',
                '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',
            );
            $businessType = Process_BillConfig::businessType('auto');
            $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
            $rpType = Process_BillConfig::rpType('auto');
            $bilIncomeStatus = Process_BillConfig::bilIncomeStatus('auto');

            $rows = Service_BilIncome::getNotAuditFeesByCondition($condition, $type, 0, 0, array("bil_income.bi_chargeable_time desc"));

            $i = 2; //从第二行开始
            foreach ($rows as $key => $iv) {
                $k = $i++;
                $csvData[$k] = array(
                    "A" => $iv['customer_code'],
                    "B" => $customerSettlementType[$iv['cash_type']],
                    "C" => (isset($businessType[$iv['ds_code']]) ? $businessType[$iv['ds_code']] : ''),
                    "D" => $rpType[$iv['bi_rp_type']],
                    "E" => $bilIncomeStatus[$iv['bi_status']],
                    "F" => $iv['ft_name_cn'],
                    "G" => $iv['bi_amount'],
                    "H" => $iv['customer_currency'],
                    "I" => $iv['bb_refer_code'],
                    "J" => $iv['creator'],
                    "K" => $iv['bi_add_time'],
                    "L" => $iv['bi_note']
                );
            }
        }
        return $csvData;
    }

    /**
     * @desc 导出应收未帐
     * @param $condition
     * @return array
     */
    public static function getAllFeeData($condition)
    {
        //中英文对应
        $keyMap = array(
            "A" => '客户代码',
            "B" => '结算方式',
            "C" => '业务类型',
            "D" => '收付类型',

            "E" => '状态',
            "F" => '费用类型',
            "G" => '计费金额',
            "H" => '币种',
            "I" => '单号',
            "J" => '计费时间',
            "K" => '创建人',
            "L" => '创建时间',
            "M" => '备注',
        );
        $count = Service_BilIncome::getNotAuditOrdersByCondition($condition, 'count(*)');

        $csvData = array();
        $csvData[1] = $keyMap; //Excel 表头
        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.ds_code',
                '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.bi_chargeable_time',
                'bil_income.customer_code',
                'bil_income.bi_withdraw_sign',
                'bil_income.bi_note',
            );
            $businessType = Process_BillConfig::businessType('auto');
            $customerSettlementType = Process_BillConfig::customerSettlementType('auto');
            $rpType = Process_BillConfig::rpType('auto');
            $bilIncomeStatus = Process_BillConfig::bilIncomeStatus('auto');

            $rows = Service_BilIncome::getNotAuditOrdersByCondition($condition, $type, 0, 0, array("bil_income.bi_chargeable_time asc"));

            $i = 2; //从第二行开始
            foreach ($rows as $key => $iv) {
                $k = $i++;
                $csvData[$k] = array(
                    "A" => $iv['customer_code'],
                    "B" => $customerSettlementType[$iv['cash_type']],
                    "C" => (isset($businessType[$iv['ds_code']]) ? $businessType[$iv['ds_code']] : ''),
                    "D" => $rpType[$iv['bi_rp_type']],
                    "E" => $bilIncomeStatus[$iv['bi_status']],
                    "F" => $iv['ft_name_cn'],
                    "G" => $iv['bi_amount'],
                    "H" => $iv['customer_currency'],
                    "I" => $iv['bb_refer_code'],
                    "J" => $iv['bi_chargeable_time'],
                    "K" => $iv['creator'],
                    "L" => $iv['bi_add_time'],
                    "M" => $iv['bi_note']
                );
            }
        }
        return $csvData;
    }

    /**
     * @author william-fan
     * @todo 读取数据
     */
    public static function getData($field,$type='so'){
        $orderUpload = new Zend_Session_Namespace('orderRefee');
        //$field = 'batchfee';

        switch(strtolower($type)){
            case 'so':
                break;
            case 'lo':
            default:
            $result = array("ask"=>0,"message"=>"订单类型错误",'error'=>array('订单类型错误,只能是so或者lo'));
            return $result;
        }
        $path = APPLICATION_PATH.'/../data/upload/';
        if(!file_exists($path)){
            if(!mkdir($path,0777,true)){
                $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path']		= $path;
        $config['allowed_types']	= 'xls|xlsx|csv';
        $config['max_size']			= '10000';
        $config['encrypt_name']		= true;
        $upload	= new Common_UploadFile($config);
        $upload->set_upload_path($path);
        $uploadResult = $upload->do_upload($_FILES,$field);
        if ( ! $uploadResult ){
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] =  $upload->display_errors();
            return $result;
        }
        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if(empty($resultArray) || empty($full_path)){
            $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
            return $result;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCEL($full_path);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;
    }
    /**
     * @todo 得到有效数据
     */
    public static function getDataArr($rows,$type){
        $result = array();
        if(!empty($rows)){
            foreach($rows as $key=>$value){
                if($key>0){
                    $row = array();
                    $order_code = $value[0];
                    if($type=='so'){
                        $orderRow = Service_Orders::getByField($order_code,'order_code');
                        if(empty($orderRow)){
                            $row['order_code'] = $order_code;
                            $row['is_valid'] = '0';
                            $row['error'] = array('订单不存在');
                        }else{
                            $row['order_code'] = $order_code;
                            $row['is_valid'] = '1';
                        }
                    }
                    if($type=='lo'){
                        $orderRow = Service_LogisticsOrder::getByField($order_code,'logistics_code');
                        if(empty($orderRow)){
                            $row['order_code'] = $order_code;
                            $row['is_valid'] = '0';
                            $row['error'] = array('订单不存在');
                        }else{
                            $row['order_code'] = $order_code;
                            $row['is_valid'] = '1';
                        }
                    }
                    $result[] = $row;
                }
            }
        }
        return $result;
    }

}