<?php

namespace Admin\Controller;
/**
 * 上下游结算单
 * @author cz
 */
class AggregateStatementPoolController extends ThinkController
{
    public $CompanyType = [
        "1"=>"下游公司",
        "2"=>"下游个人",
        "3"=>"上游CP"
    ];
    public $IsPayment = [
        "1"=>"是",
        "2"=>"否"
    ];
    public $WithdrawType = [
        "0"=>"周结",
        "1"=>"月结",
        "2"=>"下游个人补点",
        "3"=>"其他",
    ];
    public $VerifyStatus=[
        "-2"=>"拒绝打款",
        "-1"=>"审批拒绝",
        "0"=>"未审批",
        "1"=>"审批通过",
        "2"=>"待打款",
        "3"=>"打款中",
        "4"=>"打款成功",
        "5"=>"无需打款"
    ];
    public $InfoVerifyStatus=[
        "-1"=>"配置信息不全",
        "0"=>"信息未确认",
        "1"=>"允许打款",
        "2"=>"线下无需打款"
    ];
    public $PayStatus=[
        "-1"=>"打款失败",
        "0"=>"未打款",
        "1"=>"打款成功"
    ];
    public $admininfo;
    public $DBModel;
    public function _initialize()
    {
        $this->admininfo = $_SESSION['onethink_admin']['user_auth'];
        $this->DBModel = M("AggregateStatementPool","tab_");
        parent::_initialize();
    }

    public function lists() {
        $params = I('get.');
        $page = $params['p'] ? intval($params['p']) : 1;
        $row = $params['row'] ? intval($params['row']) : 10;
        //权限分配
        if(!IS_ROOT){
            $this->OpAuthList= getModuleControllerAuth();
        }
        $this->assign('menubtn',$this->menuAuth());

        $map = [
            "_string"=>"1=1"
        ];
        if (isset($_REQUEST['time_start']) && isset($_REQUEST['time_end'])) {
            $time_start = strtotime($_REQUEST['time_start']);
            $time_end = strtotime($_REQUEST['time_end'])+ 86399;
            $map["_string"] =  "(statement_begin_time BETWEEN {$time_start} AND {$time_end}) OR (statement_end_time BETWEEN {$time_start} AND {$time_end}) OR (statement_begin_time <= {$time_end} AND  statement_end_time >= {$time_end})";
        } elseif (isset($_REQUEST['time_start'])) {
            $time_start = strtotime($_REQUEST['time_start']);
            $map["_string"] =  "(statement_begin_time >= {$time_start} ) OR (statement_end_time >= {$time_start})";
        } elseif (isset($_REQUEST['time_end'])) {
            $time_end = strtotime($_REQUEST['time_end'])+ 86399;
            $map["_string"] =  "(statement_begin_time <= {$time_end} ) OR (statement_end_time <= {$time_end})";
        }

        if (isset($_REQUEST['time_start2']) && isset($_REQUEST['time_end2'])) {
            $map['op_time'] = ['between', [strtotime($_REQUEST['time_start2']), strtotime($_REQUEST['time_end2']) + 86399]];
        } elseif (isset($_REQUEST['time_start2'])) {
            $map['op_time'] = ['EGT', strtotime($_REQUEST['time_start2'])];
        } elseif (isset($_REQUEST['time_end2'])) {
            $map['op_time'] = ['ELT', strtotime($_REQUEST['time_end2']) + 86399];
        }

        //其他

        if(isset($_REQUEST['company_type'])){
            $map['company_type'] = $_REQUEST['company_type'];
        }
        if(isset($_REQUEST['verify_status'])){
            $map['verify_status'] = $_REQUEST['verify_status'];
        }
        if(isset($_REQUEST['statement_num'])){
            $map['statement_num'] = $_REQUEST['statement_num'];
        }
        if(isset($_REQUEST['is_payment'])){
            $map['is_payment'] = $_REQUEST['is_payment'];
        }
        if(isset($_REQUEST['withdraw_type'])){
            $map['withdraw_type'] = $_REQUEST['withdraw_type'];
        }
        

        // $this->checkListOrCountAuthRestMap($map);//导出权限
        //条件end
        $data = $this->DBModel
            ->field("*")
            ->where($map)
            ->order("FIELD(verify_status,0,1,-1,-2,2,3,4,5),id desc")
            ->page($page,$row)->select();
        foreach($data as $k => &$v) {

            $v['statement_begin_time'] = date('Y-m-d',$v['statement_begin_time']);
            $v['statement_end_time'] = date('Y-m-d',$v['statement_end_time']);

            $v['company_type_str'] = $this->CompanyType[$v['company_type']];
            $v['is_payment_str'] = $this->IsPayment[$v['is_payment']];
            $v['can_export'] = $v['statement_money'] == 0 ? "0" : '1';

            $v['op_time'] = date('Y-m-d H:i:s',$v['op_time']);
            $v["valid"] = "{$v['statement_begin_time']} ~ {$v['statement_end_time']}";

            $v['ext_file_type'] = empty($v['ext_file']) ? "无" : "有";
            $v['withdraw_type'] = $this->WithdrawType[$v['withdraw_type']];;

            $v['verify_log'] = json_decode($v['verify_log'], true);
            if (isset($params['export'])) {
                $symbol = "\n";
            } else {
                $symbol = "<br>";
            }
            $v["create"]= "{$v['verify_log']['create_user']} {$symbol} {$v['verify_log']['create_time']}";
            if(isset($v['verify_log']['verify_user'])){
                if($v['verify_status'] == -1){
                    $ts = "审核拒绝";
                }else{
                    $ts = "审核通过";
                }
                $v["verify"]= "{$ts}({$v['verify_log']['verify_user']}) {$symbol} {$v['verify_log']['verify_time']}";
            }else{
                $v["verify"] = '--';
            }


            if(isset($v['verify_log']['payment_user'])){
                if($v['verify_status'] == -2){
                    $ts = "拒绝打款";
                    $v["payment"]= "{$ts}({$v['verify_log']['payment_user']}){$symbol} {$v['verify_log']['payment_time']}";
                }elseif($v['verify_status'] == 2){
                    $ts = "待打款";
                    $v["payment"]= "{$ts}({$v['verify_log']['payment_user']}){$symbol} {$v['verify_log']['payment_time']}";
                }elseif($v['verify_status'] == 3){
                    $ts = "打款中";
                    $v["payment"]= "{$ts}({$v['verify_log']['payment_user']}){$symbol} {$v['verify_log']['payment_time']}";
                }elseif($v['verify_status'] == 4){
                    if($v['is_payment']==1){
                        $ts="线上打款成功";
                    }else{
                        $ts="线下打款成功";
                    }
                    $v["payment"]= "{$ts}({$v['verify_log']['payment_user']}){$symbol} {$v['verify_log']['payment_time']}";
                }elseif($v['verify_status'] == 5){
                    $ts="无需打款";
                    $v["payment"]= "{$ts}({$v['verify_log']['payment_user']}){$symbol} {$v['verify_log']['payment_time']}";
                }
            }else{
                $v["payment"] = '--';
            }

            $v['oplist'] = $this->OpAuth($v);
        }
        $count =  $this->DBModel->field("count(id) count,SUM(statement_money) as statement_money,SUM(lack_statement_money) lack_statement_money")->where($map)->find();
        // dd($count);
        $params['p'] = $page;
        $params['row'] = $row;
        $page = set_pagination($count['count'], $row, $params);
        if ($page) {
            $this->assign('_page', $page);
        }
        
        $this->assign('data',$data);
        $this->assign('count',$count);
        $this->assign('CompanyType',$this->CompanyType);
        $this->assign('IsPayment',$this->IsPayment);
        $this->assign('VerifyStatus',$this->VerifyStatus);
        $this->assign('WithdrawType',$this->WithdrawType);
        $this->display();

    }
    //查看
    public function viewPool()
    {
        if(!isset($_REQUEST['id'])){
            $this->error('参数错误');
        }
        $id = $_REQUEST['id'];
        $is_export= false;
        if (isset($_REQUEST['export']) && $_REQUEST['export']==1){
            $is_export = true;
        }
        //获取基本信息
        $infolist = M("aggregate_statement_info","tab_")->field("*,'1' as st")->where("pool_id = '{$id}'")->select();
        //获取母单
        $pool_info =  M("aggregate_statement_pool","tab_")->field('statement_num,create_lack_ids,verify_status,is_payment')->where("id={$id}")->find();
        $statement_num = $pool_info['statement_num'];
        $this->assign("title",$statement_num);
        $this->assign("pool_status",$pool_info['verify_status']);
        $this->assign("pool_status",$pool_info['verify_status']);
        $this->assign("is_payment",$pool_info['is_payment']);

        //获取母单
        if(!empty($pool_info['create_lack_ids'])){
            $l_ids = $pool_info['create_lack_ids'];
            $lack_info = M("aggregate_lack_statement_info","tab_")->field("*,'0' as st")->where("id in ({$l_ids})")->select();

            $infolist =array_merge($infolist,$lack_info);
        }

        $this->viewPuPool($infolist,$is_export);

    }
    //个人汇总结算查看
    public function viewPuPool(&$infolist,$is_export){
        // dd($infolist);
        $line = 1;
        $count = [];
        //获取对接人
        foreach($infolist as $k=>&$v){
            $v['statement_info'] = json_decode($v['statement_info'],true);
            $v['company_info'] = json_decode($v['company_info'],true);
            $v['statement_begin_time'] = date('Y.m.d',$v['statement_begin_time']);
            $v['statement_end_time'] = date('Y.m.d',$v['statement_end_time']);
            $cline = $line+1;
            if($is_export){
                $v['sum_money_exp'] = "=";
            }
            foreach($v['statement_info'] as $ke=>&$va){
                $line ++;
                if(isset($va['ratio'])){
                    $va['increment_ratio'] = 0;
                }else{
                    $va['ratio'] = 0;
                }

                if($is_export){
                    //J3*(K3+L3)+M3-N3
                    if($va['statement_type'] > 0){ //罚款服务器费用
                        $va['sum_money'] =  "=J{$line}";
                    }else{
                        $va['sum_money'] =  "=J{$line}*(K{$line}+L{$line})+M{$line}-N{$line}";
                    }
                    $va['ratio_money'] = "=ROUND(G{$line}*H{$line}*(1-I{$line})-J{$line}-K{$line},2)";
                }else{
                    $count['platform_amount'] += $va['money'];
                    $count['sum_money'] +=  $va['ratio_money'];
                }
            }
            $v['statement_count'] = count($v['statement_info']);
        }
        if($is_export){
            $count["platform_amount"] = "=ROUND(SUM(G2:G".$line."),2)";
            $count["sum_money"] = "=ROUND(SUM(L2:L".$line."),2)";
        }

        $this->assign("data",$infolist);
        $this->assign("count",$count);
        $this->assign("is_export",$is_export);
        $this->display("AggregateStatementPool/viewPuPool");
    }
    //下游汇总结算查看
    public function viewPcPool(&$infolist,$is_export){
        $line = 1;
        $count = [];
        //获取对接人
        $p_id = array_column($infolist,'company_id');
        $map['id'] = ['in',$p_id];
        $pl =  M("promote_company","tab_")->field("id,settlement_contact")->where($map)->select();
        $Partner = [];
        foreach($pl as $k=>$v){
            $Partner[$v['id']] = $v['settlement_contact'];
        }
        unset($pl);
        foreach($infolist as $k=>&$v){
            $v['statement_info'] = json_decode($v['statement_info'],true);
            $v['statement_begin_time'] = date('Y.m.d',$v['statement_begin_time']);
            $v['statement_end_time'] = date('Y.m.d',$v['statement_end_time']);
            $cline = $line+1;
            if($is_export){
                $v['statement_money_exp'] = "=";
            }
            foreach($v['statement_info'] as $ke=>&$va){
                $line ++;
                if(isset($va['ratio'])){
                    $va['increment_ratio'] = 0;
                }else{
                    $va['ratio'] = 0;
                }

                if($is_export){
                    $v['statement_money_exp'] .= "H{$line}+";

                    $va['d_statement_money'] =  "=D{$line}*(1-G{$line})*(E{$line}+F{$line})";

                    $count['platform_amount_exp'] .= "D{$line}+";
                    $count['d_statement_money_exp'] .=  "H{$line}+";

                }else{
                    $va['d_statement_money'] =  round($va['pay_amount']*($va['ratio']+$va['increment_ratio'])*(100-$va['fax_ratio'])/100/100,2);

                    $count['platform_amount'] += $va['pay_amount'];

                    $count['d_statement_money'] +=  $va['d_statement_money'];
                }
            }
            $v['settlement_contact'] = $Partner[$v['company_id']];

            if($is_export){
                $v['statement_money_exp'] .= "J{$cline}-I{$cline}";
                $v['statement_money'] =  $v['statement_money_exp'];

                $count['fine_exp'] .= "I{$cline}+";
                $count['reward_exp'] .= "J{$cline}+";

                $count['statement_money_exp'] .= "K{$cline}+";
            }else{
                $count['fine'] += $v['fine'];
                $count['reward'] += $v['reward'];
                $count['statement_money'] += $v['statement_money'];
            }
            $v['statement_count'] = count($v['statement_info']);
            
        }
        if($is_export){
            $count["d_statement_money"] = "=".trim($count["d_statement_money_exp"],"+");
            $count["platform_amount"] = "=".trim($count["platform_amount_exp"],"+");
            $count["fine"] = "=".trim($count["fine_exp"],"+");
            $count["reward"] = "=".trim($count["reward_exp"],"+");
            $count["statement_money"] = "=".trim($count["statement_money_exp"],"+");
        }

        $this->assign("data",$infolist);
        $this->assign("count",$count);
        $this->assign("is_export",$is_export);
        $this->display("AggregateStatementPool/viewPcPool");

    }

    //上游汇总查看及导出
    public function viewCpPool(&$infolist,$is_export)
    {
        $line = 2;
        $count = [];
        //获取平台名
        $p_id = array_column($infolist,'company_id');
        $map['id'] = ['in',$p_id];
        $pl =  M("Partner","tab_")->field("id,matche_platform")->where($map)->select();
        $Partner = [];
        foreach($pl as $k=>$v){
            $Partner[$v['id']] = $v['matche_platform'];
        }
        unset($pl);
        //
        foreach($infolist as $k=>&$v){
            $v['statement_info'] = json_decode($v['statement_info'],true);
            $v['statement_begin_time'] = date('Y.m.d',$v['statement_begin_time']);
            $v['statement_end_time'] = date('Y.m.d',$v['statement_end_time']);
            $cline = $line+1;
            if($is_export){
                $v['statement_money_exp'] = "=";
            }
            foreach($v['statement_info'] as $ke=>&$va){
                $line ++;
                $va['company_ratio'] = 100-$va['ratio'];
                if($is_export){
                    $v['statement_money_exp'] .= "K{$line}+";
                    $va['d_statement_money'] =  "=F{$line}*G{$line}";
                    $count['platform_amount_exp'] .= "E{$line}+";
                    $count['platform_amount_exp2'] .= "F{$line}+";
                    $count['d_statement_money_exp'] .=  "K{$line}+";
                }else{
                    $va['d_statement_money'] =  round($va['pay_amount']*$va['ratio']/100,2);
                    $count['platform_amount'] += $va['pay_amount'];
                    $count['platform_amount2'] += $va['pay_amount'];
                    $count['d_statement_money'] +=  $va['d_statement_money'];
                }
            }
            $v['matche_platform'] = $Partner[$v['company_id']];
            if($is_export){
                $v['statement_money_exp'] .= "M{$cline}-L{$cline}";
                $v['statement_money'] =  $v['statement_money_exp'];
                $count['fine_exp'] .= "L{$cline}+";
                $count['reward_exp'] .= "M{$cline}+";
                $count['statement_money_exp'] .= "N{$cline}+";
            }else{
                $count['fine'] += $v['fine'];
                $count['reward'] += $v['reward'];
                $count['statement_money'] += $v['statement_money'];
            }
            $v['statement_count'] = count($v['statement_info']);
            
        }
        if($is_export){
            $count["d_statement_money"] = "=".trim($count["d_statement_money_exp"],"+");
            $count["platform_amount"] = "=".trim($count["platform_amount_exp"],"+");
            $count["platform_amount2"] = "=".trim($count["platform_amount_exp2"],"+");
            $count["fine"] = "=".trim($count["fine_exp"],"+");
            $count["reward"] = "=".trim($count["reward_exp"],"+");
            $count["statement_money"] = "=".trim($count["statement_money_exp"],"+");
        }
        $this->assign("data",$infolist);
        $this->assign("count",$count);
        $this->assign("is_export",$is_export);
        $this->display("AggregateStatementPool/viewCpPool");
    }

    //审批通过
    public function verifyAgree(){
        $this->setVerifyStatus(0,1,"verify");
    }
    public function verifyRefuse(){
        $this->setVerifyStatus(0,-1,"verify");
    }
    //线下打款
    public function setUlPayment()
    {
        if(!isset($_REQUEST['ids'])) $this->error("参数错误");
        $ids = $_REQUEST['ids'];

        //修改info
        $ires = M("aggregate_statement_info","tab_")->where("pool_id='{$ids}'")->save(['pay_type'=>3,'pay_status'=>1]);
        if($ires !== false){
            $this->setVerifyStatus(1,4,"payment");
        }
        $this->ajaxReturn(array(
            'status' =>0,
            "info"=>"线下打款失败"
        ));
        
        
    }

    //type 0 汇总 1 审批 2 开票 3 到账
    public function setAggregateDetail($type=0, $status = 1,$detail_info = "",$id = 0) {

        $data = M("aggregate_statement","tab_")->where(['id'=>$id])->find();

        $detail['detail'] = json_decode($data['detail'],true);

        $adminInfo = $_SESSION['onethink_admin']['user_auth'];
        if ($type == 0) {
            $detail['detail']['pool'] = $detail_info."({$adminInfo["username"]})".date("Y-m-d H:i:s");
            $detail['detail']['pool_status'] = $status;
        } else if($type == 1) {
            $detail['detail']['apply'] = $detail_info."({$adminInfo["username"]})".date("Y-m-d H:i:s");
            $detail['detail']['apply_status'] = $status;
            if ($status == 1) {
                $verify_status = 7;
            } else {
                $verify_status = -4;
            }
            M("aggregate_statement","tab_")->where(['id'=>$id])->save(['verify_status'=>$verify_status]);
        } else if($type == 2) {
            $detail['detail']['invoiced'] = $detail_info."({$adminInfo["username"]})".date("Y-m-d H:i:s");
            $detail['detail']['invoiced_status'] = $status;
        } else if($type == 3) {
            $detail['detail']['received'] = $detail_info."({$adminInfo["username"]})".date("Y-m-d H:i:s");
            $detail['detail']['received_status'] = $status;
        }

        M("aggregate_statement","tab_")->where(['id'=>$id])->save(['detail'=>json_encode($detail['detail'])]);

    }

    protected function setVerifyStatus($old_status,$change_status,$op_pre)
    {

        if(!isset($_REQUEST['ids'])) $this->error("参数错误");
        $ids = $_REQUEST['ids'];
        $dbres = $this->DBModel->field("id,verify_status,verify_log,statement_ids")->where("id in ({$ids})")->select();



        foreach($dbres as $k=>&$v){
            $get_statement_ids = explode(',',$v['statement_ids']);

            foreach ($get_statement_ids as $key => $value) {
                $this->setAggregateDetail(1,$change_status==1?1:0,$change_status==1?'审批通过':'审批拒绝',$value);
            }

            if($v['verify_status'] != $old_status) continue;
            $v['verify_log'] = json_decode($v['verify_log'],true);
            $v['verify_log'][$op_pre.'_user']=$this->admininfo["username"];
            $v['verify_log'][$op_pre.'_time']=date("Y-m-d H:i:s");
            $v['verify_log'] = json_encode($v['verify_log']);
            $v['verify_status']=$change_status;
            $this->DBModel->save($v);
            $opname = $this->VerifyStatus[$change_status];
            addOperationLog(['op_type'=>1,'key'=>$v['id'],"op_name"=>$opname,'url'=>U('lists')]);
        }
        $this->ajaxReturn(array(
            'status' => 1,
            "info"=>$opname."成功"
        ));
    }

    protected function setOneVerifyStatus($change_status,$op_pre,$id,$mgs = "操作")
    {
        $dbres = $this->DBModel->field("id,verify_status,verify_log")->where("id = {$id}")->find();
        $dbres['verify_log'] = json_decode($dbres['verify_log'],true);
        $dbres['verify_log'][$op_pre.'_user']=$this->admininfo["username"];
        $dbres['verify_log'][$op_pre.'_time']=date("Y-m-d H:i:s");
        $dbres['verify_log'] = json_encode($dbres['verify_log']);
        $dbres['verify_status']=$change_status;
        $this->DBModel->save($dbres);
        addOperationLog(['op_type'=>1,'key'=>$id,"op_name"=>$mgs,'url'=>U('lists')]);
        $this->ajaxReturn(array(
            'status' => 1,
            "info"=>$mgs."成功"
        ));
    }

    //打款设置
    public function setPayment(){
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];
        $CompanyInfo = M("aggregate_statement_info","tab_")
                      ->alias('i')
                      ->field("i.id,i.pool_id,i.company_name,i.company_info,i.statement_money,p.statement_num,i.remark,i.pay_status,p.statement_money all_money")
                      ->join("tab_company_statement_pool p ON p.id = i.pool_id")
                      ->where("pool_id='{$id}'")
                      ->select();
        foreach($CompanyInfo as $k=>&$v){
            $v['company_info'] = json_decode($v['company_info'],true);
            $v['company_info']['ali_user'] ?? '';
            $v['company_info']['ali_account'] ?? '';
        }

        $this->assign("CompanyInfo",$CompanyInfo);
        $this->assign("id",$id);
        $this->display();
    }
    //修改打款设置
    public function editPayment(){
        if(!isset($_REQUEST['info'])) $this->error("参数错误");
        $info = $_REQUEST['info'];
        $CompanyInfo = M("aggregate_statement_info","tab_");
        //循环保存
        foreach($info as $k=>$v){
            $ydata = $CompanyInfo->where("id= '{$k}'")->find();
            if($ydata['verify_status'] == 2){continue;}

            $company_info = json_decode($ydata['company_info'],true);
            $company_info['ali_user'] = $v['ali_user'];
            $company_info['ali_account'] = $v['ali_account'];
            $savedata = [
                "company_info"=>json_encode($company_info,JSON_UNESCAPED_UNICODE),
                "remark"=>$v['remark'],
                "id"=>$k
            ];
            if(empty($v['ali_user']) || empty($v['ali_account'])){
                $savedata['verify_status'] = -1;
            }else{
                $savedata['verify_status'] = 1;
            }
            $CompanyInfo->save($savedata);
        }
        //修改状态
       $this->setOneVerifyStatus(2,"payment",$_REQUEST['pool_id'],$mgs = "打款信息提交");
    }
    //查看打款信息
    public function viewPayment(){
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];
        $CompanyInfo = M("aggregate_statement_info","tab_")
                      ->alias('i')
                      ->field("i.id,i.pool_id,i.company_name,i.company_info,i.statement_money,p.statement_num,i.remark,i.pay_status,i.verify_status,p.statement_money all_money")
                      ->join("tab_company_statement_pool p ON p.id = i.pool_id")
                      ->where("pool_id='{$id}'")
                      ->select();
        foreach($CompanyInfo as $k=>&$v){
            $v['company_info'] = json_decode($v['company_info'],true);
            $v['company_info']['ali_user'] ?? '';
            $v['company_info']['ali_account'] ?? '';
            $v['verify_status_str'] = $this->InfoVerifyStatus[ $v['verify_status']];
           
            if($v['verify_status'] == 1){
                
                $v['verify_status_str'] = $this->PayStatus[$v['pay_status']];
                if($v['pay_status'] == 1){
                    $v['pay_type'] = $v['pay_type'] == 1 ? "提现" :"线上打款";
                    $v['verify_status_str'] .= ("/". $v['pay_type']);
                }
            }
        }

        $this->assign("CompanyInfo",$CompanyInfo);
        $this->display();
    }
    
    //保存备注
    public function saveRemark(){
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];
        $remark = $_REQUEST['remark'];
        $this->DBModel->where("id = '{$id}'")->save(['remark'=>$remark]);
        $this->ajaxReturn(array(
            'status' => 1,
            'info' => "操作成功"
        ));
    }

     //上传凭证
     public function uploadVoucher()
     {
         if(!isset($_REQUEST['id'])) $this->error("参数错误");
         $id = $_REQUEST['id'];
         $this->assign("id",$id);
         $this->display();
     }
     //修改凭证
     public function editVoucher()
     {
         if(!isset($_REQUEST['id'])) $this->error("参数错误");
         $id = $_REQUEST['id'];
         $info = $this->DBModel->field("id,ext_file")->where("id = '{$id}'")->find();
         $this->assign("id",$id);
         $this->assign("ext_file",$info['ext_file']);
         $this->display();
     }
     //保存凭证
     public function saveVoucher()
     {
         if(!isset($_REQUEST['id'])) $this->error("参数错误");
         $id = $_REQUEST['id'];
 
         $path = '/Uploads/';
         $upload = new \Think\Upload();// 实例化上传类
         $upload->maxSize   =     0 ;// 设置附件上传大小
         $upload->exts      = array('jpg', 'gif', 'png', 'jpeg');;// 设置附件上传类型
         $upload->rootPath  =     '.'.$path; // 设置附件上传根目录
         $upload->savePath  =     ''; // 设置附件上传(子)目录
         // 上传文件 
         $info   =   $upload->upload();
         if(!$info) {// 上传错误提示错误信息
             $msg = $upload->getError();
             $array= array('status' => 0, 'info' => $msg);
         }else{// 上传成功
             //
             $pf = $path.$info['file']['savepath'].$info['file']['savename'];
             $save = [
                 "ext_file"=>$pf,
             ];
             //获取旧值,存在删除
             $info = $this->DBModel->field("id,ext_file")->where("id = '{$id}'")->find();
             if(!empty($info['ext_file'])){
                 unlink("./".$info['ext_file']);
             }
             $this->DBModel->where("id = '{$id}'")->save($save);
             $array=array(
                 'status' => 1,
                 "info"=>"上传成功",
                 "file_path"=>$pf,
             );
         }
         $this->ajaxReturn($array);
     }
     //删除凭证
     public function delVoucher(){
         if(!isset($_REQUEST['id'])) $this->error("参数错误");
         $id = $_REQUEST['id'];
         $info = $this->DBModel->field("id,ext_file")->where("id = '{$id}'")->find();
         if(!empty($info['ext_file'])){
             unlink("./".$info['ext_file']);
         }
         $save = [
             "ext_file"=>'',
         ];

         $this->DBModel->where("id = '{$id}'")->save($save);
        //  $this->doAddOperationLog($id,"删除凭证");
         $this->ajaxReturn(array(
             'status' => 1,
             'info' => "删除成功"
         ));
     }
    //不结算
    public function cancelStatement()
    {
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];
        //获取结算信息
        $v =  M("aggregate_statement_info","tab_")->where("id = '{$id}'")->find();
        if(empty($v)){
            $this->error("请勿重复操作");
        }
        $pool =  M("aggregate_statement_pool","tab_")->where("id = {$v['pool_id']}")->find();
        // dump($pool);
        //保存未结算
        $lackcompany =[
            "company_id"=>$v['company_id'],
            "company_type"=>$v['company_type'],
            "company_name"=>$v['company_name'],
            "company_belong_name"=>$v['company_belong_name'],
            "company_info"=>$v['company_info'],
            "statement_money"=>$v['statement_money'],
            "pay_amount"=>$v['pay_amount'],
            "platform_amount"=>$v['platform_amount'],
            "fine"=>$v['fine'],
            "reward"=>$v['reward'],
            "statement_begin_time"=>$v['statement_begin_time'],
            "statement_end_time"=>$v['statement_end_time'],
            "is_payment"=>$pool['is_payment'],
            "statement_pool_num"=>$pool['statement_num'],
            "statement_info"=>$v['statement_info'],
            "withdraw_type"=>$pool['withdraw_type'],
        ];

        $l_id =  M("aggregate_lack_statement_info","tab_")->add($lackcompany);

        //汇总表
        $pool_data = [
            "id"=>$pool['id'],
            'statement_money'=>$pool['statement_money']-$v['statement_money'],
            'pay_amount'=>$pool['pay_amount']-$v['pay_amount'],
            'fine'=>$pool['fine']-$v['fine'],
            'reward'=>$pool['reward']-$v['reward'],
            'lack_statement_money'=>$pool['lack_statement_money']+$v['statement_money'],
            'lack_platform_amount'=>$pool['lack_platform_amount']-0+$v['platform_amount'],
            'verify_status'=>0
        ];
        //
        if(empty($pool_data['create_lack_ids'])){
            $pool_data['create_lack_ids'] = $l_id;
        }else{
            $pool_data['create_lack_ids'] = $pool_data['create_lack_ids'].",".$l_id;
        }
        $info_ids = explode(",",$pool['info_ids']);
        $pool_data['info_ids'] =implode(",",array_diff($info_ids,[$id]));
        M("aggregate_statement_pool","tab_")->save($pool_data);
        M("aggregate_statement_info","tab_")->where("id='{$id}'")->delete();
        $this->ajaxReturn(array(
            'status' => 1,
            "info"=>"不结算成功"
        ));
    }

    //撤销汇总
    public function cancelPool(){
        if(!isset($_REQUEST['id'])) $this->error("参数错误");
        $id = $_REQUEST['id'];
        //获取基础信息 
        $db_res = $this->DBModel->where("id='{$id}'")->find();

        $is_qz = (substr($db_res['statement_num'],0,2) == "QZ" ? true :false); //强制汇总的都允许回退
        if($is_qz){
            //强制汇总回退
            $this->cancelQzPool($db_res);
        }

        $re_op = true;
        $create_lack_ids = $db_res['create_lack_ids'];
        if(!empty($create_lack_ids) && !$is_qz){
            $clsi  =  M("aggregate_lack_statement_info","tab_")->where("is_pool = 1 and id in ({$create_lack_ids})")->find();
            $re_op = true;
            if(!empty($clsi)){
                $re_op = false; //被引用无法重算
            }
        }
        if($re_op){
            //公司及上游回退
            $this->cancelCompanyPool($db_res);//公司撤回
        }

    }
    /**
     * 重算 先全删再进行二次生成
     */
    public function retry($info)
    {
        //执行删除
        $dids = $info['del_lack_ids'];
        $cids = $info['create_lack_ids'];
        M()->startTrans();
         //删除info
        $infores  =  M("aggregate_statement_info","tab_")->where("pool_id = {$info['id']}")->delete();
        if($infores === false){
            M()->rollback();
            $this->ajaxReturn(array('status' => 0,"info"=>"重算失败"));
        }
        //删除自己
        $poolres = $this->DBModel->where("id = {$info['id']}")->delete();
        if($poolres === false){
            M()->rollback();
            $this->ajaxReturn(array('status' => 0,"info"=>"重算失败"));
        }
        //修改引用不足单
        if(!empty($dids)){
            $dres =  M("aggregate_lack_statement_info","tab_")->where("id in ({$dids})")->save(['is_pool'=>0]);
            if($dres === false){
                M()->rollback();
                $this->ajaxReturn(array('status' => 0,"info"=>"重算失败"));
            }
        }
        //删除创建的不足单
        if(!empty($cids)){
            $cres =  M("aggregate_lack_statement_info","tab_")->where("id in ({$cids})")->delete();
            if($cres === false){
                M()->rollback();
                $this->ajaxReturn(array('status' => 0,"info"=>"重算失败"));
            }
        }
        M()->commit();

        //重新计算
        $stime = $info['statement_end_time']-0+1;
        $type = $info['withdraw_type'];
        A("AggregateStatementSet")->promoteUserPool($type,$stime,true,$info['is_payment']);
        $this->ajaxReturn(array(
            'status' => 1,
            'info' => "重算成功"
        ));
    }

    public function cancelQzPool($info){
        if(!empty($info['del_lack_ids'])){
            M()->startTrans();//事务
           $dbres =  M("aggregate_lack_statement_info","tab_")->where("id in ({$info['del_lack_ids']})")->save(['is_pool'=>0]);
           $poolres = $this->DBModel->where("id = {$info['id']}")->delete();
           $infores  =  M("aggregate_statement_info","tab_")->where("pool_id = {$info['id']}")->delete();
           if($dbres !== false && $poolres !== false && $infores !== false){
                M()->commit();
                $this->ajaxReturn(array(
                    'status' => 1,
                    'info' => "撤销汇总成功"
                ));
           }
        }
        M()->rollback();
        $this->ajaxReturn(array(
            'status' => 0,
            'info' => "撤销汇总失败"
        ));
    }

    public function cancelCompanyPool($info)
    {
        if(in_array($info['verify_status'],[3,4])) return;//有打款就不允许回退

        $sids = $info['statement_ids'];
        $dids = $info['del_lack_ids'];
        $cids = $info['create_lack_ids'];

        M()->startTrans();//事务
        //删除info
        $infores  =  M("aggregate_statement_info","tab_")->where("pool_id = {$info['id']}")->delete();
        if($infores === false){
            M()->rollback();
            $this->ajaxReturn(array('status' => 0,"info"=>"撤销汇总失败"));
        }

        //删除自己
        $poolres = $this->DBModel->where("id = {$info['id']}")->delete();

        if($poolres === false){
            M()->rollback();
            $this->ajaxReturn(array('status' => 0,"info"=>"撤销汇总失败"));
        }
        //修改结算单信息
        $st_res = M("aggregate_statement","tab_")->field("id,verify_status")->where("id in ({$sids})")->select();

        foreach($st_res as $k=>&$v){

            if ($v['verify_status'] == 5) {
                M()->rollback();
                $this->ajaxReturn(array('status' => 0,"info"=>"拥有已到账的结算单,不能撤销汇总"));
            }

            $v['verify_status']=-3;
            $v['detail']="";

            $stres =  M("aggregate_statement","tab_")->save($v);

            if($stres === false){
                M()->rollback();
                $this->ajaxReturn(array('status' => 0,"info"=>"撤销汇总失败"));
            }
        }
        //修改引用不足单
        if(!empty($dids)){
            $dres =  M("aggregate_lack_statement_info","tab_")->where("id in ({$dids})")->save(['is_pool'=>0]);
            if($dres === false){
                M()->rollback();
                $this->ajaxReturn(array('status' => 0,"info"=>"撤销汇总失败"));
            }
        }
        //删除创建的不足单
        if(!empty($cids)){
            $cres =  M("aggregate_lack_statement_info","tab_")->where("id in ({$cids})")->delete();
            if($cres === false){
                M()->rollback();
                $this->ajaxReturn(array('status' => 0,"info"=>"撤销汇总失败"));
            }
        }
        M()->commit();
        $this->ajaxReturn(array(
            'status' => 1,
            "info"=>"撤销汇总成功"
        ));
    }



    public function OpAuth($info)
    {
        $id = $info['id'];
        $img = $info['ext_file'];
        $remark = $info['remark'];
        $create_lack_ids = $info['create_lack_ids'];
        $is_qz = (substr($info['statement_num'],0,2) == "QZ" ? true :false); //强制汇总的都允许回退

        $re_op = true;
        if(!empty($create_lack_ids) && !$is_qz){
            $clsi  =  M("aggregate_lack_statement_info","tab_")->where("is_pool = 1 and id in ({$create_lack_ids})")->find();
            $re_op = true;
            if(!empty($clsi)){
                $re_op = false; //被引用无法重算
            }
        }
        
        //原始列表
        $opBtn = [
            "viewPool"=>"<a class='confirm viewPool' data-id='{$id}'>查看</a>",

            "addRemark"=>"<a class='confirm addRemark' data-id='{$id}'>新增备注</a>",
            "editRemark"=>"<a class='confirm editRemark' data-remark='{$remark}' data-id='{$id}'>修改备注</a>",
            "viewRemark"=>"<a class='confirm viewRemark' data-remark='{$remark}' data-id='{$id}'>查看备注</a>",

            "uploadVoucher"=>"<a class='confirm uploadVoucher' data-id='{$id}'>上传凭证</a>",
            "viewVoucher"=>"<a class='confirm viewVoucher' data-img='{$img}' data-id='{$id}'>查看凭证</a>",
            "editVoucher"=>" <a class='confirm editVoucher' data-id='{$id}'>编辑凭证</a>",

            "setUlPayment"=>"<a class='confirm setUlPayment' data-id='{$id}'>线下打款</a>",

            "setPayment"=>"<a class='confirm setPayment' data-id='{$id}'>打款信息提交</a>",
            "editPayment"=>"<a class='confirm editPayment' data-id='{$id}'>打款信息编辑</a>",
            "viewPayment"=>"<a class='confirm viewPayment' data-id='{$id}'>打款详情</a>",

            'reCount'=>"<a class='confirm reCount' data-id='{$id}'>重算</a>",
            'cancelPool'=>"<a class='confirm cancelPool' data-id='{$id}'>撤销</a>",

        ];
        //操作对应菜单
        $optist = [];
        switch ($info['verify_status']) {
            case '-2':
            case '-1':
            case '0':
                $optist = ["viewPool","reCount","cancelPool"];
                break;
            case '1':
                $optist = ["viewPool","addRemark","viewRemark","editRemark","viewVoucher","editVoucher","uploadVoucher","setPayment","setUlPayment"];
                break;
            case '2':
                $optist = ["viewPool","addRemark","viewRemark","editRemark","viewVoucher","editVoucher","uploadVoucher","editPayment"];
                break;
            case '3':
                $optist = ["viewPool","addRemark","viewRemark","editRemark","viewVoucher","editVoucher","uploadVoucher","editPayment","viewPayment"];
                break;
            case '4':
                $optist = ["viewPool","addRemark","viewRemark","editRemark","viewVoucher","editVoucher","uploadVoucher","viewPayment"];
                break;
            case '5':
                $optist = ["viewPool","addRemark","viewRemark","editRemark","reCount","cancelPool"];
                break;
            default:
                break;
        }

        $optist = ["viewPool","cancelPool"];
        //
        if($info['platform_amount'] <= 0 && $info['company_type'] != 2){
            $optist = array_diff($optist, ["viewPool"]);
        }
        //个人重算,上游撤销
        if($re_op){

            if($is_qz){
                $optist = array_diff($optist, ["reCount"]);
            }else{
                if($info['company_type'] == 2){
                    $optist = array_diff($optist, ["cancelPool"]);
                }else{
                    $optist = array_diff($optist, ["reCount"]);
                }
            }
            
        }else{
            $optist = array_diff($optist, ["cancelPool","reCount"]);
        }

        if(empty($info['ext_file'])){
            //未上传凭证
            $optist = array_diff($optist, ["viewVoucher", "editVoucher"]);
        }else{
            $optist = array_diff($optist, ["uploadVoucher"]);
        }

        if($info['is_payment'] == 1){
            $optist = array_diff($optist, ["setUlPayment"]);
        }else{
            $optist = array_diff($optist, ["setPayment","editPayment","viewPayment"]);
        }

        if(empty($info['remark'])){
            //未上传备注
            $optist = array_diff($optist, ["editRemark", "viewRemark"]);
        }else{
            $optist = array_diff($optist, ["addRemark"]);
        }

        //
        $resarr = [];
        foreach ($optist as $k => $v) {
            if(IS_ROOT){
                $resarr[] = $opBtn[$v];
            }else{
                if(in_array("Admin/aggregateStatementPool/".$v,$this->OpAuthList)){
                    $resarr[] = $opBtn[$v];
                }
            }
        }
        return $resarr;
    }
    public function menuAuth()
    {
        $mentBtn = [
            "verifyAgree"=>"<a class='butn' id='verifyAgree'>审批通过</a>",
            "verifyRefuse"=>"<a class='butn' id='verifyRefuse' style='background-color: red;'>审核拒绝</a>",
            "export"=>"<a class='butn' id='export'>批量导出</a>"
        ];
        $resarr = [];
        foreach ($mentBtn as $k => $v) {
            if(IS_ROOT){
                $resarr[] = $v;
            }else{
                if(in_array("Admin/aggregateStatementPool/".$k,$this->OpAuthList)){
                    $resarr[] = $v;
                }
            }
        }
        return $resarr;
    }

}