<?php

namespace Admin\Controller;

use Admin\Model\PromoteModel;
use Home\Controller\FileController;
use User\Api\UserApi as UserApi;
use Admin\Model\WithdrawModel;

/**
 * 推广查询控制器
 * @author 王贺
 */
class QueryController extends ThinkController
{
    public $pay_way_name = [       //无费率默认平台必 即是费率为0
        '-1' => 'bind_pay',   //绑币支付
        '0' => 'ptb_pay',    //平台币支付
        '1' => 'alipay',    //支付宝
        '2' => 'wei_xin',
        '3' => 'wei_xin',
        '4' => 'weixin',
        '5' => 'ptb_pay',
        '6' => 'jft',   //竣付通
        '7' => 'ptb_pay',
        '8' => 'ptb_pay',
        '9' => 'sqpay', //双乾支付-支付宝
        '10' => 'sqpay',  //双乾支付-银联
        '15' => 'sqpay', //双乾支付-快捷
    ];
    //生成提现单号
    public 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 settlement($p = 0)
    {
        $settlementType = intval(I('settlement_type', 0));
        $settlementTypeList = WithdrawModel::$settlementTypeList;
        $page = intval(I('p', 1)); //默认显示第一页数据
        $row = intval(I('row', 10));
        $group = I('group', 1);
        $this->assign('group', $group);
        $this->assign('is_admin', is_administrator());
        $promoteId = I('promote_id', 0);

        if ($group == 1) {
            unset($settlementTypeList[WithdrawModel::SETTLEMENT_TYPE_OTHER]);
            $time = I('time', '');
            if (empty($promoteId) || empty($settlementType) || empty($time)) {
                $this->assign('settlementTypeList', $settlementTypeList);
                $this->display();
            } else {
                $promoteIds = M('promote', 'tab_')->where(['chain' => ['like', "/{$promoteId}/%"]])->getField('id', true);
                $promoteIds[] = $promoteId;

                if ($settlementType == 1) {
                    $time = explode(' 至 ', $time);
                    if (count($time) != 2) {
                        $this->display();die;
                    }

                    $beginTime = strtotime($time[0]);
                    $endTime = strtotime($time[1]) + 3600 * 24 - 1;
                } else {
                    $beginTime = strtotime($time);
                    $endTime = strtotime('+1 month', $beginTime) - 1;
                }

                $promote = M('promote', 'tab_')->find($promoteId);
                if (empty($promote) || $promote['level'] != 1 || empty($promote['settlement_type'])) {
                    $this->error('网络异常');
                }
                if ($promote['settlement_type'] == 1) {
                    unset($settlementTypeList[WithdrawModel::SETTLEMENT_TYPE_MONTH]);
                } else {
                    unset($settlementTypeList[WithdrawModel::SETTLEMENT_TYPE_WEEK]);
                    unset($settlementTypeList[WithdrawModel::SETTLEMENT_TYPE_RECOUP]);
                }
                if ($settlementType == 3) {
                    $withdrawMap['promote_id'] = $promoteId;
                    $withdrawMap['status'] = ['neq', -2];
                    $withdrawMap['settlement_begin_time'] = $beginTime;
                    $withdrawMap['settlement_end_time'] = $endTime;
                    $withdraw = D('withdraw')->where($withdrawMap)->find();
                    if (!empty($withdraw)) {
                        $this->assign('settlementTypeList', $settlementTypeList);
                        $this->display();die;
                    }
                } else {
                    $spendMap['tab_spend.selle_status'] = 0;
                }

                $sortBy = I('sort_by', '');
                $sortColumn = I('sort_column', '');
                $order = 'day';
                $orderType = 'desc';

                if (in_array($sortColumn, ['user_num', 'sum_amount'])) {
                    $order = $sortColumn;
                }
                if ($sortBy == 1) {
                    $orderType = 'desc';
                } elseif ($sortBy == 2) {
                    $orderType = 'asc';
                }

                $spendMap['tab_spend.pay_status'] = 1;
                $spendMap['tab_spend.pay_time'] = ['between', [$beginTime, $endTime]];
                $spendMap['tab_spend.promote_id'] = ['in', $promoteIds];
                $spendField = "tab_spend.game_id, tab_spend.game_name, sum(tab_spend.pay_amount) as sum_amount, tab_spend.selle_ratio, sum(if(tab_spend.selle_ratio > 0, tab_spend.pay_amount * tab_spend.selle_ratio, 0)) as settlement_amount, FROM_UNIXTIME(tab_spend.`pay_time`, '%Y-%m-%d') as day";
                $userMap['tab_user.promote_id'] = ['in', $promoteIds];
                $userMap['_string'] = 'tab_user.promote_id = tab_spend.promote_id';
                $userField = M('user', 'tab_')->field('count(tab_user.id) as user_num')
                    ->where($userMap)
                    ->buildSql();
                $field = "{$spendField}, {$userField} as user_num";

                $query = M('spend', 'tab_')->field($field)
                    ->where($spendMap)
                    ->group('tab_spend.selle_ratio, tab_spend.game_id, day')
                    ->order("{$order} {$orderType}");
                if(I('export', 0) != 1){
                    $query->page($page, $row);
                }
                $records = M()->table($query->buildSql())
                    ->alias('record')
                    ->select();
                if(I('export', 0) != 1){
                    $countQuery = M('spend', 'tab_')->field($spendField)
                        ->where($spendMap)
                        ->group('tab_spend.selle_ratio, tab_spend.game_id, day')
                        ->buildSql();
                    $count = M()->table($countQuery)
                        ->alias('tab_spend')
                        ->count();
                    $page = set_pagination($count, $row);
                }

                if (!empty($records)) {
                    foreach ($records as &$record) {
                        $record['promote_account'] = $promote['account'] ?? '未知';
                        $record['settlement_amount'] = bcdiv($record['settlement_amount'], 100, 2);
                    }
                }

                if ($settlementType != 3) {
                    $totalField = 'sum(if(tab_spend.selle_ratio > 0, tab_spend.pay_amount * tab_spend.selle_ratio, 0)) as settlement_amount';
                    $zTotal = null_to_0(M('spend', 'tab_')->field($totalField)->where($spendMap)->find()['settlement_amount']);//累计
                    $zTotal = bcdiv($zTotal, 100 ,2);
                } else {
                    $spendMap['game_id'] = 157;
                    $totalField = 'sum(tab_spend.pay_amount) as sum_amount';
                    $zTotal = null_to_0(M('spend', 'tab_')->field($totalField)->where($spendMap)->find()['sum_amount']);//累计
                }

                if(I('export', 0) == 1) {
                    $data = [];
                    foreach ($records as $value) {
                        $data[] = [
                            'day' => $value['day'],
                            'promote_account' => $value['promote_account'],
                            'game_name' => $value['game_name'],
                            'sum_amount' => $value['sum_amount'],
                            'user_num' => $value['user_num'],
                            'type' => 'CPS',
                            'selle_ratio' => $value['selle_ratio'] . '%',
                            'settlement_amount' => $value['settlement_amount'],
                        ];
                    }

                    $field = [
                        'day' => '日期',
                        'promote_account' => '会长账号',
                        'game_name' => '游戏名称',
                        'sum_amount' => '总充值',
                        'user_num' => '总注册',
                        'type' => '结算模式',
                        'selle_ratio' => '分成比例',
                        'settlement_amount' => '结算金额',
                    ];
                    data2csv($data,"推广结算", $field);
                    exit;
                }

                if($page) {
                    $this->assign('_page', $page);
                }
                $this->assign('settlementTypeList', $settlementTypeList);
                $this->assign('records', $records);
                $this->assign('zTotal', $zTotal);
                $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/settlement', 'status' => 1])->find());
                $this->m_title = '推广结算';
                $this->display();
            }
        } elseif ($group == 2) {
            $map['_string'] = '1 = 1';
            $createTime = strtotime(I('create_time', ''));
            $withdrawNumber = I('widthdraw_number', '');
            $status = intval(I('status', ''));
            $opType = intval(I('op_type', 0));
            if ($createTime) {
                $createTimeEnd = $createTime + 3600 * 24 - 1;
                $map['create_time'] = ['between', [$createTime, $createTimeEnd]];
            }
            if ($promoteId) {
                $map['promote_id'] = $promoteId;
            }
            if ($withdrawNumber) {
                $map['widthdraw_number'] = ['like', "{$withdrawNumber}%"];
            }
            if (isset($_REQUEST['status'])) {
                $map['status'] = $status;
            }
            if ($opType) {
                $map['op_type'] = $opType;
            }
            if ($settlementType) {
                $map['settlement_type'] = $settlementType;
            }

            $query = M('withdraw', 'tab_')->field('id, promote_account, widthdraw_number, sum_money, op_id, op_type, last_op_id, last_op_type, settlement_begin_time, settlement_end_time, create_time, status, respond, settlement_type')
                ->where($map)
                ->order('create_time desc');
            if(I('export', 0) != 1){
                $query->page($page, $row);
            }
            $records = $query->select();
            if(I('export', 0) != 1){
                $count = M('withdraw', 'tab_')->field('id, promote_account, widthdraw_number, sum_money, op_id, op_type, last_op_id, last_op_type, settlement_begin_time, settlement_end_time, create_time, status, respond')
                    ->where($map)
                    ->count();
            }
            if (!empty($records)) {
                foreach ($records as &$record) {
                    $record['settlement_begin_time'] = $record['settlement_begin_time'] ? date('Y-m-d H:i:s', $record['settlement_begin_time']) : '--';
                    $record['settlement_end_time'] = date('Y-m-d H:i:s', $record['settlement_end_time']);
                    $record['create_time'] = date('Y-m-d H:i:s', $record['create_time']);
                    $record['status_text'] = promoteWithdrawStatus($record['status']);
                    if ($record['status'] == -2) {
                        $record['status_text'] = '<span style="color: #999;">' . $record['status_text'] . '</span>';
                    }
                    $record['op_id_text'] = $this->getOpTypeText($record['op_type'], $record['op_id']);
                    $record['last_op_id_text'] = $this->getOpTypeText($record['last_op_type'], $record['last_op_id']);
                    $record['op_type_text'] = getPromoteWithdrawOpType($record['op_type']);
                    $record['last_op_type_text'] = getPromoteWithdrawOpType($record['last_op_type']);
                    $record['settlement_type_text'] = getPromoteWithdrawSettlementType($record['settlement_type']);
                }
            }

            if(I('export', 0) == 1) {
                $data = [];
                foreach ($records as $value) {
                    $data[] = [
                        'promote_account' => $value['promote_account'],
                        'widthdraw_number' => $value['widthdraw_number'],
                        'sum_money' => $value['sum_money'],
                        'op_id_text' => $value['op_id_text'],
                        'op_type_text' => $value['op_type_text'],
                        'last_op_id_text' => $value['last_op_id_text'],
                        'last_op_type_text' => $value['last_op_type_text'],
                        'settlement_type_text' => $value['settlement_type_text'],
                        'settlement_begin_time' => $value['settlement_begin_time'],
                        'settlement_end_time' => $value['settlement_end_time'],
                        'create_time' => $value['create_time'],
                        'status_text' => promoteWithdrawStatus($value['status']),
                        'respond' => $value['respond'],
                    ];
                }

                $field = [
                    'promote_account' => '推广员账号',
                    'widthdraw_number' => '结算单号',
                    'sum_money' => '结算金额',
                    'op_id_text' => '操作人',
                    'op_type_text' => '操作人类型',
                    'last_op_id_text' => '最后操作人',
                    'last_op_type_text' => '最后操作人类型',
                    'settlement_type_text' => '提现模式',
                    'settlement_begin_time' => '结算开始时间',
                    'settlement_end_time' => '结算截止时间',
                    'create_time' => '提现时间',
                    'status_text' => '提现状态',
                    'respond' => '说明',
                ];
                data2csv($data,"推广结算", $field);
                exit;
            }

            $page = set_pagination($count, $row);
            if($page) {
                $this->assign('_page', $page);
            }
            $this->assign('settlementTypeList', $settlementTypeList);
            $this->assign('records', $records);
            $this->display();
        }
    }

    private function getOpTypeText($type, $id)
    {
        switch ($type) {
            case 1:
                return get_promote_name($id);
                break;
            case 2:
                return getAdminNickname($id);
                break;
            default:
                return '自动';
                break;
        }
    }

    public function settlementWithdraw()
    {
        $promoteId = intval(I('promote_id', 0));
        $settlementType = intval(I('settlement_type', 0));
        $time = I('time', '');
        if (empty($promoteId)) {
            $data['status'] = 0;
            $data['msg'] = '请选择会长账号';
            $this->ajaxReturn($data);
        }
        if (empty($settlementType)) {
            $data['status'] = 0;
            $data['msg'] = '请选择提现模式';
            $this->ajaxReturn($data);
        }
        if (empty($time)) {
            $data['status'] = 0;
            $data['msg'] = '请选择充值时间';
            $this->ajaxReturn($data);
        }

        $promote = M('promote', 'tab_')->find($promoteId);
        if (empty($promote)) {
            $data['status'] = 0;
            $data['msg'] = '数据异常';
            $this->ajaxReturn($data);
        }
        if ($promote['level'] != 1) {
            $data['status'] = 0;
            $data['msg'] = '非会长账号,无法执行此操作';
            $this->ajaxReturn($data);
        }
        if ($promote['ver_status'] != 1) {
            $data['status'] = 0;
            $data['msg'] = '该会长未通过资质认证审核,暂时无法提现';
            $this->ajaxReturn($data);
        }
        if ($promote['settlement_type'] == 1) {
            if (!in_array($settlementType, [1, 3])) {
                $data['status'] = 0;
                $data['msg'] = '参数异常';
                $this->ajaxReturn($data);
            }
        } else {
            if ($settlementType != 2) {
                $data['status'] = 0;
                $data['msg'] = '参数异常';
                $this->ajaxReturn($data);
            }
        }

        if ($settlementType == 1) {
            $time = explode(' 至 ', $time);
            if (count($time) != 2) {
                $data['status'] = 0;
                $data['msg'] = '参数异常';
                $this->ajaxReturn($data);
            }
            $beginTime = strtotime($time[0]);
            $endTime = strtotime($time[1]) + 3600 * 24 - 1;
        } else {
            $beginTime = strtotime($time);
            $endTime = strtotime('+1 month', $beginTime) - 1;
        }

        $withdrawModel = new WithdrawModel();
        $data['begin_time'] = $beginTime;
        $data['end_time'] = $endTime;
        $data['op_id'] = is_login();
        $data['op_type'] = 2;
        switch ($settlementType) {
            case 1:
                $result = $withdrawModel->promoteWithdrawWeeklyByPromote($promote, false, $data);
                break;
            case 2:
                $result = $withdrawModel->promoteWithdrawPerMonthByPromote($promote, false, $data);
                break;
            case 3:
                $result = $withdrawModel->promoteWithdrawRecoupByPromote($promote, $data);
                break;
        }

        $data = [];
        $data['status'] = 0;
        switch ($result) {
            case -4:
            case -3:
                $data['msg'] = '无可补点订单';
                break;
            case -2:
                if ($settlementType == 3) {
                    $data['msg'] = '无可补点订单';
                } else {
                    $data['msg'] = '累计结算低于100元,无法提现!';
                }
                break;
            case -1:
            case 0:
                $data['msg'] = '操作失败';
                break;
            case 1:
                $data['status'] = 1;
                $data['msg'] = '操作成功';
                break;
        }

        $this->ajaxReturn($data);
    }

    public function renewReview()
    {
        $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);
        }

        $save['id'] = $id;
        $save['status'] = 0;
        $save['last_up_update_time'] = time();
        $save['last_op_id'] = is_login();
        $save['last_op_type'] = 2;
        $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()
    {
        $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);
        }

        $time = time();
        $data['status'] = 1;
        $data['msg'] = '撤销成功';
        $withdrawSave['id'] = $id;
        $withdrawSave['status'] = -2;
        $withdrawSave['last_up_update_time'] = $time;
        $withdrawSave['last_op_id'] = is_login();
        $withdrawSave['last_op_type'] = 2;
        if ($data['settlement_type'] == 3) {
            $withdrawRes = M('withdraw', 'tab_')->save($withdrawSave);
            if ($withdrawRes === false) {
                $data['status'] = 0;
                $data['msg'] = '撤销失败';
                $this->ajaxReturn($data);
            }
        } else {
            $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);
            $withdrawSave['spend_ids'] = $spendIds;

            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();//事物提交
            }
        }

        $this->ajaxReturn($data);
    }

    public function downloadProve()
    {
        $id = intval(I('id', 0));
        if ($id) {
            $withdraw = M('withdraw', 'tab_')->find($id);
            if (empty($withdraw) || $withdraw['status'] != 2 || !$withdraw['transfer_proof']) {
                $this->error('网络异常');
            }

            $file = new FileController();
            $file->download($withdraw['transfer_proof']);
        } else {
            $this->error('参数异常');
        }
    }

    public function cpsettlement($p = 0)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $this->assign('setdate', date("Y-m-d", strtotime("-1 day")));
        if ($_REQUEST['sum_money'] == 2) {
            $order = 'total desc';
        } else if ($_REQUEST['sum_money'] == 1) {
            $order = 'total asc';
        }
        $group = I('group', 1);
        $this->assign('group', $group);


        $this->m_title = '开发者结算';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/cpsettlement', 'status' => 1])->find());

        if (isset($_REQUEST['timestart']) && $_REQUEST['timestart'] != '' && $_REQUEST['group'] == 1) {
            $starttime = strtotime($_REQUEST['timestart']);
            $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;

            if (isset($_REQUEST['developers_id'])) {
                $map['g.developers'] = $_REQUEST['developers_id'];
            } else {
                $this->error('请选择开发者');
            }

            if (isset($_REQUEST['selle_status'])) {
                if ($_REQUEST['selle_status'] == "未结算") {
                    $map['s.selle_status'] = 0;
                } else if ($_REQUEST['selle_status'] == "已结算") {
                    $map['s.selle_status'] = 1;
                }
            } else {
                $map['s.selle_status'] = 0;
            }
            //判断是否结算绑币
            if ($_REQUEST['bind_coin'] == 0) {
                $map['s.pay_way'] = array('neq', -1);
            }
            $map['s.pay_status'] = 1;
            $map['pay_time'] = array('BETWEEN', array($starttime, $endtime));
            $model = array(
                'm_name' => 'Spend as s',
                'order' => $order,
                'title' => '渠道结算',
                'group' => 'g.developers,g.id',
                'fields' => 'sum(s.pay_amount) as total,s.selle_ratio,s.id,g.developers,s.selle_status,g.id as gid,g.game_name,s.pay_status,s.pay_amount',
                'template_list' => 'cpsettlement',
            );

            $user = A('Spend', 'Event');
            $this->meta_title = '开发者结算';
            $user->cpsettl_list($model, $p, $map);
        } else if ($_REQUEST['group'] == 2) {

            if (isset($_REQUEST['timestart']) && $_REQUEST['timeend'] != '') {
                $starttime = strtotime($_REQUEST['timestart']);
                $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;
                $map['starttime'] = array('egt', $starttime);
                $map['endtime'] = array('elt', $endtime);
            } elseif (isset($_REQUEST['timestart'])) {
                $starttime = strtotime($_REQUEST['timestart']);
                $map['starttime'] = array('egt', $starttime);
            } elseif (isset($_REQUEST['timeend'])) {
                $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;
                $map['endtime'] = array('elt', $endtime);

            }

            if (isset($_REQUEST['start']) && $_REQUEST['end'] != '') {
                $starttime = strtotime($_REQUEST['start']);
                $endtime = strtotime($_REQUEST['end']) + 24 * 3600 - 1;
                $map['create_time'] = array('BETWEEN', array($starttime, $endtime));
            } elseif (isset($_REQUEST['start'])) {
                $starttime = strtotime($_REQUEST['start']);
                $map['create_time'] = array('BETWEEN', array($starttime, time()));
            } elseif (isset($_REQUEST['end'])) {
                $endtime = strtotime($_REQUEST['end']) + 24 * 3600 - 1;
                $map['create_time'] = array('LT', $endtime);
            }

            if (isset($_REQUEST['developers_id'])) {
                $map['developers'] = $_REQUEST['developers_id'];
            } else {
                $map['developers'] = array('neq', 0);
            }

            $data = M('TotalSettlement', 'tab_')->where($map)->order('create_time desc')->page($page, $row)->select();
            $count = M('TotalSettlement', 'tab_')->where($map)->order('create_time desc')->count();

            $page = set_pagination($count, $row);
            if ($page) {
                $this->assign('_page', $page);
            }

            $this->assign('data', $data);
            $this->assign('meta_title', '开发者结算记录');
            $this->display();
        } else {
            $this->meta_title = '开发者结算列表';
            $this->display();
        }
    }

    public function generatesettlementAll()
    {
        $request = I('request.ids');

        if (empty($request)) {
            $this->error('请选择要操作的数据');
        }
        if (is_array($request)) {
            foreach ($request as $k => $v) {
                $query = explode(',', $v);
                $ids[] = $k;
                $_REQUEST[$k]['cooperation'] = $query[0];
                $_REQUEST[$k]['cps_ratio'] = $query[1];
                $_REQUEST[$k]['cpa_price'] = $query[2];
                $_REQUEST[$k]['unum'] = $query[3];
                $_REQUEST[$k]['spay_amount'] = $query[4];
                $_REQUEST[$k]['game_id'] = $query[5];
            }
            unset($_REQUEST['ids']);
        } elseif (is_numeric($request)) {
            $id = $ids[] = $request;
            $_REQUEST[$id]['ids'] = $id;
            $_REQUEST[$id]['cooperation'] = $_REQUEST['cooperation'];
            $_REQUEST[$id]['cps_ratio'] = $_REQUEST['cps_ratio'];
            $_REQUEST[$id]['cpa_price'] = $_REQUEST['cpa_price'];
            $_REQUEST[$id]['unum'] = $_REQUEST['unum'];
            $_REQUEST[$id]['spay_amount'] = $_REQUEST['spay_amount'];
        } else {
            $this->error('参数有误!!!');
        }
        sort(array_unique($ids));
        if (is_array($ids)) {
            $promote_id = get_promote_id($_REQUEST['promote_account']);
            $create_time = time();
            foreach ($ids as $k => $v) {
                if (get_settlement($_REQUEST['timestart'], $_REQUEST['timeend'], $promote_id, $_REQUEST[$v]['game_id'])) {
                    continue;
                }

                $data[$k]['game_id'] = $_REQUEST[$v]['game_id'];
                $data[$k]['game_name'] = get_game_name($_REQUEST[$v]['game_id']);
                $data[$k]['promote_account'] = $_REQUEST['promote_account'];
                $data[$k]['promote_id'] = $promote_id;
                $data[$k]['total_money'] = $_REQUEST[$v]['spay_amount'];
                $data[$k]['total_number'] = $_REQUEST[$v]['unum'];
                $data[$k]['starttime'] = strtotime($_REQUEST['timestart']);
                $data[$k]['endtime'] = strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1;
                $data[$k]['pattern'] = $_REQUEST[$v]['cooperation'] == 'CPS' ? 0 : 1;
                $data[$k]['ratio'] = $_REQUEST[$v]['cps_ratio'];
                $data[$k]['money'] = $_REQUEST[$v]['cpa_price'];
                $data[$k]['create_time'] = $create_time;
                $data[$k]['bind_coin_status'] = $_REQUEST['bind_coin'];
                $data[$k]['settlement_number'] = 'JS-' . date('Ymd') . date('His') . sp_random_string(4);

                if (get_settlement($data[$k]['starttime'], $data[$k]['endtime'], $data[$k]['promote_id'], $data[$k]['game_id'])) {
                    $this->error('该结算周期不可结算,请重新选择');
                }
                if ($data[$k]['pattern']) {
                    $data[$k]['sum_money'] = $data[$k]['total_number'] * $data[$k]['money'];
                } else {
                    $data[$k]['sum_money'] = $data[$k]['total_money'] * $data[$k]['ratio'] / 100;
                }
                if ($data[$k]['game_id'] == '' || $data[$k]['promote_id'] == '' || $data[$k]['starttime'] == '' || $data[$k]['endtime'] == '') {
                    $this->error('必要参数不存在');
                }

                $map['fgame_id'] = $data[$k]['game_id'];
                // $map['is_check']=1;
                $map['puid'] = 0;
                $map['register_time'] = array('BETWEEN', array($data[$k]['starttime'], $data[$k]['endtime']));
                $allid = get_subordinate_promote_($data[$k]['promote_account']);
                $allid[] = $data[$k]['promote_account'];
                $map['promote_account'] = array('in', $allid);
                $u = M('User', 'tab_');
                $user = $u->where($map)->setField('settle_check', 1);
                unset($map['register_time']);
                unset($map['puid']);
                $map['pay_status'] = 1;
                $map['pay_time'] = array('BETWEEN', array($data[$k]['starttime'], $data[$k]['endtime']));
                $s = M('spend', 'tab_');
                $spend = $s->where($map)->setField('settle_check', 1);
            }
        }
        $data = array_values($data);
        $result = M('settlement', 'tab_')->addAll($data);
        if ($result) {
            $settMap['promote_id'] = $promote_id;
            $settMap['starttime'] = strtotime($_REQUEST['timestart']);
            $settMap['endtime'] = strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1;
            $settMap['create_time'] = $data[0]['create_time'];
            $settMap['bind_coin_status'] = $_REQUEST['bind_coin'];
            $dataSett = M('settlement', 'tab_')->field(array(
                'settlement_number',
                'starttime', 'endtime',
                'promote_id', 'promote_account',
                'sum(total_money) as total_money',
                'sum(total_number) as total_number',
                'sum(sum_money) as sum_money',
                'status',
                'ti_status',
                'bind_coin_status',
                'create_time'))->where($settMap)
                ->group('promote_id,starttime,endtime,create_time,bind_coin_status')
                ->order('create_time desc')
                ->select();
            M('TotalSettlement', 'tab_')->addAll($dataSett);
            $this->success('结算成功', U('Query/settlement', array('group' => 2)));
        } else {

            /*if (is_array($ids)) {
                $promote_id  = get_promote_id($_REQUEST['promote_account']);
                foreach ($ids as $k => $v) {
                    if(get_settlement($_REQUEST['timestart'],$_REQUEST['timeend'],$promote_id,$_REQUEST[$v]['game_id'])){
                        continue;
                    }

                    $errorStartTime = strtotime($_REQUEST['timestart']);
                    $errorEndTime = strtotime($_REQUEST['timeend'])+24*60*60-1;

                    $game_id = $_REQUEST[$v]['game_id'];

                    $map['fgame_id']=$game_id;
                    $map['register_time']=array('BETWEEN',array($errorStartTime,$errorEndTime));
                    $map['promote_id']=array('in',$promote_id);
                    $u=M('User','tab_');
                    $user=$u->where($map)->setField('settle_check',0);
                    unset($map['register_time']);
                    $map['pay_time']=array('BETWEEN',array($errorStartTime,$errorEndTime));
                    $s=M('spend','tab_');
                    $spend=$s->where($map)->setField('settle_check',0);
                }
            }*/


            $this->error('结算失败');
        }
    }

    public function generatesettlement()
    {
        //批量结算要加判断
        $data['game_id'] = $_REQUEST['game_id'];
        $data['game_name'] = get_game_name($_REQUEST['game_id']);
        $data['promote_id'] = $_REQUEST['promote_id'];
        $data['promote_account'] = get_promote_name($_REQUEST['promote_id']);
        $data['total_money'] = $_REQUEST['spay_amount'];
        $data['total_number'] = $_REQUEST['unum'];
        $data['starttime'] = strtotime($_REQUEST['starttime']);
        $data['endtime'] = strtotime($_REQUEST['endtime']) + 24 * 60 * 60 - 1;
        $data['pattern'] = $_REQUEST['cooperation'] == 'CPS' ? 0 : 1;
        $data['ratio'] = $_REQUEST['cps_ratio'];
        $data['money'] = $_REQUEST['cpa_price'];
        $data['create_time'] = time();
        $data['settlement_number'] = 'JS-' . date('Ymd') . date('His') . sp_random_string(4);
        if (get_settlement($data['starttime'], $data['promote_id'], $data['game_id'])) {
            $this->error('该结算周期不可结算,请重新选择');
        }
        if ($data['pattern']) {
            $data['sum_money'] = $data['total_number'] * $data['money'];
        } else {
            $data['sum_money'] = $data['total_money'] * $data['ratio'] / 100;
        }
        if ($data['game_id'] == '' || $data['promote_id'] == '' || $data['starttime'] == '' || $data['endtime'] == '') {
            $this->error('必要参数不存在');
        }
        $map['fgame_id'] = $data['game_id'];
        // $map['is_check']=1;
        $map['register_time'] = array('BETWEEN', array($data['starttime'], $data['endtime']));
        $allid = get_subordinate_promote_($data['promote_account']);
        $allid[] = $data['promote_account'];
        $map['promote_id'] = array('in', $data['promote_id']);
        $u = M('User', 'tab_');
        $user = $u->where($map)->setField('settle_check', 1);
        unset($map['register_time']);
        $map['pay_time'] = array('BETWEEN', array($data['starttime'], $data['endtime']));
        $s = M('spend', 'tab_');
        $spend = $s->where($map)->setField('settle_check', 1);
        $result = M('settlement', 'tab_')->add($data);
        if ($result) {
            $this->success('结算成功');
        } else {
            $this->error('结算失败');
        }
    }

    public function generatecpsettlement()
    {//cp结算

        $request = I('request.ids');
        if (empty($request)) {
            $this->error('请选择要操作的数据');
        }
        $starttime = strtotime($_REQUEST['timestart']);
        $endtime = strtotime($_REQUEST['endtime']) + 24 * 3600 - 1;
        $map['s.pay_status'] = 1;
        $map['s.selle_status'] = 0;
        foreach ($request as $key => $value) {
            $query = explode(',', $value);

            $ids[] = $query[0];
            $requestData[$key]['game_id'] = $query[0];
            $requestData[$key]['selle_ratio'] = $query[1];
            $requestData[$key]['total'] = $query[2];
        }

        $map['s.game_id'] = array('in', $ids);
        $map['pay_time'] = array('BETWEEN', array($starttime, $endtime));
        $spe = M('spend as s', 'tab_');
        $smap = array('s.selle_time' => date('Y-m-d', time()), 's.selle_status' => 1);
        $data = $spe
            ->field('s.id,s.selle_status,s.selle_time')
            ->join('tab_game as g on g.id=s.game_id', 'LEFT')
            ->where($map)
            ->setField($smap);
        if ($data) {
            $create_time = time();
            foreach ($requestData as $key => $value) {
                $datas[$key]['game_id'] = $value['game_id'];
                $datas[$key]['game_name'] = get_game_name($value['game_id']);
                $datas[$key]['promote_id'] = '0';
                $datas[$key]['promote_account'] = '0';
                $datas[$key]['total_money'] = $value['total'];
                $datas[$key]['total_number'] = 0;
                $datas[$key]['starttime'] = $starttime;
                $datas[$key]['endtime'] = $endtime;
                $datas[$key]['pattern'] = 0;//$_REQUEST['cooperation']=='CPS'?0:1;
                $datas[$key]['ratio'] = $value['selle_ratio'];
                $datas[$key]['sum_money'] = $value['selle_ratio'] * $value['total'] / 100;
                $datas[$key]['money'] = 0;
                $datas[$key]['developers'] = $_REQUEST['developers_id'];
                $datas[$key]['create_time'] = $create_time;
                $datas[$key]['settlement_number'] = 'JS-' . date('Ymd') . date('His') . sp_random_string(4);
                $datas[$key]['bind_coin_status'] = $_REQUEST['bind_coin'];
            }
            $datas = array_values($datas);
            $result = M('settlement', 'tab_')->addAll($datas);
            $settMap['developers'] = $_REQUEST['developers_id'];
            $settMap['starttime'] = $starttime;
            $settMap['endtime'] = $endtime;
            $settMap['create_time'] = $create_time;
            $dataSett = M('settlement', 'tab_')->field(array(
                'settlement_number',
                'starttime', 'endtime',
                'promote_id', 'promote_account',
                'sum(total_money) as total_money',
                'sum(total_number) as total_number',
                'sum(sum_money) as sum_money',
                'status',
                'ti_status',
                'bind_coin_status',
                'developers',
                'create_time',))->where($settMap)
                ->group('developers,starttime,endtime,create_time,bind_coin_status')
                ->order('create_time desc')
                ->select();
            M('TotalSettlement', 'tab_')->addAll($dataSett);
            \Think\Log::actionLog('Query/generatecpsettlement', 'Query', 1);
            $this->success('结算成功', U('Query/cpsettlement', array('group' => 2)));
        } else {
            $this->error('结算失败');
        }
        $map1 = array('status' => 1, 'selle_status' => 1);
        $total = null_to_0(D('spend')->where($map1)->sum('pay_amount'));
        $ttotal = null_to_0(D('spend')->where('pay_time' . total(1))->where($map1)->sum('pay_amount'));
        $ytotal = null_to_0(D('spend')->where('pay_time' . total(5))->where($map1)->sum('pay_amount'));
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);

    }

    public function changeratio()
    {
        $gid = I('request.game_id');
        if (empty($gid)) {
            $this->ajaxReturn(0, "请选择要操作的数据", 0);
            exit;
        }
        $starttime = strtotime($_REQUEST['timestart'] . '-01');
        $endtime = strtotime($_REQUEST['timestart'] . "+1 month -1 day") + 24 * 3600 - 1;
        $map['s.pay_status'] = 1;
        $map['s.selle_status'] = 0;
        $map['s.game_id'] = $_REQUEST['game_id'];
        $map['pay_time'] = array('BETWEEN', array($starttime, $endtime));
        $spe = M('spend as s', 'tab_');
        $data = $spe
            ->field('s.id,s.selle_status,s.selle_ratio')
            ->join('tab_game as g on g.id=s.game_id', 'LEFT')
            ->where($map)
            ->setField('s.selle_ratio', $_POST['ratio']);
        if ($data === false) {
            $this->ajaxReturn(array('status' => 0));
        } else {
            $this->ajaxReturn(['status' => 1, 'data' => $data]);
        }
    }

    public function cp_withdraw($p = 0)
    {
        if (isset($_REQUEST['settlement_number'])) {
            $map['settlement_number'] = array('like', '%' . $_REQUEST['settlement_number'] . '%');
        }
        if (isset($_REQUEST['status'])) {
            $map['status'] = $_REQUEST['status'];
        }
        if (isset($_REQUEST['developers'])) {
            if ($_REQUEST['developers'] == '全部') {
                unset($_REQUEST['developers']);
            } else {
                $map['developers'] = $_REQUEST['developers'];
            }
        } else {
            $map['developers'] = array('neq', 0);

        }

        if (isset($_REQUEST['timestart']) && isset($_REQUEST['timeend'])) {
            $starttime = strtotime($_REQUEST['timestart']);
            $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;
            $map['audit_time'] = array('BETWEEN', array($starttime, $endtime));
            unset($_REQUEST['timestart']);
            unset($_REQUEST['timeend']);
        } elseif (isset($_REQUEST['timestart'])) {
            $map['audit_time'] = ['GT', strtotime(I('timestart'))];
            unset($_REQUEST['timestart']);
        } elseif (isset($_REQUEST['timeend'])) {
            $map['audit_time'] = ['LT', strtotime(I('timeend')) + 86399];
            unset($_REQUEST['timeend']);
        }

        if ($_REQUEST['create_time'] == 2) {
            $order = 'create_time desc';
        } elseif ($_REQUEST['create_time'] == 1) {
            $order = 'create_time asc';
        } else {
            $order = 'create_time desc';
        }
        if ($_REQUEST['sum_money'] == 2) {
            $order = 'sum_money desc';
        } elseif ($_REQUEST['sum_money'] == 1) {
            $order = 'sum_money asc';
        }
        $model = array(
            'm_name' => 'withdraw',
            'order' => $order,
            'title' => '渠道提现',
            'template_list' => 'cp_withdraw',
        );
        $map1 = $map;
        $map1['status'] = 1;
        if (isset($_REQUEST['status']) && $_REQUEST['status'] == 0) {
            $total = '0.00';
            $ttotal = '0.00';
            $ytotal = '0.00';
        } else {
            $total = null_to_0(D('withdraw')->where($map1)->sum('sum_money'));
            $ttotal = null_to_0(D('withdraw')->where('audit_time' . total(1))->where($map1)->sum('sum_money'));
            $ytotal = null_to_0(D('withdraw')->where('audit_time' . total(5))->where($map1)->sum('sum_money'));
        }
        $this->assign('stotal', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $user = A('Bill', 'Event');

        $this->m_title = '开发者提现';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/cp_withdraw', 'status' => 1])->find());


        $user->money_list($model, $p, $map);
    }

    public function withdraw()
    {
        $page = I('p', 1);
        $row = I('row', 10);
        $reviewTypeList = WithdrawModel::$reviewTypeList;
        $map['_string'] = '1=1';
        $adminid = C('USER_ADMINISTRATOR');//获取超管id
        $adminmobile = M('UcenterMember')->field('mobile')->find($adminid);
        $this->assign('adminmobile', $adminmobile['mobile']);
        if (isset($_REQUEST['widthdraw_number'])) {
            $map['widthdraw_number'] = $_REQUEST['widthdraw_number'];
        }
        if (isset($_REQUEST['ti_status'])) {
            $map['status'] = $_REQUEST['ti_status'];
        }
        if (isset($_REQUEST['op_type'])) {
            $map['op_type'] = $_REQUEST['op_type'];
        }
        if (isset($_REQUEST['settlement_type'])) {
            $map['settlement_type'] = $_REQUEST['settlement_type'];
        }
        if (isset($_REQUEST['review_type'])) {
            $map['review_type'] = $_REQUEST['review_type'];
        }
        if (isset($_REQUEST['promote_account'])) {
            if ($_REQUEST['promote_account'] == '全部') {
                unset($_REQUEST['promote_account']);
            } else {
                $map['promote_account'] = $_REQUEST['promote_account'];
            }
        } else {
            $map['promote_id'] = array('gt', 0);
        }
        if (!empty($_REQUEST['company_id'])) {
            $promoteIds = D('promote')->where(['company_id' => $_REQUEST['company_id']])
                ->getField('id', true);
            $promoteIds = $promoteIds ?? [-1];
            $where['promote_id'] = ['in', $promoteIds];
            $map['_complex'] = $where;
        }

        $order = 'create_time desc';
        if (isset($_REQUEST['data_order'])) {
            $dataOrder = explode(',', $_REQUEST['data_order']);
            if (count($dataOrder) == 2 && in_array($dataOrder[1], ['create_time', 'sum_money'])) {
                if (intval($dataOrder[0]) == 4) {
                    $order = $dataOrder[1] . ' desc';
                } elseif (intval($dataOrder[0]) == 3) {
                    $order = $dataOrder[1] . ' asc';
                }
            }
        }

        $fields = 'id, widthdraw_number, sum_money, promote_id, promote_account, op_id, op_type, last_op_id, last_op_type, settlement_type, settlement_begin_time, settlement_end_time, create_time, status, respond, audit_time, review_type';
        $count = 0;
        if (I('export', 0) == 1) {
            $records = D('withdraw')->field($fields)
                ->where($map)
                ->order($order)
                ->select();
        } else {
            $records = D('withdraw')->field($fields)
                ->where($map)
                ->order($order)
                ->page($page, $row)
                ->select();
            $count = D('withdraw')->field($fields)
                ->where($map)
                ->count();
        }

        $datas = [];
        if (!empty($records)) {
            $promoteIds = array_column($records, 'promote_id');
            $promoteCompanys = D('promote')->join('tab_promote_company as company on tab_promote.company_id = company.id')
                ->where(['tab_promote.id' => ['in', $promoteIds]])
                ->getField('tab_promote.id, company.company_name', true);
            foreach ($records as $record) {
                $record['op_id_text'] = $this->getOpTypeText($record['op_type'], $record['op_id']);
                $record['last_op_id_text'] = $this->getOpTypeText($record['last_op_type'], $record['last_op_id']);
                $record['op_type_text'] = getPromoteWithdrawOpType($record['op_type']);
                $record['last_op_type_text'] = getPromoteWithdrawOpType($record['last_op_type']);
                $record['settlement_type_text'] = getPromoteWithdrawSettlementType($record['settlement_type']);
                $record['company_name'] = isset($promoteCompanys[$record['promote_id']]) ? $promoteCompanys[$record['promote_id']] : '未知';

                $data = [
                    'widthdraw_number' => $record['widthdraw_number'],
                    'sum_money' => $record['sum_money'],
                    'company_name' => $record['company_name'],
                    'promote_account' => $record['promote_account'],
                    'op_id_text' => $this->getOpTypeText($record['op_type'], $record['op_id']),
                    'last_op_id_text' => $this->getOpTypeText($record['last_op_type'], $record['last_op_id']),
                    'op_type_text' => getPromoteWithdrawOpType($record['op_type']),
                    'last_op_type_text' => getPromoteWithdrawOpType($record['last_op_type']),
                    'review_type_text' => $reviewTypeList[$record['review_type']] ?? '未知',
                    'settlement_type_text' => getPromoteWithdrawSettlementType($record['settlement_type']),
                    'settlement_begin_time' => $record['settlement_begin_time'] ? date('Y-m-d H:i:s', $record['settlement_begin_time']) : '--',
                    'settlement_end_time' => date('Y-m-d H:i:s', $record['settlement_end_time']),
                    'create_time' => date('Y-m-d H:i:s', $record['create_time']),
                    'status_text' => promoteWithdrawStatus($record['status']),
                    'respond' => $record['respond'],
                    'audit_time' => $record['audit_time'] ? date('Y-m-d H:i:s', $record['audit_time']) : '--',
                ];
                if (I('export', 0) != 1) {
                    $data['id'] = $record['id'];
                    $data['status'] = $record['status'];
                }
                $datas[] = $data;
            }

            if (I('export', 0) == 1) {
                $field = [
                    'widthdraw_number' => '结算单号',
                    'sum_money' => '结算金额',
                    'company_name' => '推广公司',
                    'promote_account' => '推广员账号',
                    'op_id_text' => '操作人',
                    'op_type_text' => '操作人类型',
                    'last_op_id_text' => '最后操作人',
                    'last_op_type_text' => '最后操作人类型',
                    'review_type_text' => '审核模式',
                    'settlement_type_text' => '提现模式',
                    'settlement_begin_time' => '结算开始时间',
                    'settlement_end_time' => '结算截止时间',
                    'create_time' => '申请时间',
                    'status_text' => '提现状态',
                    'respond' => '说明',
                    'audit_time' => '审核时间',
                ];
                data2csv($datas,"推广结算", $field);
                exit;
            }
        }

        $map1 = array('status' => ['neq', -1]);
        //为数据权限添加
        setPowerPromoteIds($map1);

        $total = null_to_0(D('withdraw')->where($map1)->sum('sum_money'));
        $ttotal = null_to_0(D('withdraw')->where('create_time' . total(1))->where($map1)->sum('sum_money'));
        $ytotal = null_to_0(D('withdraw')->where('create_time' . total(5))->where($map1)->sum('sum_money'));
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);

        $this->m_title = '推广提现';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/withdraw', 'status' => 1])->find());

        $page = set_pagination($count, $row);
        if($page) {
            $this->assign('_page', $page);
        }
        //为数据权限添加
        setPowerPromoteIds($map);
        $companys = getPromoteCompanys();
        $this->assign('companys', $companys);
        $this->assign('reviewTypeList', $reviewTypeList);
        $this->assign('is_admin', is_administrator());
        $this->assign('list_data', $datas);
        $this->display();
    }

    public function getWithdraw()
    {
        $promoteId = intval(I('post.promote_id', 0));
        $beginTime = I('post.begin_time', '');
        $endTime = I('post.end_time', '');
        $msg = '';

        if (empty($promoteId) || empty($beginTime) || empty($endTime)) {
            $this->ajaxReturn(['msg' => $msg]);
        }
        $beginTime = strtotime($beginTime);
        $endTime = strtotime($endTime) + 3600 * 24 - 1;

        $map['promote_id'] = $promoteId;
        $map['settlement_end_time'] = ['between', [$beginTime, $endTime]];
        $map['status'] = ['neq', -2];

        $withdraws = D('withdraw')->field('id, settlement_begin_time, settlement_end_time')
            ->where($map)
            ->select();
        if (!empty($withdraws)) {
            foreach ($withdraws as $withdraw) {
                $settlementEndTime = date('Y-m-d', $withdraw['settlement_end_time'] + 1);
                if ($withdraw['settlement_begin_time'] > 0) {
                    $settlementBeginTime = date('Y-m-d', $withdraw['settlement_begin_time']);
                    $msg .= "{$settlementBeginTime}至{$settlementEndTime}之间的订单已经提现;";
                } else {
                    $msg .= "{$settlementEndTime}之前的订单已经提现;";
                }
                $msg .= '<br>';
            }
        }

        $this->ajaxReturn(['msg' => $msg]);
    }

    public function set_withdraw_status($status = 1)
    {
        $withdraw = M('withdraw', "tab_");
        $ids = I('ids', 0);
        if (empty($ids)) {
            $this->error('参数异常');
        }
        if (is_array($ids)) {
            $map['id'] = ['in', $ids];
        } else {
            $map['id'] = $ids;
        }
        switch ($status) {
            case 1:
                $map['status'] = 0;
                break;
            case 2:
                $map['status'] = 1;
                break;
        }
        $save['audit_time'] = time();
        $save['status'] = $status;
        $res = $withdraw->where($map)->save($save);
        if ($res) {
            $this->success('操作成功', U('withdraw'));
        } else {
            $this->error('操作失败');
        }
    }

    public function set_withdraw()
    {
        $case = I('case', '');
        if (empty($case)) {
            $data['status'] = 0;
            $data['msg'] = '参数异常';
            $this->ajaxReturn($data);
        }
        switch ($case) {
            case 'deny':
                $data = $this->set_withdraw_deny();
                break;
            case 'upload_transfer_proof':
                $data = $this->set_withdraw_transfer_proof();
                break;
            default:
                $data['status'] = 0;
                $data['msg'] = '参数异常';
                break;
        }
        $this->ajaxReturn($data);
    }

    public function set_withdraw_deny()
    {
        $withdraw = M('withdraw', "tab_");
        $ids = I('ids', 0);
        $respond = I('respond', '');
        $status = -1;
        if (empty($ids)) {
            $data['status'] = 0;
            $data['msg'] = '参数异常';
            return $data;
        }
        if (empty($respond)) {
            $data['status'] = 0;
            $data['msg'] = '请填写驳回说明';
            return $data;
        }
        $idsData = explode(',', $ids);
        if (is_array($ids) || (is_array($idsData) && count($idsData) > 1)) {
            $map['id'] = ['in', $ids];
        } else {
            $map['id'] = $ids;
        }
        $map['status'] = 0;
        $save['audit_time'] = time();
        $save['status'] = $status;
        $save['respond'] = $respond;
        $res = $withdraw->where($map)->save($save);
        if ($res === false) {
            $data['status'] = 0;
            $data['msg'] = '驳回失败';
        } else {
            $data['status'] = 1;
            $data['msg'] = '驳回成功';
        }

        return $data;
    }

    public function set_withdraw_transfer_proof()
    {
        $withdraw = M('withdraw', "tab_");
        $ids = intval(I('ids', 0));
        $transferProof = intval(I('transfer_proof', 0));
        $status = 2;
        if (empty($ids)) {
            $data['status'] = 0;
            $data['msg'] = '参数异常';
            return $data;
        }
        if (empty($transferProof)) {
            $data['status'] = 0;
            $data['msg'] = '请上传汇款证明';
            return $data;
        }
        $downloadId = M('document_download')->where(array('file_id' => $transferProof))->getField('id');
        if (empty($downloadId)) {
            $fileData = M('File')->field('size,ext')->find($transferProof);
            $downloadSave['content'] = '推广员提现订单汇款证明';
            $downloadSave['file_id'] = $transferProof;
            $downloadSave['size'] = $fileData['size'];
            $downloadRes = M('document_download')->add($downloadSave);
            if (!$downloadRes) {
                $data['status'] = 0;
                $data['msg'] = '保存失败';
                return $data;
            }
            $downloadId = $downloadRes;
        }
        $map['id'] = $ids;
        $map['status'] = 1;
        $save['audit_time'] = time();
        $save['status'] = $status;
        $save['transfer_proof'] = $downloadId;
        $res = $withdraw->where($map)->save($save);
        if ($res === false) {
            $data['status'] = 0;
            $data['msg'] = '保存失败';
        } else {
            $data['status'] = 1;
            $data['msg'] = '保存成功';
        }

        return $data;
    }

    private function set_total_settlement_ti_status($settlement_number)
    {
        $totalSettlementMap['settlement_number'] = $settlement_number;
        $totalSettlement = M('TotalSettlement', 'tab_');
        $totalSettlement->where($totalSettlementMap)->save(array("ti_status" => $_REQUEST['status']));
        $dataTotalSettlement = $totalSettlement->where($totalSettlementMap)->find();
        $settMap['promote_id'] = $dataTotalSettlement['promote_id'];
        $settMap['starttime'] = $dataTotalSettlement['starttime'];
        $settMap['endtime'] = $dataTotalSettlement['endtime'];
        $settMap['create_time'] = $dataTotalSettlement['create_time'];
        M("settlement", "tab_")->where($settMap)->save(array('ti_status' => $_REQUEST['status']));
    }


    protected function upPromote($promote_id)
    {
        $model = D('Promote');
        $data['id'] = $promote_id;
        $data['money'] = 0;
        return $model->save($data);
    }

    public function details($promote_id = 0, $create_time = 0)
    {
        $map['promote_id'] = $promote_id;
        $map['create_time'] = $create_time;
        $data = M('settlement', 'tab_')->where($map)->select();
        $total = M('settlement', 'tab_')->where($map)->sum('sum_money');
        $this->assign('total', $total);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function detailscps($developers_id = 0, $create_time = 0, $p = 0)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = !empty(C('ADMIN_LIST_ROW')) ? C('ADMIN_LIST_ROW') : 10;
        $map['developers_id'] = $developers_id;
        $map['create_time'] = $create_time;
        $data = M('settlement', 'tab_')->where($map)->page($page, $row)->select();
        $count = M('settlement', 'tab_')->where($map)->count();
        if ($count > $row) {
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
        $total = M('settlement', 'tab_')->where($map)->sum('sum_money');
        $this->assign('total', $total);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function withdrawDetails($id)
    {
        $withdrawId = intval($id);
        $withdraw = D('withdraw')->find($withdrawId);
        $records = [];
        if (!empty($withdraw) && !empty($withdraw['game_ratio'])) {
            $gameRatios = json_decode($withdraw['game_ratio'], true);
            foreach ($gameRatios as $gameId => $gameRatio) {
                $gameName = D('game')->where(array('id' => $gameId))->getField('game_name');
                foreach ($gameRatio as $list) {
                    $list['selle_ratio'] = $list['selle_ratio'] ?? '0.00';
                    $records[] = [
                        'settlement_time' => "{$list['begin_time']} - {$list['end_time']}",
                        'game_name' => $gameName ?? '未知',
                        'sum_amount' => $list['sum_amount'],
                        'default_ratio' => $list['default_ratio'] ?  $list['default_ratio'] . '%' : '未知',
                        'ratio' => $list['selle_ratio'] . '%',
                        'settlement_amount' => bcdiv(bcmul($list['sum_amount'], $list['selle_ratio'], 2), 100, 2),
                    ];
                }
            }
        }

        $this->assign('settlementType', $withdraw['settlement_type']);
        $this->assign('records', $records);
        $this->display();
    }

    /**
     * 审核推广提现
     * @author <jszsl001@163.com>
     */

    public function set_withdraw_agree()
    {
        //行为日志判断
        if (I('status') == 1 && I('msg_type') == 5 && I('field') == 'status') {
            //同意推广提现
            action_log('tg_tx_agree', 'withdraw', UID, UID);
        }
        if (I('status') == 2 && I('msg_type') == 6 && I('field') == 'status') {
            //拒绝推广提现
            action_log('tg_tx_disagree', 'withdraw', UID, UID);
        }

        //判断打款类型
        if (I('withdraw_type', 0, 'intval') == 1) {
            //手动打款,直接就改状态
            $this->set_withdraw_status();
        } else {
            $adminid = C('USER_ADMINISTRATOR');//获取超管id
            $adminmobile = M('UcenterMember')->field('mobile')->find($adminid);

            $dx = A('Phone');
            $res = -1;
            $res = $dx->check_tel_code($adminmobile['mobile'], $_POST['code']);
            switch ($res) {
                case '-1':
                    $this->error('短信验证码无效,请重新获取');
                    break;
                case '-2':
                    $this->error('时间超时,请重新获取短信验证码');
                    break;
                case '-3':
                    $this->error('短信验证码不正确,请重新输入');
                    break;
            }
            $withdraw = M('withdraw', "tab_");
            $pay = new \Think\Pay('alipay', C('alipay'));
            $withdraw_way = $_POST['withdraw_way'];
            //支付宝
            if ($withdraw_way == 1) {
                $map['id'] = $_POST['ids'];
                $dind = $withdraw->where($map)->find();
                if ($dind['status'] == 1) {
                    $this->ajaxReturn(['status' => -1, 'info' => '请不要重复打款']);
                }
                $widthdrawNo = "TX_" . date('Ymd') . date('His') . sp_random_string(4);
                $vo = new \Think\Pay\PayVo();
                $vo->setOrderNo($dind['settlement_number'])
                    ->setBatchNo($widthdrawNo)
                    ->setTable('Withdraw')
                    ->setPayMethod("transfer")
                    ->setDetailData('渠道结算提现,订单' . $dind["settlement_number"]);
                $res = $pay->buildRequestForm($vo);
                if ($res == 10000) {
                    $this->ajaxReturn(['status' => 1, 'info' => '打款成功']);
                } else {
                    $this->ajaxReturn(['status' => 0, 'info' => '打款失败']);
                }
            }

        }
    }

    public function marketList($p=1) {

        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $arraypage = $page;

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $map = [];
//        setPowerPromoteIds($map,'root_id');

        if ($_REQUEST['promote_id']||$_REQUEST['promote_id']=='0') {
            if ($_REQUEST['promote_id']=='0') {
                unset($map['root_id']);
                $map['promote_account'] = '官方渠道';
            } else {
                $map['root_id'] = $_REQUEST['promote_id'];
            }
        }

        if ($_REQUEST['game_name']) {
            $map['game_names'] = $_REQUEST['game_name'];
        }

        if ($_REQUEST['count_date']) {
            $map['my_time'] = $_REQUEST['count_date'];
        }

        if ($_REQUEST['device']) {
//            $map['tab_spend.sdk_version'] = $_REQUEST['device'];
            $spendMap['tab_spend.sdk_version'] = $_REQUEST['device'];

        }
        $spendMap['tab_spend.pay_status'] = 1;
        //获取spend表中的数据,同时根据会长id进行group分类
        $data = M('Spend','tab_')
            ->field("FROM_UNIXTIME(pay_time,'%Y-%m') as my_time,sum(pay_amount) as pay_amount,game_id,tab_spend.game_name,SUBSTRING_INDEX(tab_spend.`game_name`,\"(\",1) as game_names,promote_id,promote_account,company_relation,company_belong,CASE WHEN SUBSTRING_INDEX(SUBSTRING_INDEX(`chain`,\"/\",2),\"/\",-1)='' THEN promote_id ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(`chain`,\"/\",2),\"/\",-1) END as root_id,tab_game.ratio,tab_game.relation_game_id ")
            ->join("left join tab_promote on promote_id = tab_promote.id")
            ->join("left join tab_game on tab_game.id=tab_spend.game_id")
            ->where($spendMap)
            ->group("my_time,game_names,root_id")
            ->order("my_time Desc")
            ->select(false);


        $count = M()->table('('.$data.') as a')
            ->field("my_time,pay_amount,game_id,game_names,promote_id,promote_account,a.company_relation,a.company_belong,CASE WHEN root_id is null THEN 0 ELSE root_id END as root_id,CASE WHEN account is null THEN '官方渠道' ELSE account END as account")
            ->join("left join tab_promote on root_id = tab_promote.id")
            ->group("my_time,game_names,root_id")
            ->where($map)
            ->order("my_time Desc")
            ->select(false);

        //关联表获取会长账号名
        $data = M()->table('('.$data.') as a')
            ->field("my_time,pay_amount,a.game_id,game_name,game_names,a.promote_id,a.promote_account,a.company_relation,a.company_belong,CASE WHEN root_id is null THEN 0 ELSE root_id END as root_id,CASE WHEN account is null THEN '官方渠道' ELSE account END as account,tab_ratio.ratio as ratio,turnover_ratio,a.ratio as game_ratio")
            ->join("left join tab_promote on root_id = tab_promote.id")
            ->join("left join tab_promote_game_ratio as tab_ratio on tab_ratio.game_id = a.relation_game_id and tab_ratio.promote_id=root_id")
//            ->join("left join tab_cp_game_ratio as game_ratio on game_ratio.game_id = a.game_id")
            ->page($page,$row)
            ->where($map)
            ->group("my_time,game_names,root_id")
            ->order("my_time Desc")
            ->select();
//        var_dump($data);die();

//        dump($data);die();

        $pagecount = M()->table('('.$count.') as a')->count();

        foreach($data as $key => $value) {
             $mytime = $value['my_time'];
             $nextMonth = date('Y-m',strtotime("$mytime + 1 month"));
             $game_id = $value['game_id'];
             $gameInfo = M('game','tab_')->where(['id'=>$game_id])->getField('game_name');
             $gameName = substr($gameInfo,0,strpos($gameInfo,'('));
             $gameMap['game_name'] = ['like','%'.$gameName.'%'];
             $gameIdArr = M('game','tab_')->field('id')->where($gameMap)->select();
             $gameNameIdArr = [];
             foreach($gameIdArr as $gameKey => $gameValue){
                 $gameNameIdArr[] = $gameValue['id'];
             }
             $promote_id = $value['promote_id'];
             $pay_status = 1;
             $promoteInfo = M('promote','tab_')->where(['id'=>$promote_id])->find();
             $level = $promoteInfo['level'];
             if($promote_id != 0) {
                $promoteIdArr = [];
                if ($level == 1) {
                    $rootPromoteId = $promote_id;
                    $promoteIdArr[] = $promote_id;
                }else {
                    $chain = $promoteInfo['chain'];
                    $chainArr = explode('/',$chain);
                    $rootPromoteId = $chainArr[1];
                }
                $where1['chain'] =  array('like', '%/' . $rootPromoteId. '/%');  
                $promoteIdInfo = M('promote','tab_')->field('id')->where($where1)->select();
                foreach($promoteIdInfo as $key2 => $v1) {
                   $promoteIdArr[] = $v1['id'];
                }
                $map['promote_id'] = ['in',$promoteIdArr];
             }else {
                $map['promote_id'] = 0;
             }
            
             
             $where['game_id'] = ['in',$gameNameIdArr];
             $where['pay_status'] = 1;
             $begTime = strtotime($mytime);
             $endTime = strtotime($nextMonth);
             $where['pay_time'] = ['between',[$begTime,$endTime]];
             $spendInfo = M('spend','tab_')->field('pay_amount,pay_way')->where($where)->select();
             $initNum = 0;
             foreach($spendInfo as $key1 => $spendValue) {
                 $pay_way = $spendValue['pay_way'];
                 $channel_rate = $this->getChannelConfig($pay_way) / 100;
                 $initNum += $spendValue['pay_amount'] * $channel_rate;

             }
             $data[$key]['pay_amount'] = $value['pay_amount'] - $initNum;
//            if ($value['games_ratio']) {
//                $data[$key]['upstream'] = $value['pay_amount'] * ($value['games_ratio']*0.01);
//            } else {
                $data[$key]['upstream'] = caculateUpstream($value['game_id'],$value['pay_amount']);
//            }

            if ($value['ratio']) {
                $data[$key]['downstream'] = $value['pay_amount'] * ($value['ratio']*0.01);
            } else {
                $data[$key]['downstream'] = $value['pay_amount'] * ($value['game_ratio']*0.01);
            }

            $value['turnover_ratio'] = json_decode($value['turnover_ratio'],true);

//            dd($value);

            if (is_array($value['turnover_ratio'])) {
                foreach($value['turnover_ratio'] as $k =>$v) {
                    if($value['pay_amount']>$v['turnover']) {
                        $data[$key]['downstream'] = $value['pay_amount'] * ($v['ratio']*0.01);
                    }
                }
            }

            $data[$key]['highquality'] = number_format(($value['pay_amount']-$data[$key]['upstream']-$data[$key]['downstream']) * (1-0.0672),2,'.','');

            $data[$key]['company_belong'] = $data[$key]['company_belong']?'外团':'内团';
            $data[$key]['company_relation'] = $data[$key]['company_relation']?'只维护':'自主开发及维护';

        }

        $page = set_pagination($pagecount, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->meta_title = '市场结算管理';
        $this->assign('data',$data);

        $this->display();
    }

    public function getChannelStream() {

        $map = [];
//        setPowerPromoteIds($map,'root_id');

        if ($_REQUEST['promote_id']||$_REQUEST['promote_id']=='0') {
            if ($_REQUEST['promote_id']=='0') {
                unset($map['root_id']);
                $map['promote_account'] = '官方渠道';
            } else {
                $map['root_id'] = $_REQUEST['promote_id'];
            }
        }

        if ($_REQUEST['game_name']) {
            $map['game_names'] = $_REQUEST['game_name'];
        }

        if ($_REQUEST['count_date']) {
            $map['my_time'] = $_REQUEST['count_date'];
        }

//        if ($_REQUEST['device']) {
//            $map['game_name'] = ['like','%'.$_REQUEST['device'].'%'];
//        }

        if ($_REQUEST['device']) {
//            $map['tab_spend.sdk_version'] = $_REQUEST['device'];
            $spendMap['tab_spend.sdk_version'] = $_REQUEST['device'];

        }
        $spendMap['tab_spend.pay_status'] = 1;

        //获取spend表中的数据,同时根据会长id进行group分类
        $data = M('Spend','tab_')
            ->field("FROM_UNIXTIME(pay_time,'%Y-%m') as my_time,sum(pay_amount) as pay_amount,game_id,game_name,SUBSTRING_INDEX(`game_name`,\"(\",1) as game_names,promote_id,promote_account,company_relation,company_belong,CASE WHEN SUBSTRING_INDEX(SUBSTRING_INDEX(`chain`,\"/\",2),\"/\",-1)='' THEN promote_id ELSE SUBSTRING_INDEX(SUBSTRING_INDEX(`chain`,\"/\",2),\"/\",-1) END as root_id,pay_way ")
            ->join("left join tab_promote on promote_id = tab_promote.id")
            ->where($spendMap)
            ->group("my_time,game_names,root_id,pay_way")
            ->order("my_time Desc")
            ->select(false);

        //关联表获取会长账号名
        $data = M()->table('('.$data.') as a')
            ->field("pay_amount,a.pay_way")
            ->join("left join tab_promote on root_id = tab_promote.id")
            ->join("left join tab_promote_game_ratio as tab_ratio on tab_ratio.game_id = a.game_id and tab_ratio.promote_id=root_id")
            ->where($map)
            ->group("my_time,game_names,root_id,pay_way")
            ->order("my_time Desc")
            ->select();

        $returnData = '';

        foreach($data as $key => $value) {

            $returnData .=get_pay_way($value['pay_way']).':'.$value['pay_amount']."<br />";


        }
//        echo $returnData;die();
        $this->ajaxReturn($returnData);

    }

    public function getPromoteSettlementType()
    {
        $promoteId = intval(I('post.promote_id', 0));
        $settlementType = [];
        if ($promoteId > 0) {
            $promote = D('promote')->field('level, settlement_type')->where(array('id' => $promoteId))->find();
            if (empty($promote) || $promote['level'] != 1 || empty($promote['settlement_type'])) {
                $settlementType = [];
            } else {
                $settlementType = WithdrawModel::$settlementTypeList;
                unset($settlementType[WithdrawModel::SETTLEMENT_TYPE_OTHER]);
                if ($promote['settlement_type'] == 1) {
                    unset($settlementType[WithdrawModel::SETTLEMENT_TYPE_MONTH]);
                } else {
                    unset($settlementType[WithdrawModel::SETTLEMENT_TYPE_WEEK]);
                    unset($settlementType[WithdrawModel::SETTLEMENT_TYPE_RECOUP]);
                }
            }
        }

        $this->ajaxReturn(['settlement_type' => $settlementType]);
    }

    public function getAmountBySettlementType()
    {
        $withdrawModel = new WithdrawModel();
        $promoteId = intval(I('promote_id', 0));
        $settlementType = intval(I('settlement_type', 0));
        $time = I('time', '');

        if (empty($promoteId) || !in_array($settlementType, [2, 3])) {
            $this->ajaxReturn(['balance' => 0]);
        }

        $promote = M('promote', 'tab_')->find($promoteId);
        if (empty($promote) || $promote['level'] != 1 || $promote['ver_status'] != 1 || empty($time)) {
            $this->ajaxReturn(['balance' => 0]);
        }

        $data['begin_time'] = strtotime($time);
        $data['end_time'] = strtotime('+1 month', $data['begin_time']) - 1;

        if ($settlementType == 2) {
            $balance = $withdrawModel->getMonthAmount($promote, $data);
        } else {
            $balance = $withdrawModel->getRecoupAmount($promote, $data);
        }
        $this->ajaxReturn(['balance' => $balance]);
    }

    public function autoReview($autoStatus = 0)
    {
        if ($_POST) {
            $promoteIds = I('ids', '');
            $autoStatus = intval($autoStatus);
            if (empty($promoteIds)) {
                $this->error('请选择需要操作的数据');
            }
            if (!in_array($autoStatus, [0, 1])) {
                $this->error('参数错误');
            }

            $map['id'] = ['in', $promoteIds];
            $time = time();
            $save['auto_review_withdraw_status'] = $autoStatus;
            $save['auto_review_withdraw_updated_time'] = $time;

            $result = D('promote')->where($map)->save($save);
            if ($result === false) {
                $this->error('操作失败');
            } else {
                $this->success('操作成功');
            }
        } else {
            $page = intval(I('p', 1));
            $row = intval(I('row', 10));
            $companyId = intval(I('company_id', 0));
            $promoteId = intval(I('promote_id', 0));
            $autoReviewWithdrawStatus = I('status', '');

            if ($companyId > 0) {
                $map['company_id'] =$companyId;
            }
            if ($promoteId > 0) {
                $map['id'] =$promoteId;
            }
            if ($autoReviewWithdrawStatus !== '') {
                $map['auto_review_withdraw_status'] = $autoReviewWithdrawStatus;
            }
            $map['level'] = 1;
            $field = 'id, account, company_id, auto_review_withdraw_status';
            $promotes = D('promote')->field($field)
                ->where($map)
                ->order('auto_review_withdraw_updated_time desc')
                ->page($page, $row)
                ->select();
            $count = D('promote')->field($field)
                ->where($map)
                ->count();

            $companys = getPromoteCompanys();
            $companyList = array_column($companys, 'company_name', 'id');
            $promoteList = (new PromoteModel())->getPromotersByLevel();

            $records = [];
            if (!empty($promotes)) {
                foreach ($promotes as $promote) {
                    $promote['company_name'] = ($companyList[$promote['company_id']] ? $companyList[$promote['company_id']] : ($promote['company_id'] == 0 ? '万盟天下科技' : '未知'));
                    if ($promote['auto_review_withdraw_status'] == 0) {
                        $className = 'auto-closed';
                        $text = '关闭';
                    } else {
                        $className = 'auto-open';
                        $text = '开启';
                    }
                    $promote['auto_review_withdraw_status_text'] = "<span class='{$className}'>{$text}</span>";
                    $records[] = $promote;
                }
            }

            $page = set_pagination($count, $row);
            if($page) {
                $this->assign('_page', $page);
            }
            $this->assign('meta_title', '推广提现自动审核管理');
            $this->assign('records', $records);
            $this->assign('count', $count);
            $this->assign('companys', $companys);
            $this->assign('promoteList', $promoteList);
            $this->display('auto_review');
        }
    }

    public function getChannelConfig($pay_way = 0,$config=false) {
        if(!$config) {
            $payWayName = $this->pay_way_name[$pay_way];
            $toolConfig = M('tool','tab_')->where(['name'=>$payWayName])->find();
            $config = json_decode($toolConfig['config'],true);
            if(empty($config['channel_rate'])){
                $channel_rate = 0;
            }else {
                $channel_rate = $config['channel_rate'];
            }
            
        }else {
            foreach($this->pay_way_name as $key => $value) {
                $name = $value;
                $toolConfig = M('tool','tab_')->where(['name'=>$name])->find();
                $config = json_decode($toolConfig['config'],true);
                if(empty($config['channel_rate'])){
                    $channel_rate[$key] = 0;
                }else {
                    $channel_rate[$key] = $config['channel_rate'];
                }
            }
        }

        return $channel_rate;
        
    }

    public function detailList($p = 1) {
        $mytime = $_REQUEST['my_time'];
        $nextMonth = date('Y-m',strtotime("$mytime + 1 month"));
        $game_id = $_REQUEST['game_id'];
        $gameInfo = M('game','tab_')->where(['id'=>$game_id])->getField('game_name');
        $gameName = substr($gameInfo,0,strpos($gameInfo,'('));
        $gameMap['game_name'] = ['like','%'.$gameName.'%'];
        $gameIdArr = M('game','tab_')->field('id')->where($gameMap)->select();
        $gameNameIdArr = [];
        foreach($gameIdArr as $gameKey => $gameValue){
            $gameNameIdArr[] = $gameValue['id'];
        }
        $promote_id = $_REQUEST['promote_id'];
        $promoteInfo = M('promote','tab_')->where(['id'=>$promote_id])->find();
        $level = $promoteInfo['level'];
        if($promote_id != 0) {
            $promoteIdArr = [];
            if ($level == 1) {
                $rootPromoteId = $promote_id;
                $promoteIdArr[] = $promote_id;
            }else {
                $chain = $promoteInfo['chain'];
                $chainArr = explode('/',$chain);
                $rootPromoteId = $chainArr[1];
            }
            $where1['chain'] =  array('like', '%/' . $rootPromoteId. '/%');  
            $promoteIdInfo = M('promote','tab_')->field('id')->where($where1)->select();
            foreach($promoteIdInfo as $key2 => $v1) {
               $promoteIdArr[] = $v1['id'];
            }
            $map['promote_id'] = ['in',$promoteIdArr];
         }else {
            $map['promote_id'] = 0;
         }
         var_dump($level);
        $pay_status = 1;
        $map['game_id'] = ['in',$gameNameIdArr];
      //  $map['promote_id'] = ['in',$promoteIdArr];
        $map['pay_status'] = 1;
        $begTime = strtotime($mytime);
        $endTime = strtotime($nextMonth);
        $map['pay_time'] = ['between',[$begTime,$endTime]];
        
        $spendInfo = M('spend','tab_')->field('pay_amount,pay_way')->where($map)->select();
        $initZfbNum = 0;
        $initWxsmNum = 0;
        $initWxNum = 0;
        $initPlatformCoinNum = 0;
        $initBindNum = 0;
        $initSqNum = 0;
        $initWftNum = 0;
        $initJbyNum = 0;
        $initJftNum = 0;
        $initappleNum = 0;
        $initJzNum = 0;
        $initSqzfbNum = 0;   //双乾支付-支付宝
        $initSqylNum = 0;     //双乾支付-银联
        $initSqkjNum = 0;   // 双乾支付-快捷
        $initZfbNumTotal = 0;
        $initWxsmNumTotal = 0;
        $initWxNumTotal = 0;
        $initPlatformCoinNumTotal = 0;
        $initBindNumTotal = 0;
        $initSqNumTotal = 0;
        $initWftNumTotal = 0;
        $initJbyNumTotal = 0;
        $initJftNumTotal = 0;
        $initappleNumTotal = 0;
        $initJzNumTotal = 0;
        $initSqzfbNumTotal = 0;   //双乾支付-支付宝
        $initSqylNumTotal = 0;     //双乾支付-银联
        $initSqkjNumTotal = 0;   // 双乾支付-快捷
        $detailInfoTotal = [];
        foreach($spendInfo as $key => $value) {
            $pay_way = $value['pay_way'];
            $pay_amount = $value['pay_amount'];
            $channel_rate = $this->getChannelConfig($pay_way) / 100;
            switch($pay_way) {
                 case -1:
                    $initBindNumTotal += $pay_amount ;     //总流水   
                    $initBindNum += $channel_rate * $pay_amount;    //总扣费
                    $afterBindNum = $initBindNumTotal - $initBindNum;
                    break;   
                 case 0:
                    $initPlatformCoinNumTotal += $pay_amount ;     
                    $initPlatformCoinNum += $channel_rate * $pay_amount;  
                    $afterPlatformCoinNum = $initPlatformCoinNumTotal - $initPlatformCoinNum;
                 break;
                 case 1:
                    $initZfbNumTotal += $pay_amount ;        
                    $initZfbNum += $channel_rate * $pay_amount;    
                    $afterZfbNum = $initZfbNumTotal - $initZfbNum;
                 break;
                 case 2:
                    $initWxsmNumTotal += $pay_amount ;    
                    $initWxsmNum += $channel_rate * $pay_amount;    
                    $afterWxsmNum = $initWxsmNumTotal - $initWxsmNum;
                 break;
                 case 3:
                    $initWxNumTotal += $pay_amount ;     
                    $initWxNum += $channel_rate * $pay_amount;    
                    $afterWxNum = $initWxNumTotal - $initWxNum;
                 break;
                 case 4:
                    $initWftNumTotal += $pay_amount ;      
                    $initWftNum += $channel_rate * $pay_amount;    
                    $afterWftNum = $initWftNumTotal - $initWftNum;
                 break;
                 case 5:
                    $initJbyNumTotal += $pay_amount ;     
                    $initJbyNum += $channel_rate * $pay_amount;    
                    $afterJbyNum = $initJbyNumTotal - $initJbyNum;
                 break;
                 case 6:
                    $initJftNumTotal += $pay_amount ;    
                    $initJftNum += $channel_rate * $pay_amount;   
                    $afterJftNum = $initJftNumTotal - $initJftNum;
                 break;
                 case 7:
                    $initappleNumTotal += $pay_amount;
                    $initappleNum += $channel_rate * $pay_amount;
                    $afterappleNum = $initappleNumTotal - $initappleNum;
                 break;   
                 case 8:
                    $initJzNumTotal += $pay_amount;
                    $initJzNum += $channel_rate * $pay_amount;
                    $afterappleNum = $initappleNumTotal - $initappleNum;
                 break;
                 case 9:
                    $initSqzfbNumTotal += $pay_amount;
                    $initSqzfbNum += $channel_rate * $pay_amount;
                    $afterSqzfbNum = $initSqzfbNumTotal - $initSqzfbNum;
                 break;
                 case 10:
                    $initSqylNumTotal += $pay_amount;
                    $initSqylNum += $channel_rate * $pay_amount;
                    $afterSqylNum = $initSqylNumTotal - $initSqylNum;
                 break;
                 case 15:
                    $initSqkjNumTotal += $pay_amount;
                    $initSqkjNum += $channel_rate * $pay_amount;
                    $afterSqkjNum = $initSqkjNumTotal - $initSqkjNum;  
                 break;
                 default:
                break;
            }

        }
        $detailInfoTotal['bindtotal'] = $initBindNumTotal;
        $detailInfoTotal['platformcointotal'] = $initPlatformCoinNumTotal;
        $detailInfoTotal['zfbtotal'] = $initZfbNumTotal;
        $detailInfoTotal['wxsmtotal'] = $initWxsmNumTotal;
        $detailInfoTotal['wxtotal'] = $initWxNumTotal;
        $detailInfoTotal['wfttotal'] = $initWftNumTotal;
        $detailInfoTotal['jbytotal'] = $initJbyNumTotal;
        $detailInfoTotal['jfttotal'] = $initJftNumTotal;
        $detailInfoTotal['appletotal'] = $initappleNumTotal;
        $detailInfoTotal['jztotal'] = $initJzNumTotal;
        $detailInfoTotal['sqzfbtotal'] = $initSqzfbNumTotal;
        $detailInfoTotal['sqyltotal'] = $initSqylNumTotal;
        $detailInfoTotal['sqkjtotal'] = $initSqkjNumTotal;


        $detailInfoTotal['bind'] = $initBindNum;
        $detailInfoTotal['platformcoin'] = $initPlatformCoinNum;
        $detailInfoTotal['zfb'] = $initZfbNum;
        $detailInfoTotal['wxsm'] = $initWxsmNum;
        $detailInfoTotal['wx'] = $initWxNum;
        $detailInfoTotal['wft'] = $initWftNum;
        $detailInfoTotal['jby'] = $initJbyNum;
        $detailInfoTotal['jft'] = $initJftNum;
        $detailInfoTotal['apple'] = $initappleNum;
        $detailInfoTotal['jz'] = $initJzNum;
        $detailInfoTotal['sqzfb'] = $initSqzfbNum;
        $detailInfoTotal['sqyl'] = $initSqylNum;
        $detailInfoTotal['sqkj'] = $initSqkjNum;

        $detailInfoTotal['afterbind'] = $afterBindNum;
        $detailInfoTotal['afterplatformcoin'] = $afterPlatformCoinNum;
        $detailInfoTotal['afterzfb'] = $afterZfbNum;
        $detailInfoTotal['afterwxsm'] = $afterWxsmNum;
        $detailInfoTotal['afterwx'] = $afterWxNum;
        $detailInfoTotal['afterwft'] = $afterWftNum;
        $detailInfoTotal['afterjby'] = $afterJbyNum;
        $detailInfoTotal['afterjft'] = $afterJftNum;
        $detailInfoTotal['afterapple'] = $afterappleNum;
        $detailInfoTotal['afterjz'] = $afterJzNum;
        $detailInfoTotal['aftersqzfb'] = $afterSqzfbNum;
        $detailInfoTotal['aftersqyl'] = $afterSqylNum;
        $detailInfoTotal['aftersqkj'] = $afterSqkjNum;
        
        $rateCon = $this->getChannelConfig(0,true);    
        $this->assign('ratecon',$rateCon);
        $this->assign('data', $detailInfoTotal);
        $this->display();
    }
}