<?php

namespace Home\Controller;

use Admin\Model\WithdrawModel;
use Base\Model\Model;
use OT\DataDictionary;
use Base\Repository\PromoteRepository;
use Base\Repository\SpendRepository;
use Base\Repository\UserRepository;
use Base\Service\PromoteService;

/**
 * 财务管理
 */
class FinanceController extends BaseController
{
    //提现状态
    public static $withdrawStatus = [
        -2 => '已撤销',
        -1 => '审核未通过',
        0 => '待审核',
        1 => '汇款中',
        2 => '已汇款',
    ];

    //权限过滤
    private function purview()
    {
        $this->getLoginPromote();
        if ($this->loginPromote['level'] != 1) {
            $this->error('权限异常');
        }
        return true;
    }

    private function getDayList($beginTime, $endTime, $timeType = 1)
    {
        $dayList = [];
        switch ($timeType) {
            case 1:
                do {
                    $dayList[] = date('Y-m-d', $beginTime);
                    $beginTime += 24 * 60 * 60;
                } while ($beginTime < $endTime);
                break;
            case 2:
                do {
                    $dayList[] = date('Y-m', $beginTime);
                    $beginTime = strtotime('+1 month', $beginTime);
                } while ($beginTime < $endTime);
                break;
        }

        return $dayList;
    }

    private function assembleRecords($items, $keys, $valueColumn, $keyColumn = 'day')
    {
        $records = [];
        foreach ($keys as $key) {
            $value = 0;
            foreach ($items as $item) {
                if ($item[$keyColumn] == $key) {
                    $value = $item[$valueColumn];
                }
            }
            $records[$key] = $value;
        }
        return $records;
    }

    //生成提现单号
    private function produceWithdrawNumber()
    {
        $prefix = 'WD_';
        $number = '';
        while (true) {
            $randomNum = rand(10, 99);
            $number = $prefix . time() . $randomNum;
            $map['widthdraw_number'] = $number;
            $res = M('withdraw', 'tab_')->where($map)->getField('id');
            if (!$res) {
                break;
            }
        }
        return $number;
    }

    //结算中心
    public function index()
    {
        //是否是会长
        $this->purview();
        $id = get_pid();
        $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
        if(empty($safePwd['second_pwd'])) {
            $this->display('Public/setSafePwd');
            exit;
        }
        //验证安全密码
        $metaTitle = '结算中心';
        $modelList = ['财务管理', $metaTitle];
        $this->verifyPasswordView($modelList);

        $model = M('spend', 'tab_');
        $thisDay = strtotime(date('Y-m-d'));
        $thisMonth = strtotime(date('Y-m'));
        $yesterday = strtotime(date('Y-m-d', strtotime('-1 day', time())));
        $nowTime = date('Y-m-d');
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
        $endTime = $endTime + 3600 * 24;

        $records = [];
        $income = [];
        if (intval($endTime - $begTime) / (24 * 3600) <= 31) {
            $map['chain'] = ['like', $this->loginPromote['chain'] . $this->loginPromote['id'] . '/%'];
            $promoteIds = M('promote', 'tab_')->where($map)->getField('id', true);
            $promoteIds[] = $this->loginPromote['id'];
            $promoteIds = implode(',', $promoteIds);

            $map = [];
            $map['pay_status'] = 1;
            $map['promote_id'] = ['in', $promoteIds];
            $income = $model->field("sum(if(pay_time < $thisDay, if(selle_ratio > 0, pay_amount * selle_ratio, 0), 0)) as history_income,
        sum(if(pay_time >= $thisMonth, if(selle_ratio > 0, pay_amount * selle_ratio, 0), 0)) as this_month_income,
        sum(if((pay_time >= $yesterday and pay_time < $thisDay), if(selle_ratio > 0, pay_amount * selle_ratio, 0), 0)) as yesterday_income,
        sum(if(pay_time < $thisDay, if(selle_status = 0, pay_amount * selle_ratio, 0), 0)) as balance")
                ->where($map)
                ->find();

            foreach ($income as &$value) {
                $value = bcdiv($value, 100, 2);
            }

            $withdrawMap['promote_id'] = $this->loginPromote['id'];
            $withdrawMap['status'] = 2;

            //已提现总额
            $income['withdrawn_amount'] = M('withdraw', 'tab_')->field('sum(sum_money) as withdrawn_amount')->where($withdrawMap)->find()['withdrawn_amount'];
            $withdrawMap['status'] = ['in', [-1, 0, 1]];
            $notWithdrawnAmount = M('withdraw', 'tab_')->field('sum(sum_money) as withdrawn_amount')->where($withdrawMap)->find()['withdrawn_amount'];
            $income['withdrawn_amount'] = $income['withdrawn_amount'] ?? '0.00';
            $notWithdrawnAmount = $notWithdrawnAmount ?? 0;
            $income['not_withdrawn_amount'] = bcadd($this->getSumAmountBySettlementType(), $notWithdrawnAmount, 2);

            $withdrawMap['status'] = ['not in', [-2, -1]];
            $withdrawns = M('withdraw', 'tab_')->field('settlement_begin_time, settlement_end_time')
                ->where($withdrawMap)
                ->select();

            $days = [];
            if (!empty($withdrawns)) {
                foreach ($withdrawns as $withdrawn) {
                    $thisDays = [];
                    if (empty($withdrawn['settlement_begin_time'])) {
                        if ($begTime < $withdrawn['settlement_end_time']) {
                            if ($endTime <= $withdrawn['settlement_end_time']) {
                                $thisEndTime = $endTime;
                            } else {
                                $thisEndTime = $withdrawn['settlement_end_time'];
                            }
                            $thisDays = $this->getDayList($begTime, $thisEndTime);
                        }
                    } else {
                        $thisDays = $this->getDayList($withdrawn['settlement_begin_time'], $withdrawn['settlement_end_time']);
                    }
                    $days = array_merge($days, $thisDays);
                }
            }
            $days = array_unique($days);

            $map['pay_time'] = ['between', [$begTime, $endTime]];
            $dayList = $this->getDayList($begTime, $endTime);
            $data = $model->field('FROM_UNIXTIME(pay_time, "%Y-%m-%d") as day,
        sum(if(selle_ratio > 0, pay_amount * selle_ratio, 0)) as income, selle_status')
                ->where($map)
                ->group('day')
                ->select();
            $data = $this->assembleRecords($data, $dayList, 'income');
            foreach ($dayList as $day) {
                $date = date('Ymd', strtotime($day));
                $records[] = [
                    'day' => $date,
                    'income' => bcdiv($data[$day], 100, 2),
                    'selle_status_text' => (in_array($day, $days) ? '已提现' : '未提现'),
                    'url' => U('settlementDtl', array('begtime' => $day, 'endtime' => $day))
                ];
            }
        }

        $settlementCycle = ($this->loginPromote['settlement_type'] == 1 ? '周结' : '月结');
        $this->assign('income', $income);
        $this->assign('listData', $records);
        $this->assign('settlementCycle', $settlementCycle);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('yesterday', date('Y-m-d', $yesterday));
        $this->assign('meta_title', $metaTitle);
        $this->display();
    }

    public function getSumAmountBySettlementType()
    {
        $withdrawModel = new WithdrawModel();
        $balance = 0;

        if ($this->loginPromote['settlement_type'] == 2) {
            $settlementType = 2;
        } else {
            $map['pay_status'] = 1;
            $map['selle_status'] = 0;
            $balance = M('spend', 'tab_')->field('sum(pay_amount * selle_ratio) as balance')->where($map)->find()['balance'];
            $balance = $balance ? bcdiv($balance , 100, 2) : 0;
            $settlementType = 3;
        }

        $months = $this->getDayList(strtotime('2019-09'), strtotime(date('Y-m')), 2);
        $promote = $this->loginPromote;

        if ($settlementType == 2) {
            $fun = 'getMonthAmount';
        } else {
            $fun = 'getRecoupAmount';
        }

        if ($months) {
            foreach ($months as $month) {
                $data['begin_time'] = strtotime($month);
                $data['end_time'] = strtotime('+1 month', $data['begin_time']) - 1;
                $balance = bcadd($balance, $withdrawModel->$fun($promote, $data), 2);
            }
        }

        return $balance;
    }

    public function getNotWithdrawnAmount()
    {
        $thisMonth = strtotime(date('Y-m'));
        $map['promote_id'] = $this->loginPromote['id'];
        $map['status'] = 1;
        $map['begin_time'] = ['elt', $thisMonth];
        $promoteGameRatios = M('promote_game_ratio', 'tab_')->field('game_id, begin_time, end_time, ratio, turnover_ratio')
            ->where($map)
            ->select();

        if (empty($promoteGameRatios)) {
            return 0;
        } else {
            $income = 0;
            $map['status'] = ['neq', -2];
            $map['settlement_type'] = ['in', [2, 3]];
            unset($map['begin_time']);
            $withdrawDays = M('withdraw', 'tab_')->where($map)->getField('settlement_begin_time', true);
            if ($withdrawDays) {
                foreach ($withdrawDays as &$withdrawDay) {
                    $withdrawDay = date('Y-m', $withdrawDay);
                }
            } else {
                $withdrawDays = [];
            }
            foreach ($promoteGameRatios as $promoteGameRatio) {
                $map = [];
                $map['game_id'] = $promoteGameRatio['game_id'];
                $promoteGameRatio['turnover_ratio'] = json_decode($promoteGameRatio['turnover_ratio'], true);
                $days = $this->getDayList($promoteGameRatio['begin_time'], $thisMonth, 2);
                if ($days) {
                    foreach ($days as $day) {
                        if (!in_array($day, $withdrawDays)) {
                            $day = strtotime($day);
                            $map['pay_time'] = ['between', [$day, strtotime('+1 month', $day) - 1]];
                            $sumAmount = $this->getSumMoney($map);
                            $diffRatio = $this->getDiffRatio($sumAmount, $promoteGameRatio['ratio'], $promoteGameRatio['turnover_ratio']);
                            $income += bcmul($sumAmount, bcdiv($diffRatio, 100, 2), 2);
                        }
                    }
                }
            }
        }

        return $income;
    }

    private function getSumMoney($map = [])
    {
        $map['pay_status'] = 1;

        $sumAmount = M('spend', 'tab_')->field('sum(pay_amount) as sum_amount')->where($map)->find()['sum_amount'];
        $sumAmount = $sumAmount ?? 0;
        return $sumAmount;
    }

    private function getDiffRatio($sumAmount, $defaultRatio, $turnoverRatios)
    {
        if ($turnoverRatios) {
            $ratio = $defaultRatio;
            foreach ($turnoverRatios as $turnoverRatio) {
                if (empty($turnoverRatio['instanceof']) || $turnoverRatio['instanceof'] == 1) {
                    if ($sumAmount >= $turnoverRatio['turnover']) {
                        $ratio = $turnoverRatio['ratio'];
                        break;
                    }
                } else {
                    if ($sumAmount > $turnoverRatio['turnover']) {
                        $ratio = $turnoverRatio['ratio'];
                        break;
                    }
                }
            }

            $ratio = bcsub($ratio - $defaultRatio, 2);
            return $ratio;
        }

        return 0;
    }

    //结算明细
    public function settlementDtl()
    {
        //是否是会长
        $this->purview();
        $id = get_pid();
        $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
        if(empty($safePwd['second_pwd'])) {
            $this->display('Public/setSafePwd');
            exit;
        }
        //验证安全密码
        $metaTitle = '结算明细';
        $modelList = ['财务管理', $metaTitle];
        $this->verifyPasswordView($modelList);

        $model = M('spend', 'tab_');
        $page = intval(I('get.p', 1));
        $page = $page ? $page : 1; //默认显示第一页数据arraypage
        $row = intval(I('get.row', 10));
        $gameId = intval(I('game_id', 0));
        $payOrderNumber = I('pay_order_number', '');
        $status = intval(I('status', 0));
        $nowTime = date('Y-m-d');
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
        $endTime += 3600 * 24;

        $parameter['p'] = $page;
        $parameter['row'] = $row;
        $parameter['game_id'] = $gameId;
        $parameter['pay_order_number'] = $payOrderNumber;
        !isset($_GET['status']) || $parameter['status'] = $status;
        $parameter['begtime'] = $initBegTime;
        $parameter['endtime'] = $initEndTime;

        $data = [];
        $total = [];
        $count = 0;
        if (intval($endTime - $begTime) / (24 * 3600) <= 31) {
            $withdrawIds = [];
            $map['chain'] = ['like', $this->loginPromote['chain'] . $this->loginPromote['id'] . '/%'];
            $ids = M('promote', 'tab_')->where($map)->getField('id', true);
            $ids[] = $this->loginPromote['id'];
            $ids = implode(',', $ids);

            $map = [];
            $map['promote_id'] = ['in', $ids];
            $map['pay_status'] = 1;
            $map['pay_time'] = ['between', [$begTime, $endTime]];
            if (!empty($gameId)) {
                $map['game_id'] = $gameId;
            }
            if (!empty($payOrderNumber)) {
                $map['pay_order_number'] = $payOrderNumber;
            }
            if (isset($_GET['status'])) {
                if ($status == -99) {
                    $map['selle_status'] = 0;
                } else {
                    $withdrawMap['promote_id'] = $this->loginPromote['id'];
                    $withdrawMap['status'] = $status;
                    $withdrawIds = M('withdraw', 'tab_')->where($withdrawMap)->getField('id', true);

                    if (empty($withdrawIds)) {
                        $map = '1 = 2';
                    } else {
                        $map['withdraw_id'] = ['in', $withdrawIds];
                    }
                }
            }

            $data = $model->field('pay_order_number,game_name,user_account,promote_id,promote_account,pay_amount,pay_way,if(selle_ratio >= 0,selle_ratio,0) as selle_ratio,pay_time,selle_status,pay_status,withdraw_id')
                ->where($map)
                ->order('id desc')
                ->page($page, $row)
                ->select();
            $count = $model->where($map)->count();
            $total = $model->field('sum(pay_amount) as pay_amount,sum(if(pay_way > -1,pay_amount,0)) as direct_pay_amount,sum(if(pay_way = -1,pay_amount,0)) as inner_pay_amount,sum(if(selle_ratio >= 0,selle_ratio * pay_amount,0)) as income')
                ->where($map)
                ->find();
            $total['direct_pay_amount'] = empty($total['direct_pay_amount']) ? '0.00' : $total['direct_pay_amount'];
            $total['inner_pay_amount'] = empty($total['inner_pay_amount']) ? '0.00' : $total['inner_pay_amount'];
            $total['income'] = empty($total['income']) ? 0 : $total['income'];
            $total['income'] = bcdiv($total['income'], 100, 2);

            //提现状态
            if (empty($withdrawIds)) {
                $withdrawIds = [0];
                foreach ($data as $key => $value) {
                    if ($value['withdraw_id'] > 0 && !in_array($value['withdraw_id'], $withdrawIds)) {
                        $withdrawIds[] = $value['withdraw_id'];
                    }
                }
            }
            $withdrawStatus = M('withdraw', 'tab_')
                ->where(array('id' => ['in', $withdrawIds]))
                ->getField('id,status');

            $promotes = [];
            $promoteService = new PromoteService();
            if (count($data) > 0) {
                $promoteIds = array_column($data, 'promote_id');
                $promotes = M('promote', 'tab_')->field(['id', 'chain', 'account'])->where(['id' => ['in', $promoteIds]])->select();
                $promotes = index_by_column('id', $promotes);
            }

            foreach ($data as &$list) {
                //提现状态
                if ($list['pay_status'] == 1) {
                    switch ($list['selle_status']) {
                        case 0:
                            $list['selle_status'] = '未提现';
                            break;
                        default:
                            if ($list['withdraw_id'] > 0) {
                                $list['selle_status'] = FinanceController::$withdrawStatus[$withdrawStatus[$list['withdraw_id']]];
                            } else {
                                $list['selle_status'] = '';
                            }
                            break;
                    }
                } else {
                    $list['selle_status'] = '支付失败';
                }

                $list['income'] = bcmul($list['pay_amount'], bcdiv($list['selle_ratio'], 100, 2), 2);
                $list['pay_time'] = date('Y-m-d H:i:s', $list['pay_time']);
                $list['user_account'] = encryption($list['user_account']);
                $list['promote_group'] = isset($promotes[$list['promote_id']]) ? $promoteService->getGroupNameByChain($promotes[$list['promote_id']]['chain'], $list['promote_id']) : '';
            }
        }

        $page = set_pagination($count, $row, $parameter);

        $this->assign('listData', $data);
        $this->assign('count', $count);
        $this->assign('total', $total);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('_page', $page);
        $this->assign('meta_title', $metaTitle);
        $this->assign('modelList', $modelList);
        $this->display();
    }

    //提现
    public function withdraw()
    {
        $this->error('无法执行此操作');
        //是否是会长
        $this->purview();
        //验证安全密码
        $modelList = [];
        $res = $this->verifyPasswordView($modelList, false);
        if ($res == false) {
            $data['status'] = 0;
            $data['msg'] = '权限异常';
            $this->ajaxReturn($data);
        }

        if ($this->loginPromote['ver_status'] != 1) {
            $data['status'] = 0;
            $data['msg'] = '未通过资质认证审核,暂时无法提现';
            $this->ajaxReturn($data);
        }

        $spendModel = M('spend', 'tab_');
        $thisDay = strtotime(date('Y-m-d'));

        $map['chain'] = ['like', $this->loginPromote['chain'] . $this->loginPromote['id'] . '/%'];
        $promoteIds = M('promote', 'tab_')->where($map)->getField('id', true);
        $promoteIds[] = $this->loginPromote['id'];
        $promoteIds = implode(',', $promoteIds);

        $map = [];
        $map['pay_status'] = 1;
        $map['selle_status'] = 0;
        $map['promote_id'] = ['in', $promoteIds];
        $map['pay_time'] = ['lt', $thisDay];
        $balance = $spendModel->field("sum(pay_amount * selle_ratio) as balance")
            ->where($map)
            ->find()['balance'];
        $balance = bcdiv($balance, 100, 2);
        if ($balance < 100) {
            $data['status'] = 0;
            $data['msg'] = '账户余额低于100元,无法提现!';
            $this->ajaxReturn($data);
        }
        $spendIds = $spendModel->where($map)->getField('id', true);
        if (empty($spendIds)) {
            $data['status'] = 0;
            $data['msg'] = '数据异常';
            $this->ajaxReturn($data);
        }

        $thisTime = time();
        $add['sum_money'] = $balance;
        $add['promote_id'] = $this->loginPromote['id'];
        $add['promote_account'] = $this->loginPromote['account'];
        $add['create_time'] = $thisTime;
        $add['status'] = 0;
        $add['widthdraw_number'] = $this->produceWithdrawNumber();
        $add['settlement_end_time'] = $thisDay - 1;
        $add['spend_ids'] = '';
        $add['op_id'] = $this->loginPromote['id'];
        $add['op_type'] = 1;
        $add['last_op_id'] = $this->loginPromote['id'];
        $add['last_op_type'] = 1;
        $add['settlement_type'] = 4;

        M()->startTrans();//开启事物
        $withdrawId = M('withdraw', 'tab_')->add($add);
        if (!$withdrawId) {
            M()->rollback();//事物回滚
            $data['status'] = 0;
            $data['msg'] = '提现失败';
            $this->ajaxReturn($data);
        }

        $map = [];
        $map['id'] = ['in', $spendIds];
        $save['selle_status'] = 1;
        $save['selle_time'] = $thisTime;
        $save['withdraw_id'] = $withdrawId;
        $res = $spendModel->where($map)->save($save);
        if ($res === false) {
            M('withdraw', 'tab_')->delete($withdrawId);
            M()->rollback();//事物回滚
            $data['status'] = 0;
            $data['msg'] = '提现失败';
            $this->ajaxReturn($data);
        }

        M()->commit();//事物提交
        $data['status'] = 1;
        $data['msg'] = '提现成功';
        $this->ajaxReturn($data);
    }

    //提现记录
    public function withdrawRecord()
    {
        //是否是会长
        $this->purview();
        $id = get_pid();
        $safePwd = M('promote','tab_')->where(['id'=>$id])->field('second_pwd')->find();
        if(empty($safePwd['second_pwd'])) {
            $this->display('Public/setSafePwd');
            exit;
        }
        //验证安全密码
        $metaTitle = '提现记录';
        $modelList = ['财务管理', $metaTitle];
        $this->verifyPasswordView($modelList);

        $model = M('withdraw', 'tab_');
        $page = intval(I('get.p', 1));
        $page = $page ? $page : 1; //默认显示第一页数据arraypage
        $row = intval(I('get.row', 10));
        $withdrawNumber = I('widthdraw_number', '');
        $initBegTime = I('begtime', '');
        $initEndTime = I('endtime', '');
        $begTime = strtotime(date('Y-m-d', strtotime($initBegTime)));
        $endTime = strtotime(date('Y-m-d', strtotime($initEndTime))) + 3600 * 24;
        $status = '';
        $settlementType = intval(I('settlement_type', 0));

        $parameter['p'] = $page;
        $parameter['row'] = $row;
        $parameter['widthdraw_number'] = $withdrawNumber;
        $parameter['begtime'] = $initBegTime;
        $parameter['endtime'] = $initEndTime;

        $map['promote_id'] = $this->loginPromote['id'];
        if (!empty($withdrawNumber)) {
            $map['widthdraw_number'] = $withdrawNumber;
        }
        if (!empty($initBegTime) && empty($initEndTime)) {
            $map['create_time'] = ['egt', $begTime];
        } elseif (empty($initBegTime) && !empty($initEndTime)) {
            $map['create_time'] = ['lt', $endTime];
        } elseif (!empty($initBegTime) && !empty($initEndTime)) {
            $map['create_time'] = ['between', [$begTime, $endTime - 1]];
        }
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $status = intval($_GET['status']);
            if (isset(FinanceController::$withdrawStatus[$status])) {
                $map['status'] = $status;
            }
        }
        if (!empty($settlementType)) {
            $map['settlement_type'] = $settlementType;
        }

        $data = $model->field('id, widthdraw_number, create_time, settlement_begin_time, settlement_end_time, sum_money, status, respond, transfer_proof, op_id, op_type, last_op_id, last_op_type, settlement_type')
            ->where($map)
            ->order('id desc')
            ->page($page, $row)
            ->select();
        $count = $model
            ->where($map)
            ->count();

        if (!empty($data)) {
            foreach ($data as &$list) {
                $list['create_time'] = date('Y-m-d H:i:s', $list['create_time']);
                $list['settlement_begin_time'] =  $list['settlement_begin_time'] ? date('Y-m-d H:i:s', $list['settlement_begin_time']) : '--';
                $list['settlement_end_time'] = date('Y-m-d H:i:s', $list['settlement_end_time']);
                $list['status_name'] = FinanceController::$withdrawStatus[$list['status']];
                $list['op_id'] = $this->getOpIdByType($list['op_id'], $list['op_type']);
                $list['last_op_id'] = $this->getOpIdByType($list['last_op_id'], $list['last_op_type']);
                $list['op_type'] = getPromoteWithdrawOpType($list['op_type']);
                $list['last_op_type'] = getPromoteWithdrawOpType($list['last_op_type']);
                $list['settlement_type_text'] = WithdrawModel::$settlementTypeList[$list['settlement_type']] ?? '未知';
                switch ($list['status']) {
                    case -2:
                        $list['status_name'] = '<span style="color: #bbbaba;">' . $list['status_name'] . '</span>';
                        break;
                    case -1:
                        $list['status_name'] = '<span style="color: red;">' . $list['status_name'] . '</span>';
                        break;
                    default:
                        break;
                }
            }
        }

        $page = set_pagination($count, $row, $parameter);

        $settlementTypeList = WithdrawModel::$settlementTypeList;

        $this->assign('listData', $data);
        $this->assign('count', $count);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('status', $status);
        $this->assign('_page', $page);
        $this->assign('meta_title', $metaTitle);
        $this->assign('modelList', $modelList);
        $this->assign('settlementTypeList', $settlementTypeList);
        $this->display();
    }

    private function getOpIdByType($opId, $opType)
    {
        switch ($opType) {
            case 1:
                $opId = get_promote_name($opId);
                break;
            case 2:
                $opId = getAdminNickname($opId);
                break;
            case 3:
                $opId = '自动';
                break;
        }

        return $opId;
    }

    //提现明细
    public function withdrawDtl()
    {
        //是否是会长
        $this->purview();
        //验证安全密码
        $metaTitle = '提现明细';
        $modelList = ['财务管理', '提现记录', $metaTitle];
        $this->verifyPasswordView($modelList);

        $model = M('withdraw', 'tab_');
        $spendModel = M('spend', 'tab_');
        $page = intval(I('get.p', 1));
        $page = $page ? $page : 1; //默认显示第一页数据arraypage
        $row = intval(I('get.row', 10));
        $withdrawId = intval(I('get.id', 0));
        if ($withdrawId == 0) {
            $this->error('参数异常');
        }
        $withdraw = $model->where(array('id' => $withdrawId))->find();
        if (empty($withdraw) || $withdraw['promote_id'] != $this->loginPromote['id']) {
            $this->error('参数异常');
        }
        $gameId = intval(I('game_id', 0));
        $userAccount = I('user_account', '');
        $payOrderNumber = I('pay_order_number', '');

        $parameter['p'] = $page;
        $parameter['row'] = $row;
        $parameter['id'] = $withdrawId;
        $parameter['game_id'] = $gameId;
        $parameter['user_account'] = $userAccount;
        $parameter['pay_order_number'] = $payOrderNumber;

        if ($withdraw['settlement_type'] == 3) {
            if (empty($withdraw['game_ratio'])) {
                $map['_string'] = '1 = 2';
            } else {
                $gameRatios = json_decode($withdraw['game_ratio'], true);
                $gameIds = array_keys($gameRatios);
                $map['game_id'] = ['in', $gameIds];
                $map['pay_time'] = ['between', [$withdraw['settlement_begin_time'], $withdraw['settlement_end_time']]];
            }
        } else {
            $map['withdraw_id'] = $withdrawId;
        }
        if (!empty($gameId)) {
            $map['game_id'] = $gameId;
        }
        if (!empty($userAccount)) {
            $map['user_account'] = $userAccount;
        }
        if (!empty($payOrderNumber)) {
            $map['pay_order_number'] = $payOrderNumber;
        }

        $data = $spendModel
            ->field('id,pay_order_number,game_name,sdk_version,user_account,pay_amount,pay_way,selle_ratio,pay_time')
            ->where($map)
            ->order('id desc')
            ->page($page, $row)
            ->select();
        $count = $spendModel
            ->where($map)
            ->count();

        if (!empty($data)) {
            foreach ($data as &$list) {
                $list['income'] = bcmul($list['pay_amount'], bcdiv($list['selle_ratio'], 100, 2), 2);
                $list['pay_time'] = date('Y-m-d H:i:s', $list['pay_time']);
                $list['user_account'] = encryption($list['user_account']);
                switch ($list['pay_way']) {
                    case 2:
                    case 3:
                    case 4:
                        $list['pay_way_name'] = QueryController::$payWay[2];
                        break;
                    default:
                        $list['pay_way_name'] = QueryController::$payWay[$list['pay_way']];
                        break;
                }
            }
        }

        $page = set_pagination($count, $row, $parameter);

        $this->assign('listData', $data);
        $this->assign('count', $count);
        $this->assign('status', FinanceController::$withdrawStatus[$withdraw['status']]);
        $this->assign('_page', $page);
        $this->assign('meta_title', $metaTitle);
        $this->assign('modelList', $modelList);
        $this->display();
    }

    //结算单
    public function settlementOrder()
    {
        //是否是会长
        $this->purview();
        //验证安全密码
        $metaTitle = '公会对账';
        $modelList = ['财务管理', '提现记录', $metaTitle];
        $this->verifyPasswordView($modelList);

        $model = M('withdraw', 'tab_');
        $withdrawId = intval(I('get.id', 0));
        if ($withdrawId == 0) {
            $this->error('参数异常');
        }
        $withdraw = $model->find($withdrawId);
        if (empty($withdraw) || $withdraw['promote_id'] != $this->loginPromote['id']) {
            $this->error('参数异常');
        }

        $statementMap['ext_field'] =  $withdraw['widthdraw_number'];
        $statementMap['statement_type'] =  1;
        $statement = M('statement', 'tab_')->where($statementMap)->find();
        if (empty($statement)) {
            $this->error('未生成下游对账单');
        }

        $statement['first_party_info'] = json_decode($statement['first_party_info'], 1);//甲方
        $statement['second_party_info'] = json_decode($statement['second_party_info'], 1);//乙方
        $statement['statement_info'] = json_decode($statement['statement_info'], 1);//结算记录
        //收款方
        $statement['receive_company'] = ($statement['pay_type'] ? $statement['first_party_info']['partner'] : $statement['second_party_info']['partner']);
        $all_sum_money = array_sum(array_column($statement['statement_info'], 'sum_money'));//合计平台总额
        $all_pay_amount = array_sum(array_column($statement['statement_info'], 'pay_amount'));//合计结算金额
        $big_all_sum_money = convertAmountToCn($statement['statement_money']);//大写
        $this->assign('big_all_sum_money', $big_all_sum_money);
        $this->assign('all_sum_money', $all_sum_money);
        $this->assign('all_pay_amount', $all_pay_amount);
        $this->assign('data', $statement);
        $this->assign('meta_title', $metaTitle);
        $this->assign('modelList', $modelList);
        $this->display();
    }

    //审核拒绝 重新审核
    public function renewReview()
    {
        $this->error('无法执行此操作');
        //是否是会长
        $this->purview();
        //验证安全密码
        $modelList = [];
        $res = $this->verifyPasswordView($modelList, false);
        if ($res == false) {
            $data['status'] = 0;
            $data['msg'] = '权限异常';
            $this->ajaxReturn($data);
        }

        $id = intval(I('id', 0));
        $data = M('withdraw', 'tab_')->find($id);
        if (empty($data) || $data['status'] != -1) {
            $data['status'] = 0;
            $data['msg'] = '数据异常';
            $this->ajaxReturn($data);
        }
        if ($data['promote_id'] != $this->loginPromote['id']) {
            $data['status'] = 0;
            $data['msg'] = '权限异常';
            $this->ajaxReturn($data);
        }

        $save['status'] = 0;
        $save['id'] = $id;
        $save['last_op_id'] = $this->loginPromote['id'];
        $save['last_op_type'] = 1;
        $res = M('withdraw', 'tab_')->save($save);
        if ($res === false) {
            $data['status'] = 0;
            $data['msg'] = '提交失败';
        } else {
            $data['status'] = 1;
            $data['msg'] = '提交成功';
        }
        $this->ajaxReturn($data);
    }

    //撤销提现
    public function cancelWithdraw()
    {
        $this->error('无法执行此操作');
        //是否是会长
        $this->purview();
        //验证安全密码
        $modelList = [];
        $res = $this->verifyPasswordView($modelList, false);
        if ($res == false) {
            $data['status'] = 0;
            $data['msg'] = '权限异常';
            $this->ajaxReturn($data);
        }

        $id = intval(I('id', 0));
        $data = M('withdraw', 'tab_')->find($id);
        if (empty($data) || !in_array($data['status'], [-1, 0])) {
            $data['status'] = 0;
            $data['msg'] = '数据异常';
            $this->ajaxReturn($data);
        }
        if ($data['promote_id'] != $this->loginPromote['id']) {
            $data['status'] = 0;
            $data['msg'] = '权限异常';
            $this->ajaxReturn($data);
        }

        $spendMap['withdraw_id'] = $id;
        $spendIds = M('Spend', 'tab_')->where($spendMap)->getField('id', true);
        if (empty($spendIds)) {
            $data['status'] = 0;
            $data['msg'] = '数据异常';
            $this->ajaxReturn($data);
        }
        $spendIds = implode(',', $spendIds);
        $time = time();
        $withdrawSave['id'] = $id;
        $withdrawSave['status'] = -2;
        $withdrawSave['spend_ids'] = $spendIds;
        $withdrawSave['last_up_update_time'] = $time;
        $withdrawSave['last_op_id'] = $this->loginPromote['id'];
        $withdrawSave['last_op_type'] = 1;

        M('withdraw', 'tab_')->startTrans();//开启事物
        $withdrawRes = M('withdraw', 'tab_')->save($withdrawSave);
        if ($withdrawRes === false) {
            M('withdraw', 'tab_')->rollback();//事物回滚
            $data['status'] = 0;
            $data['msg'] = '撤销失败';
            $this->ajaxReturn($data);
        }

        $spendSave['selle_status'] = 0;
        $spendSave['withdraw_id'] = 0;
        $spendRes = M('spend', 'tab_')->where($spendMap)->save($spendSave);
        if ($spendRes === false) {
            M('withdraw', 'tab_')->rollback();//事物回滚
            $data['status'] = 0;
            $data['msg'] = '撤销失败';
        } else {
            M('withdraw', 'tab_')->commit();//事物提交
            $data['status'] = 1;
            $data['msg'] = '撤销成功';
        }
        $this->ajaxReturn($data);
    }
}