<?php

namespace Home\Controller;

use OT\DataDictionary;
use User\Api\PromoteApi;
use Base\Repository\PromoteRepository;
use Base\Repository\SpendRepository;
use Base\Repository\UserRepository;
use Base\Service\PromoteService;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class QueryController extends BaseController
{
    public static $payWay = [
        -1 => '绑币',
        0 => '平台币',
        1 => '支付宝',
        2 => '微信',
        9 => '双乾支付',
        15 => '双乾支付-快捷'
    ];

    public static $payStatus = [
        0 => '下单未支付',
        1 => '充值成功',
    ];

    public function recharge($p = 0)
    {
        $page = intval(I('p', 1));
        $row = intval(I('row', 10));
        $ownId = intval(I('own_id'), 0); //本账号
        $relationGameId = intval(I('relation_game_id', 0));
        $sdkVersion = intval(I('sdk_version', 0));
        $serverId = trim(I('server_id', ''));
        $gamePlayerName = trim(I('game_player_name', ''));
        $userAccount = trim(I('user_account', ''));
        $payOrderNumber = trim(I('pay_order_number', ''));
        $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;
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
        $loginPromote = $this->getLoginPromote();

        $map = [];
        if ($ownId) {
            $map['tab_spend.promote_id'] = $queryPromote['id'];
        } else {
            $map['chain'] = ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%'];
            $ids = M('promote', 'tab_')->where($map)->getField('id', true);
            $ids[] = $queryPromote['id'];

            $map = [];
            $map['tab_spend.promote_id'] = ['in', $ids];
        }
        if (!empty($relationGameId)) {
            $map['tab_game.relation_game_id'] = $relationGameId;
        }
        if (!empty($sdkVersion)) {
            $map['tab_game.sdk_version'] = $sdkVersion;
        }
        if (!empty($serverId)) {
            $map['tab_spend.server_id'] = $serverId;
        }
        if (!empty($gamePlayerName)) {
            $map['tab_spend.game_player_name'] = $gamePlayerName;
        }
        if (!empty($userAccount)) {
            $map['tab_spend.user_account'] = $userAccount;
        }
        if (!empty($payOrderNumber)) {
            $map['tab_spend.pay_order_number'] = $payOrderNumber;
        }
        if (isset($_REQUEST['pay_way']) && $_REQUEST['pay_way'] !== '') {
            $payWay = intval(I('pay_way'));

            if (in_array($payWay, array_keys(QueryController::$payWay))) {
                if ($payWay == 2) {
                    $map['tab_spend.pay_way'] = ['in', '2,3,4'];
                } else {
                    $map['tab_spend.pay_way'] = $payWay;
                }
            }
        }
        if (isset($_REQUEST['pay_status']) && $_REQUEST['pay_status'] !== '') {
            $payStatus = intval(I('pay_status'));

            if (in_array($payStatus, array_keys(QueryController::$payStatus))) {
                $map['tab_spend.pay_status'] = $payStatus;
            }
        }
        $map['tab_spend.pay_time'] = ['between', [$begTime, $endTime - 1]];

        $data = [];
        $count = 0;
        $income = '0.00';
        if (intval($endTime - $begTime) / (24 * 3600) <= 31) {
            $data = M('Spend', 'tab_')
                ->field('tab_spend.*,tab_promote.account as pro_account,tab_promote.real_name as pro_real_name,tab_promote.chain as chain,tab_promote.level,tab_promote.parent_id')
                ->join('tab_game on tab_spend.game_id = tab_game.id')
                ->join('left join tab_promote on tab_spend.promote_id = tab_promote.id')
                ->where($map)
                ->order('tab_spend.id desc')
                ->page($page, $row)
                ->select();

            $count = M('Spend', 'tab_')
                ->join('tab_game on tab_spend.game_id = tab_game.id')
                ->where($map)
                ->count();

            $income = M('Spend', 'tab_')
                ->field('sum(tab_spend.pay_amount) as income')
                ->join('tab_game on tab_spend.game_id = tab_game.id')
                ->join('left join tab_promote on tab_spend.promote_id = tab_promote.id')
                ->where($map)
                ->order('tab_spend.id desc')
                ->find()['income'];
        }
        if (!empty($data)) {
            $promoteIdData = [];
            foreach ($data as $list) {
                switch ($list['level']) {
                    case 3:
                        $promoteIdData[] = $list['parent_id'];
                        break;
                    case 4:
                        $promoteIdData[] = $list['parent_id'];
                        $chain = trim($list['chain'], '/');
                        $chainArr = explode('/', $chain);
                        $promoteIdData[] = $chainArr[1];
                        break;
                }
            }
            $promoteData = [];
            if (!empty($promoteIdData)) {
                $promoteIdData = array_unique($promoteIdData);
                $promoteData = M('promote', 'tab_')->where(array('id' => ['in',$promoteIdData]))->getField('id,account,real_name,group_remark');
            }
            foreach ($data as &$list) {
                switch ($list['level']) {
                    case 1:
                    case 2:
                        $list['p_p_pro_account'] = $list['pro_account'];
                        $list['p_p_pro_real_name'] = $list['pro_real_name'];
                        $list['p_pro_account'] = $list['pro_account'];
                        $list['p_pro_real_name'] = $list['pro_real_name'];
                        break;
                    case 3:
                        $list['p_p_pro_account'] = $promoteData[$list['parent_id']]['account'];
                        $list['p_p_pro_real_name'] = $promoteData[$list['parent_id']]['real_name'];
                        $list['p_pro_account'] = $list['pro_account'];
                        $list['p_pro_real_name'] = $list['pro_real_name'];
                        break;
                    case 4:
                        $promoteIdData[] = $list['parent_id'];
                        $chain = trim($list['chain'], '/');
                        $chainArr = explode('/', $chain);
                        $list['p_p_pro_account'] = $promoteData[$chainArr[1]]['account'];
                        $list['p_p_pro_real_name'] = $promoteData[$chainArr[1]]['real_name'];
                        $list['p_p_pro_group_remark'] = $promoteData[$chainArr[1]]['group_remark'];
                        $list['p_pro_account'] = $promoteData[$list['parent_id']]['account'];
                        $list['p_pro_real_name'] = $promoteData[$list['parent_id']]['real_name'];
                        $list['p_pro_group_remark'] = $promoteData[$list['parent_id']]['group_remark'];
                        break;
                }
                $list['user_account'] = substr($list['user_account'], 0, 2) . '******' . substr($list['user_account'], 8);
                $list['pay_time'] = ($list['pay_status'] == 1) ? date('Y-m-d H:i:s', $list['pay_time']) : '--';
                $list['pay_status'] = isset(QueryController::$payStatus[$list['pay_status']]) ? QueryController::$payStatus[$list['pay_status']] : '未知状态';
                $list['sdk_version'] = getSDKTypeName($list['sdk_version']);

                //订单隐藏算法
                $orderLen = strlen($list['pay_order_number']);
                $strLen = 4;
                $hideChar = '';

                if ($orderLen <= 8) {
                    $strLen = 2;
                }

                for ($i = 0; $i < $orderLen - $strLen * 2; $i++) {
                    $hideChar .= '*';
                }

                $list['pay_order_number'] = substr($list['pay_order_number'], 0, $strLen) . $hideChar . substr($list['pay_order_number'], $orderLen - $strLen);
            }
        }

        //分页
        $parameter['p'] = $page;
        $parameter['row'] = $row;
        $parameter['begtime'] = $initBegTime;
        $parameter['endtime'] = $initEndTime;
        $parameter['relation_game_id'] = $relationGameId;
        $parameter['sdk_version'] = $sdkVersion;
        $parameter['server_id'] = $serverId;
        $parameter['game_player_name'] = $gamePlayerName;
        $parameter['user_account'] = $userAccount;
        $parameter['pay_order_number'] = $payOrderNumber;
        $parameter['own_id'] = $ownId;
        $parameter['level_promote_2'] = $levelPromote[0];
        $parameter['level_promote_3'] = $levelPromote[1];
        $parameter['level_promote_4'] = $levelPromote[2];
        !isset($_REQUEST['pay_way']) || $parameter['pay_way'] = I('pay_way');
        !isset($_REQUEST['pay_status']) || $parameter['pay_status'] = I('pay_status', -1);

        $serverData = $this->getServer(I('relation_game_id'), I('sdk_version'));
        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('listData', $data);
        $this->assign('count', $count);
        $this->assign('income', $income);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('setdate', date("Y-m-d"));
        $this->assign('serverData', $serverData['data']);
        $this->assign('ownId', $ownId);
        $this->assign('payWayData', QueryController::$payWay);
        $this->assign('payStatusData', QueryController::$payStatus);
        $this->meta_title = "订单查询";
        $this->display();
    }

    public function register($p = 0)
    {
        $page = intval(I('p', 1));
        $row = intval(I('row', 10));
        $ownId = intval(I('own_id'), 0);//本账号
        $account = trim(I('account', ''));
        $id = intval(I('id', 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;
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
        $loginPromote = $this->getLoginPromote();

        $map = [];
        if ($ownId) {
            $map['tab_user.promote_id'] = $queryPromote['id'];
        } else {
            $map['chain'] = ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%'];
            $ids = M('promote', 'tab_')->where($map)->getField('id', true);
            $ids[] = $queryPromote['id'];

            $map = [];
            $map['tab_user.promote_id'] = ['in', $ids];
        }
        if (!empty($account)) {
            $map['tab_user.account'] = $account;
        }
        if (!empty($id)) {
            $map['tab_user.id'] = $id;
        }
        $map['tab_user.register_time'] = ['between', [$begTime, $endTime - 1]];

        $data = [];
        $count = 0;
        if (intval($endTime - $begTime) / (24 * 3600) <= 31) {
            $data = M('User', 'tab_')
                ->field('tab_user.*,tab_promote.real_name as pro_real_name')
                ->join('left join tab_promote on tab_user.promote_id = tab_promote.id')
                ->where($map)
                ->order('tab_user.id desc')
                ->page($page, $row)
                ->select();

            $count = M('User', 'tab_')
                ->where($map)
                ->count();
        }

        if (!empty($data)) {
            foreach ($data as &$list) {
                $loginMap['user_id'] = $list['id'];
                $newLoginData = M('UserLoginRecord', 'tab_')
                    ->field('login_time,login_ip')
                    ->where($loginMap)
                    ->order('login_time desc')
                    ->find();

                $list['new_login_time'] = date('Y-m-d H:i:s', $newLoginData['login_time']);
                $list['new_login_ip'] = $newLoginData['login_ip'];
                $list['account'] = substr($list['account'], 0, 2) . '******' . substr($list['account'], 8);
                if(!empty($list['device_number'])) {
                     $list['device_number'] = encryption($list['device_number']);
                }
                
            }
        }

        //分页
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');
        $parameter['begtime'] = $initBegTime;
        $parameter['endtime'] = $initEndTime;
        $parameter['account'] = $account;
        empty($id) || $parameter['id'] = $id;
        $parameter['own_id'] = $ownId;
        $parameter['level_promote_2'] = $levelPromote[0];
        $parameter['level_promote_3'] = $levelPromote[1];
        $parameter['level_promote_4'] = $levelPromote[2];
        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }

        $this->assign('listData', $data);
        $this->assign('count', $count);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('setdate', date("Y-m-d"));
        $this->assign('ownId', $ownId);
        $this->meta_title = '注册明细';
        $this->display();
    }

    /**
     *我的对账单
     */
    public function bill()
    {
        $map['promote_id'] = get_pid();
        if (isset($_REQUEST['bill_number']) && !empty($_REQUEST['bill_number'])) {
            $map['bill_number'] = $_REQUEST['bill_number'];
        }
        if (isset($_REQUEST['game_id']) && !empty($_REQUEST['game_id'])) {
            $map['game_id'] = $_REQUEST['game_id'];
        }
        if (!empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
            $map['bill_start_time'] = array('egt', strtotime($_REQUEST['timestart']));
            $map['bill_end_time'] = array('elt', strtotime($_REQUEST['timeend']) + 24 * 3600 - 1);
        }
        $model = array(
            'm_name' => 'bill',
            'map' => $map,
            'template_list' => 'bill',
            'title' => '我的对账单',
        );
        $user = A('User', 'Event');
        $user->bill_list($model, $_GET['p']);
    }


    /**
     *我的结算
     */
    public function my_earning($p = 1)
    {
        $pro_map['id'] = get_pid();
        $pro = M("promote", "tab_")->where($pro_map)->find();
        $map['promote_id'] = get_pid();
        if ($pro['parent_id'] == 0) {
            if (isset($_REQUEST['settlement_number']) && !empty($_REQUEST['settlement_number'])) {
                $map['settlement_number'] = ['like', '%' . $_REQUEST['settlement_number'] . '%'];
            }
            if (!empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
                /*$map['bill_start_time'] = array('egt',strtotime($_REQUEST['timestart']));
                $map['bill_end_time'] = array('elt',strtotime($_REQUEST['timeend'])+24*3600-1);*/
                $map['starttime'] = array('egt', strtotime($_REQUEST['timestart']));
                $map['endtime'] = array('elt', strtotime($_REQUEST['timeend']) + 24 * 3600 - 1);
            } elseif (!empty($_REQUEST['timestart']) && empty($_REQUEST['timeend'])) {
                $map['starttime'] = array('egt', strtotime($_REQUEST['timestart']));
            } elseif (empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
                $map['endtime'] = array('elt', strtotime($_REQUEST['timeend']) + 24 * 3600 - 1);
            }

            $model = array(
                'm_name' => 'TotalSettlement',
                'map' => $map,
                'fields' => true,
                'order' => 'create_time desc ',
                'template_list' => 'my_earning',
                'title' => '我的结算',

            );
        } else {

            if (isset($_REQUEST['settlement_number']) && !empty($_REQUEST['settlement_number'])) {
                $map['settlement_number'] = ['like', '%' . $_REQUEST['settlement_number'] . '%'];
            }
            if (!empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
                $map['settlement_start_time'] = array('egt', strtotime($_REQUEST['timestart']));
                $map['settlement_end_time'] = array('elt', strtotime($_REQUEST['timeend']) + 24 * 3600 - 1);
            } elseif (!empty($_REQUEST['timestart']) && empty($_REQUEST['timeend'])) {
                $map['settlement_start_time'] = array('egt', strtotime($_REQUEST['timestart']));
            } elseif (empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
                $map['settlement_end_time'] = array('elt', strtotime($_REQUEST['timeend']) + 24 * 3600 - 1);
            }

            $model = array(
                'm_name' => 'son_settlement',
                'fields' => 'settlement_number,settlement_start_time,create_time,
                        settlement_end_time,game_id,game_name,promote_id,
                        promote_account,pattern,bind_coin_status,floor(sum(sum_money*100))/100 as sum_money,
                        sum(reg_number) as reg_number,ratio,money,floor(sum(jie_money*100))/100 as jie_money,status,ti_status',
                'map' => $map,
                'template_list' => 'my_earning_sub',
                'order' => 'create_time desc',
                'group' => 'settlement_number, create_time',
                'title' => '我的结算',
            );
        }
        $user = A('User', 'Event');
        $this->assign("parent_id", $pro['parent_id']);
        $user->shou_list($model, $p);
    }

    /**
     *子渠道结算单
     */
    public function son_earning_($p = 1)
    {
        if (PLEVEL == 0) {
            if (isset($_REQUEST['timestart']) && isset($_REQUEST['timeend']) && !empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
                $starttime = strtotime($_REQUEST['timestart']);
                $endtime = strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1;
                $this->assign('starttime', $starttime);
                $this->assign('endtime', $endtime);
                $map[0]['register_time'] = array('BETWEEN', array($starttime, $endtime));
                $map[1]['pay_time'] = array('BETWEEN', array($starttime, $endtime));
                unset($_REQUEST['timestart']);
                unset($_REQUEST['timeend']);

                $map[1]['parent_id'] = $map[0]['u.parent_id'] = PID;
                if (isset($_REQUEST['ch_promote_id']) && !empty($_REQUEST['ch_promote_id'])) {
                    $map[1]['s.promote_id'] = $map[0]['u.promote_id'] = $_REQUEST['ch_promote_id'];
                }
                $model = array(
                    'title' => '子渠道结算单',
                    'template_list' => 'son_earning',
                );
                $user = A('User', 'Event');
                $user->check_bill($model, $p, $map);
            } else {
                $this->display();
            }
        } else {
            $model = array(
                'm_name' => 'SonSettlement',
                'order' => 'id ',
                'title' => '结算账单',
                'template_list' => 'son_earning',
            );

            $user = A('User', 'Event');
            $user->money_list($model, $p);
        }
    }

    //子渠道结算单
    public function son_list($p = 0)
    {
        if (!empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
            $map['settlement_start_time'] = array('egt', strtotime($_REQUEST['timestart']));
            $map['settlement_end_time'] = array('elt', strtotime($_REQUEST['timeend']) + 86399);
        } elseif (!empty($_REQUEST['timestart']) && empty($_REQUEST['timeend'])) {
            $map['settlement_start_time'] = array('egt', strtotime($_REQUEST['timestart']));
            $map['settlement_end_time'] = array('elt', time());
        } elseif (empty($_REQUEST['timestart']) && !empty($_REQUEST['timeend'])) {
            $map['settlement_end_time'] = array('elt', strtotime($_REQUEST['timeend']) + 86399);
        }
        if (!empty($_REQUEST['start']) && !empty($_REQUEST['end'])) {
            $start = strtotime($_REQUEST['start']);
            $end = strtotime($_REQUEST['end']) + 86399;
            $map['create_time'] = array('BETWEEN', array($start, $end));
        } elseif (!empty($_REQUEST['start']) && empty($_REQUEST['end'])) {
            $start = strtotime($_REQUEST['start']);
            $end = time();
            $map['create_time'] = array('BETWEEN', array($start, $end));
        } elseif (empty($_REQUEST['start']) && !empty($_REQUEST['end'])) {
            $end = strtotime($_REQUEST['end']) + 86399;
            $map['create_time'] = array('elt', $end);
        }

        if (!empty($_REQUEST['ch_promote_id'])) {
            $map['promote_id'] = $_REQUEST['ch_promote_id'];
        } else {

            $promote = M('Promote', 'tab_')->field('id')->where(['parent_id' => PID])->select();
            $zi_p = implode(',', array_column($promote, 'id'));
            $map['promote_id'] = array('in', "$zi_p");
        }
        $model = array(
            'm_name' => 'SonSettlement',
            'fields' => array(
                'settlement_number',
                'settlement_start_time',
                'settlement_end_time',
                'promote_id',
                'promote_account',
                'bind_coin_status',
                'FLOOR(sum(sum_money*100))/100  as sum_money',
                'sum(reg_number) as reg_number',
                'FLOOR(sum(jie_money*100))/100  as jie_money',
                'ti_status',
                'create_time'
            ),
            'order' => 'create_time desc',
            'group' => 'settlement_number,create_time',
            'title' => '子渠道结算单',
            'template_list' => 'son_list',
        );

        $user = A('User', 'Event');
        $user->money_list($model, $p, $map);
    }

    /**
     *子渠道结算单
     */
    public function son_earning($p = 0)
    {

        if (!empty($_REQUEST['timestart']) || !empty($_REQUEST['timeend'])) {
            $starttime = empty($_REQUEST['timestart']) ? strtotime("-7 day {$_REQUEST['timeend']}") : strtotime($_REQUEST['timestart']);
            $endtime = empty($_REQUEST['timeend']) ? mktime(23, 59, 59, date('m'), date('d') - 1, date('Y')) : strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1;
            $this->assign('starttime', date('Y-m-d', $starttime));
            $this->assign('endtime', date('Y-m-d', $endtime));
            $mapp['u.register_time'] = array('BETWEEN', array($starttime, $endtime));
            $mapp['u.' . SETTLEMENT_GRADE] = 0;
            $map['s.pay_time'] = array('BETWEEN', array($starttime, $endtime));
            $map['s.pay_status'] = 1;
            $map['s.' . SETTLEMENT_GRADE] = 0;

            if ($_REQUEST['bind_coin'] == 0) {
                $map['s.pay_way'] = array('neq', -1);
            }
            unset($_REQUEST['timestart']);
            unset($_REQUEST['timeend']);

            if (isset($_REQUEST['ch_promote_id']) && !empty($_REQUEST['ch_promote_id'])) {
                $chid = $_REQUEST['ch_promote_id'];

                $promote_child = get_sub_channel_id($chid, PRO_GRADE + 1);

                $map['s.promote_id'] = $mapp['u.promote_id'] = array('in', $promote_child);

            } else {
                $promote_child = get_zi_promote_id(PID);
                if (empty($promote_child)) {
                    $this->error('该渠道无子渠道');
                }
                $map['s.promote_id'] = $mapp['u.promote_id'] = array('in', $promote_child);
            }
            $model = array(
                'fields' => 'sum(s.pay_amount) as total_amount,s.promote_account,s.promote_id,s.game_name,s.game_id,s.sub_status',
                'm_name' => 'Spend',
                'title' => '子渠道结算单',
                'template_list' => 'son_earning',
                'join' => 'tab_apply on tab_Spend.game_id=tab_apply.game_id and tab_Spend.promote_id=tab_apply.promote_id',
                'group' => 's.promote_id,s.game_id',
                'currentid' => $chid ? $chid : '',
            );
            $mmap = array($mapp, $map);
            $user = A('User', 'Event');
            $user->check_child_bill($model, $p, $mmap);

        } else {
            $this->meta_title = '子渠道结算';
            $this->display();
        }

    }

    public function generatesub()
    {
        //$data = $_REQUEST;
        if (empty($_REQUEST['ids'])) {
            $this->error('请选择要结算的数据');
        } else {
            $settData = array();
            $settlement_number = 'js_' . date('YmdHis', time()) . rand(100, 999);
            $create_time = time();
            $start = $_REQUEST['timestart'];
            $end = $_REQUEST['timeend'];
            foreach ($_REQUEST['ids'] as $key => $value) {
                $data = json_decode($value, true);
                $data['settlement_number'] = $settlement_number;
                $data['create_time'] = time();
                $data['settlement_start_time'] = strtotime($data['settlement_start_time']);
                $data['settlement_end_time'] = strtotime($data['settlement_end_time']);
                switch ($data['cooperation']) {
                    case 'CPS':
                        $data['pattern'] = 0;
                        $cps = $data['ratio'];
                        $data['jie_money'] = round(($cps * $data['sum_money']) / 100, 2);
                        break;
                    case 'CPA':
                        $data['pattern'] = 1;
                        $cpa = $data['money'];
                        $data['jie_money'] = round($cpa * $data['reg_number'], 2);
                        break;
                }
                $userMap['register_time'] = array('BETWEEN', array($data['settlement_start_time'], $data['settlement_end_time'] + 86399));
                $userMap['fgame_id'] = $data['game_id'];

                $userMap[SETTLEMENT_GRADE] = $spendMap[SETTLEMENT_GRADE] = 0;

                $userMap['promote_id'] = $spendMap['promote_id'] = array('in', $data['tpid']);
                $spendMap['game_id'] = $data['game_id'];
                $spendMap['pay_time'] = $userMap['register_time'];
                $user = M('user', 'tab_')->where($userMap)->save(array(SETTLEMENT_GRADE => 1));
                $spend = M('spend', 'tab_')->where($spendMap)->save(array(SETTLEMENT_GRADE => 1));
                $settData[$key] = $data;
            }
            $result = M('SonSettlement', 'tab_')->addAll($settData);
            if ($result) {
                /*$this->success('生成结算单成功!',U('son_earning?success=1',array('timestart' => $start,'timeend' => $end)),true);*/
                $this->success('生成结算单成功!', U('son_list'), true);
            } else {
                $this->error('生成结算单失败!', U('son_earning?fall=1', array('timestart' => $start, 'timeend' => $end)), true);
            }
        }

        $this->error('生成结算单失败!!!', U('son_earning?fall=1', array('timestart' => $start, 'timeend' => $end)), true);
    }


    //申请提现
    public function apply_withdraw($id, $op = 0)
    {
        $map['id'] = $id;
        $with = M("withdraw", "tab_");
        $totalSett = M("TotalSettlement", "tab_")->where($map)->find();
        $with_map['settlement_number'] = $totalSett['settlement_number'];
        $fid = $with->where($with_map)->find();
        if ($fid == null) {
            $add['settlement_number'] = $totalSett['settlement_number'];
            $add['sum_money'] = $totalSett['jie_money'] ? $totalSett['jie_money'] : $totalSett['sum_money'];
            $add['promote_id'] = $totalSett['promote_id'];
            $add['promote_account'] = $totalSett['promote_account'];
            $add['create_time'] = time();
            $add['status'] = 0;
            $with->add($add);
            M("TotalSettlement", "tab_")->where($map)->save(array('ti_status' => 0));
            $settMap['promote_id'] = $totalSett['promote_id'];
            $settMap['starttime'] = $totalSett['starttime'];
            $settMap['endtime'] = $totalSett['endtime'];
            $settMap['create_time'] = $totalSett['create_time'];
            M("settlement", "tab_")->where($settMap)->save(array('ti_status' => 0));
            echo json_encode(array("status" => 1));
        } else {
            if ($op > 0) {
                $with->where($with_map)->setField('status', 0);
                M("settlement", "tab_")->where($map)->setField('ti_status', 0);
                M("TotalSettlement", "tab_")->where($map)->save(array('ti_status' => 0));
                echo json_encode(array("status" => 1));
            } else {
                echo json_encode(array("status" => 0));
            }
        }
    }

    //申请提现
    public function son_apply_withdraw($settlement_number = '')
    {
        $map['settlement_number'] = $settlement_number;
        $with_map['settlement_number'] = $totalSett['settlement_number'];
        $result = M("SonSettlement", "tab_")->where($map)->save(array('ti_status' => 0));
        if ($result !== false) {
            echo json_encode(array("status" => 1));
        } else {
            echo json_encode(array("status" => 0));
        }
    }

    public function audit_withdraw($settlement_number = '')
    {
        $map['settlement_number'] = $settlement_number;
        $with_map['settlement_number'] = $totalSett['settlement_number'];
        $result = M("SonSettlement", "tab_")->where($map)->save(array('ti_status' => 1));
        if ($result !== false) {
            $this->success('审核成功');
        } else {
            $this->error('审核失败');
        }
    }

    private function getDayList($beginTime, $endTime)
    {
        $dayList = [];
        do {
            $dayList[] = date('Y-m-d', $beginTime);
            $beginTime += 24 * 60 * 60;
        } while ($beginTime < $endTime);

        return $dayList;
    }

    public function arpu()
    {
        $this->meta_title = 'ARPU统计';

        $defaultTime = date('Y-m-d', time() - 6 * 24 * 3600) . ' 至 ' . date('Y-m-d');

        $time = I('time', '');
        $time = $time == '' ? $defaultTime : $time;
        $sdkVersion = I('sdk_version', 0);
        $gameId = I('game_id', 0);
        $serverId = I('server_id', 0);
        $levelPromote = $this->getLevelPromote();
        $searchPromote = $this->getQueryPromote($levelPromote);

        $map[] = [
            '_logic' => 'or',
            'id' => $searchPromote['id'],
            'chain' => ['like', $searchPromote['chain'] . $searchPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map)->getField('id', true);

        $games = $this->getGamesByPromote($searchPromote);

        $params = [];
        $searchGameName = '';
        $searchServerName = '';
        if ($gameId > 0) {
            $params['game_id'] = $gameId;
            $searchGameName = M('game', 'tab_')->where(['id' => $gameId])->getField('game_name');
        }
        if ($serverId > 0) {
            $params['server_id'] = $serverId;
            $searchServerName = M('server', 'tab_')->where(['server_id' => $serverId])->getField('server_name');
        }
        if ($sdkVersion > 0) {
            $params['sdk_version'] = $sdkVersion;
        }
        $params['promote_id'] = $ids;
        list($beginTime, $endTime) = $this->getBetweenTime($time);
        $params['begin_time'] = $beginTime;
        $params['end_time'] = $endTime;

        $dayList = $this->getDayList($beginTime, $endTime);
        $params['dayList'] = $dayList;

        $timeout = 0;
        $records = [];
        if (intval($endTime - $beginTime) / (24 * 3600) <= 7) {
            $userRepository = new UserRepository();
            $spendRepository = new SpendRepository();
            $payGameCountList = $spendRepository->getPayGameCountGroupByDay($params);
            $payUserCountList = $spendRepository->getPayUserCountGroupByDay($params);
            $newPayUserCountList = $spendRepository->getNewPayUserCountGroupByDay($params);
            $payAmountList = $spendRepository->getPayAmountGroupByDay($params);
            $newPayAmountList = $spendRepository->getNewPayAmountGroupByDay($params);
            $historyPayCountList = $spendRepository->getHistoryPayCountGroupByDay($params);
            $loginCountList = $userRepository->getLoginCountGroupByDay($params);
            $registerCountList = $userRepository->getRegisterCountGroupByDay($params);

            foreach ($dayList as $day) {
                $records[] = [
                    'day' => $day,
                    'payGameCount' => $payGameCountList[$day],
                    'payUserCount' => $payUserCountList[$day],
                    'newPayUserCount' => $newPayUserCountList[$day],
                    'payAmount' => number_format($payAmountList[$day], 2),
                    'newPayAmount' => number_format($newPayAmountList[$day], 2),
                    'historyPayCount' => $historyPayCountList[$day],
                    'loginCount' => $loginCountList[$day],
                    'registerCount' => $registerCountList[$day],
                    'payRate' => $loginCountList[$day] == 0 ? '--' : round($payUserCountList[$day] / $loginCountList[$day] * 100, 2) . '%',
                    'ratentionOneDay' => '--',
                    'arpu' => $loginCountList[$day] == 0 ? '0.00' : number_format(round($payAmountList[$day] / $loginCountList[$day], 2), 2),
                    'arppu' => $payUserCountList[$day] == 0 ? '0.00' : number_format(round($payAmountList[$day] / $payUserCountList[$day], 2), 2),
                ];
            }
        } else {
            $timeout = 1;
        }
        $this->assign('games', $games);
        $this->assign('timeout', $timeout);
        $this->assign('records', $records);
        $this->assign('searchGameName', $searchGameName);
        $this->assign('searchServerName', $searchServerName);
        $this->assign('searchPromote', $searchPromote);
        $this->display();
    }

    public function gameArpu()
    {
        $promote = $this->getLoginPromote();
        $map[] = [
            '_logic' => 'or',
            'id' => $promote['id'],
            'chain' => ['like', $promote['chain'] . $promote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map)->getField('id', true);

        $time = I('time', date('Y-m-d'));
        $applys = M('Apply', 'tab_')->field('game_id, game_name')->where(['promote_id' => $promote['id']])->order('game_id desc')->select();
        $gameIds = array_column($applys, 'game_id');
        $applys = index_by_column('game_id', $applys);

        $params = [
            'begin_time' => strtotime($time . ' 00:00:00'),
            'end_time' => strtotime($time . ' 23:59:59'),
            'game_ids' => $gameIds,
            'promote_ids' => $ids,
        ];

        $userRepository = new UserRepository();
        $spendRepository = new SpendRepository();
        $payUserCountList = $spendRepository->getPayUserCountGroupByGame($params);
        $newPayUserCountList = $spendRepository->getNewPayUserCountGroupByGame($params);
        $payAmountList = $spendRepository->getPayAmountGroupByGame($params);
        $newPayAmountList = $spendRepository->getNewPayAmountGroupByGame($params);
        $historyPayCountList = $spendRepository->getHistoryPayCountGroupByGame($params);
        $loginCountList = $userRepository->getLoginCountGroupByGame($params);
        $registerCountList = $userRepository->getRegisterCountGroupByGame($params);

        foreach ($gameIds as $gameId) {
            $records[] = [
                'gameId' => $gameId,
                'gameName' => $applys[$gameId]['game_name'],
                'payUserCount' => $payUserCountList[$gameId],
                'newPayUserCount' => $newPayUserCountList[$gameId],
                'payAmount' => number_format($payAmountList[$gameId], 2),
                'newPayAmount' => number_format($newPayAmountList[$gameId], 2),
                'historyPayCount' => $historyPayCountList[$gameId],
                'loginCount' => $loginCountList[$gameId],
                'registerCount' => $registerCountList[$gameId],
                'payRate' => $loginCountList[$gameId] == 0 ? '--' : round($payUserCountList[$gameId] / $loginCountList[$gameId] * 100, 2) . '%',
                'ratentionOneDay' => '--',
                'arpu' => $loginCountList[$gameId] == 0 ? '0.00' : number_format(round($payAmountList[$gameId] / $loginCountList[$gameId], 2), 2),
                'arppu' => $payUserCountList[$gameId] == 0 ? '0.00' : number_format(round($payAmountList[$gameId] / $payUserCountList[$gameId], 2), 2),
            ];
        }

        $this->assign('records', $records);
        $this->display('gameArpu');
    }

    public function arpu_analysis()
    {
        $this->meta_title = "ARPU统计";
        A('User', 'Event')->arpu_analysis();
    }

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

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

        $time = $_REQUEST['time'];
        $promote_id = $_REQUEST['promote_id'];
        /* if ($promote_id <1) {
            $pid = D('Promote')->get_child_promote(PID,'id');
            if (empty($pid[0])) {
                $promote_id = PID;
            } else {
                $id = implode(',',array_column($pid,'id'));
                $promote_id = PID.','.$id;
            }
        } */

        $join = "left join tab_user u on u.fgame_id = tab_game.id";
        if ($time == '') {
            $this->error('参数错误,缺少时间');
        } else {
            $map['register_time'] = array('between', array(strtotime($time), strtotime($time) + 24 * 60 * 60 - 1));
        }
        /* if($promote_id!=''){
            $map_list['promote_id']=array('in',$promote_id);
            $map['promote_id']=array('in',$promote_id);
            $join .= " AND u.promote_id = {$promote_id}";
        } */

        if ($promote_id > 0) {
            if (PID == $promote_id) {
                $pro_arr[] = PID;
            } else {

                $pro_id1 = get_prmoote_chlid_account2($promote_id);
                $pro_arr = array_column($pro_id1, 'id');
                $pro_arr[] = $promote_id;
            }
            $map['promote_id'] = array('in', $pro_arr);
            $map_list['promote_id'] = array('in', $pro_arr);
            $promote_id = implode(',', $pro_arr);
            $join .= " AND u.promote_id in ({$promote_id})";
        } else {
            $pid = D('Promote')->get_child_promote(PID, 'id');
            if (empty($pid[0])) {
                $pro_arr[] = PID;
            } else {
                $pro_arr = array_column($pid, 'id');
                $pro_arr[] = PID;
            }

            $map['promote_id'] = array('in', $pro_arr);
            $map_list['promote_id'] = array('in', $pro_arr);
            $promote_id = implode(',', $pro_arr);
            $join .= " AND u.promote_id in ({$promote_id})";

        }
        $spend2 = D('Spend');
        $data = M('Apply', 'tab_')->field('game_id, game_name')->where(['promote_id' => $promote_id])->order('game_id desc')->select();
        foreach ($data as $key => $value) {
            $game_id = $value['game_id'];
            $map_list['game_id'] = $game_id;
            $user = M('User', 'tab_');
            $spend = M('spend', 'tab_');

            //新增人数
            $rdata = $user
                ->field('count(id) as register_num')
                ->where(array('fgame_id' => $game_id))
                ->where(array_merge($map, ['puid' => 0]))
                ->find();
            $data[$key]['register_num'] = $rdata['register_num'];
            //活跃玩家
            //$data[$key]['act_user'] = $this->count_act_user($time,$game_id,$promote_id);
            $activedata = D('User')->login_count_by_time(strtotime($time), strtotime($time) + 86399, $game_id, $promote_id);
            $data[$key]['act_user'] = $activedata[0]['login_num'] ? $activedata[0]['login_num'] : 0;
            //1日留存
            $mapl = $map_list;
            $mapl["FROM_UNIXTIME(register_time,'%Y-%m-%d')"] = $time;
            $mapl['tab_user.promote_id'] = $mapl['promote_id'];
            $mapl['tab_user.puid'] = 0;
            unset($mapl['promote_id']);
            $login_time = date('Y-m-d', strtotime("+1 day", strtotime($time)));
            $num = $user
                ->field('count(DISTINCT tab_user.id) as num')
                ->join("right join tab_user_login_record as ur on ur.user_id = tab_user.id and FROM_UNIXTIME(ur.login_time,'%Y-%m-%d') = '{$login_time}'")
                ->where($mapl)
                ->find();
            $data[$key]['keep_num'] = round($num['num'] / $data[$key]['register_num'], 4) * 100;
            //充值
            $mapl = $map_list;
            empty($game_name) || $mapl['game_name'] = array('like', '%' . $game_name . '%');

            $mapl['pay_status'] = 1;
            $mapl["FROM_UNIXTIME(pay_time,'%Y-%m-%d')"] = $time;
            if (I('bangbi') == 1) {
                $mapl['pay_way'] = array('neq', '-10');
                $bangbi = true;
            } else {
                $mapl['pay_way'] = array('neq', -1);
                $bangbi = false;
            }
            $spend = $spend->field("IFNULL(sum(pay_amount),0) as money,IFNULL(count(distinct user_id),0) as people")->where($mapl)->find();
            $data[$key]['spend'] = $spend['money'];
            //付费玩家数
            $data[$key]['spend_people'] = $spend['people'];
            //新付费玩家
            $newsdata = $spend2->pay_count_by_time_class([$time], $game_id, $promote_id, 1, $bangbi);
            $data[$key]['spend_news'] = $newsdata[0]['pay_num'] ? $newsdata[0]['pay_num'] : 0;
            //付费率
            $data[$key]['spend_rate'] = round($data[$key]['spend_people'] / $data[$key]['act_user'], 4) * 100;
            //ARPU
            $data[$key]['ARPU'] = round($data[$key]['spend'] / $data[$key]['act_user'], 2);
            //ARPPU
            $data[$key]['ARPPU'] = round($data[$key]['spend'] / $data[$key]['spend_people'], 2);
            if ($data[$key]['register_num'] == 0 && $data[$key]['act_user'] == 0 && $data[$key]['keep_num'] == 0 && $data[$key]['spend'] == 0 && $data[$key]['spend_people'] == 0) {
                unset($data[$key]);
            }
        }
        $count = count($data);
        /*         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());
                } */

        /*$page = set_pagination($count,++$count);
        if($page) {$this->assign('_page', $page);}*/
        $this->assign('_page', '<div><span class="rows">共 ' . $count . ' 条记录</span></div>');

        /*$size=$row;//每页显示的记录数
        $pnum = ceil(count($data) / $size); //总页数,ceil()函数用于求大于数字的最小整数
        //用array_slice(array,offset,length) 函数在数组中根据条件取出一段值;array(数组),offset(元素的开始位置),length(组的长度)
        $data = array_slice($data, ($arraypage-1)*$size, $size);*/
        $this->assign('list_data', $data);
        $this->display();
    }


    /**
     * 获取活跃用户数
     * @param $time
     */
    public function count_act_user($time, $game_id = "", $promote_id = "")
    {
        $map["FROM_UNIXTIME(login_time,'%Y-%m-%d')"] = $time;
        $map1["FROM_UNIXTIME(register_time,'%Y-%m-%d')"] = $time;
        empty($game_id) || $map['game_id'] = $game_id;
        empty($game_id) || $map1['fgame_id'] = $game_id;
        if (!empty($promote_id)) {
            $user = M('User', 'tab_')->field('id')->where(array('promote_id' => $promote_id))->select();
            $user = implode(',', array_column($user, 'id'));
            $map['user_id'] = array('in', $user);
            $map1['id'] = array('in', $user);
        };
        $uudata = M('User', 'tab_')
            ->field('id')
            ->where($map1)
            ->select(false);
        $data = M('user_login_record', 'tab_')
            ->field('id')
            ->where($map)
            ->union($uudata)
            ->group('user_id')
            ->select();
        $data = count($data);
        return $data;
    }

    public function retention_analysis()
    {
        $this->meta_title = '留存统计';
        A('User', 'Event')->retention_analysis();

    }

    public function details()
    {
        $map['id'] = $_REQUEST['id'];
        $data = M('TotalSettlement', 'tab_')->where($map)->find();
        $mapSett['promote_id'] = $data['promote_id'];
        $mapSett['starttime'] = $data['starttime'];
        $mapSett['endtime'] = $data['endtime'];
        $mapSett['create_time'] = $data['create_time'];
        $listData = M('settlement', 'tab_')->where($mapSett)->select();
        $totalData = M('settlement', 'tab_')->where($mapSett)->sum('sum_money');
        $this->assign('list_data', $listData);
        $this->assign('total', $totalData);
        $this->display();
    }

    public function son_details()
    {
        $map['promote_id'] = $_REQUEST['promote_id'];
        $map['settlement_number'] = $_REQUEST['settlement_number'];
        $data = M('SonSettlement', 'tab_')->where($map)->select();
        $total = M('SonSettlement', 'tab_')->where($map)->sum('jie_money');
        $this->assign('total', floor($total * 100) / 100);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function dailySummary()
    {
        $relationGameId = intval(I('relation_game_id', 0));
        $sdkVersion = intval(I('sdk_version', 0));
        $serverId = I('server_id', '');
        $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;
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);

        $loginPromote = $this->getLoginPromote();

        $ownId = intval(I('own_id'), 0);//本账号
        if ($ownId) {
            $params['promote_id'] = $queryPromote['id'];
        } else {
            $map['chain'] = ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%'];
            $ids = M('promote', 'tab_')->where($map)->getField('id', true);
            $ids[] = $queryPromote['id'];
            $ids = implode(',', $ids);

            $params['promote_id'] = $ids;
        }
        if ($relationGameId > 0 || $sdkVersion > 0) {
            if ($sdkVersion > 0) {
                $map['sdk_version'] = $sdkVersion;
            }
            if ($relationGameId > 0) {
                $map['relation_game_id'] = $relationGameId;
            }
            $gameIds = M('Game', 'tab_')->where($map)->getField('id', true);
            if (empty($gameIds)) {
                $params['_string'] = '1=2';
            } else {
                $gameIds = implode(',', $gameIds);
                $params['game_id'] = ['in', $gameIds];
            }
        }
        if (!empty($serverId)) {
            $params['server_id'] = $serverId;
        }
        $params['begin_time'] = $begTime;
        $params['end_time'] = $endTime - 1;

        $summaryData = [];
        $dayList = $this->getDayList($begTime, $endTime);
        $dayListReverse = $dayList;
        $dayList = array_reverse($dayList);
        $params['dayList'] = $dayList;

        $records = [];
        if (intval($endTime - $begTime) / (24 * 3600) <= 31) {
            $userRepository = new UserRepository();
            $spendRepository = new SpendRepository();
            $roleNumList = $userRepository->getCreateRoleCountByDay($params);//创角数
            $userNumList = $userRepository->getCreateRoleUserCountByDay($params);//创角用户
            $newUserNumList = $userRepository->getNewCreateRoleUserCountByDay($params);//新创角用户
            $newDeviceNumList = $userRepository->getNewCreateRoleDeviceCountByDay($params);//新创角设备
            $newIpNumList = $userRepository->getNewCreateRoleIpCountByDay($params);//新创角IP
            $loginUserNumList = $userRepository->getLoginCountGroupByDayNew($params);//登录用户数
            if ($this->canViewUserRecharge) {
                $spendUserNumList = $spendRepository->getPayUserCountGroupByDayNew($params);//充值人数
                $spendNumList = $spendRepository->getPayCountGroupByDay($params);//充值次数
                $spendAllAmountList = $spendRepository->getPayAmountGroupByDayAndType($params);//充值总额
                $params['pay_way'] = ['in', '1,2,3,4,5,6'];
                $spendCashList = $spendRepository->getPayAmountGroupByDayAndType($params);//现金充值
                $params['pay_way'] = 0;
                $spendGenericList = $spendRepository->getPayAmountGroupByDayAndType($params);//通用币充值
                $params['pay_way'] = -1;
                $spendBindingList = $spendRepository->getPayAmountGroupByDayAndType($params);//绑定币充值
            }

            $allData['role_num'] = 0;
            $allData['user_num'] = 0;
            $allData['new_user_num'] = 0;
            $allData['new_device_num'] = 0;
            $allData['new_ip_num'] = 0;
            $allData['login_user_num'] = 0;
            if ($this->canViewUserRecharge) {
                $allData['spend_user_num'] = 0;
                $allData['spend_num'] = 0;
                $allData['spend_all_amount'] = 0;
                $allData['spend_cash'] = 0;
                $allData['spend_generic'] = 0;
                $allData['spend_binding'] = 0;
                $allData['spend_discount'] = 0;
                $allData['spend_voucher'] = 0;
            }
            foreach ($dayList as $day) {
                $date = date('Ymd', strtotime($day));
                $record = [
                    'day' => $date,
                    'role_num' => $roleNumList[$day],
                    'user_num' => $userNumList[$day],
                    'new_user_num' => $newUserNumList[$day],
                    'new_device_num' => $newDeviceNumList[$day],
                    'new_ip_num' => $newIpNumList[$day],
                    'login_user_num' => $loginUserNumList[$day],
                ];

                $allData['role_num'] += $roleNumList[$day];
                $allData['user_num'] += $userNumList[$day];
                $allData['new_user_num'] += $newUserNumList[$day];
                $allData['new_device_num'] += $newDeviceNumList[$day];
                $allData['new_ip_num'] += $newIpNumList[$day];
                $allData['login_user_num'] += $loginUserNumList[$day];

                if ($this->canViewUserRecharge) {
                    $record['spend_user_num'] = $spendUserNumList[$day];
                    $record['spend_num'] = $spendNumList[$day];
                    $record['spend_all_amount'] = $spendAllAmountList[$day];
                    $record['spend_cash'] = $spendCashList[$day];
                    $record['spend_generic'] = $spendGenericList[$day];
                    $record['spend_binding'] = $spendBindingList[$day];
                    $record['spend_discount'] = 0;
                    $record['spend_voucher'] = 0;

                    $allData['spend_user_num'] += $spendUserNumList[$day];
                    $allData['spend_num'] += $spendNumList[$day];
                    $allData['spend_all_amount'] = bcadd($allData['spend_all_amount'], $spendAllAmountList[$day], 2);
                    $allData['spend_cash'] = bcadd($allData['spend_cash'], $spendCashList[$day], 2);
                    $allData['spend_generic'] = bcadd($allData['spend_generic'], $spendGenericList[$day], 2);
                    $allData['spend_binding'] = bcadd($allData['spend_binding'], $spendBindingList[$day], 2);
                    $allData['spend_discount'] = bcadd($allData['spend_discount'], 0, 2);
                    $allData['spend_voucher'] = bcadd($allData['spend_voucher'], 0, 2);
                }
                $records[] = $record;
            }
            foreach ($dayListReverse as $day) {
                $date = date('Ymd', strtotime($day));
                $summaryData['date'][] = $date;
                $summaryData['role_num'][] = $roleNumList[$day];
                $summaryData['user_num'][] = $userNumList[$day];
                $summaryData['new_user_num'][] = $newUserNumList[$day];
                $summaryData['new_device_num'][] = $newDeviceNumList[$day];
                if ($this->canViewUserRecharge) {
                    $summaryData['spend_user_num'][] = $spendUserNumList[$day];
                    $summaryData['spend_all_amount'][] = $spendAllAmountList[$day];
                }
            }
        }

        $serverData = $this->getServer($relationGameId, $sdkVersion);

        $this->assign('meta_title', '每日概况');
        $this->assign('loginPromote', $loginPromote);
        $this->assign('ownId', $ownId);
        $this->assign('listData', $records);
        $this->assign('allData', $allData);
        $this->assign('summaryData', $summaryData);
        $this->assign('setdate', date("Y-m-d"));
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('serverData', $serverData['data']);
        $this->display();
    }

    public function summary()
    {
        $page = intval(I('get.p', 1));
        $page = $page ? $page : 1; //默认显示第一页数据arraypage
        $row = intval(I('get.row', 10));
        $ownId = intval(I('own_id'), 0);//本账号
        $relationGameId = intval(I('relation_game_id', 0));
        $sdkVersion = intval(I('sdk_version', 0));
        $serverId = I('server_id', '');
        $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;
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);

        $parameter['relation_game_id'] = $relationGameId;
        $parameter['sdk_version'] = $sdkVersion;
        $parameter['server_id'] = $serverId;
        $parameter['level_promote_2'] = $levelPromote[0];
        $parameter['level_promote_3'] = $levelPromote[1];
        $parameter['level_promote_4'] = $levelPromote[2];
        $parameter['begtime'] = $initBegTime;
        $parameter['endtime'] = $initEndTime;
        $parameter['own_id'] = $ownId;
        $parameter['p'] = $page;
        $parameter['row'] = $row;

        $loginPromote = $this->getLoginPromote();

        $map = [];
        if ($ownId) {
            $map['a.promote_id'] = $queryPromote['id'];
            $params['promote_ids'] = $queryPromote['id'];
        } else {
            $map['chain'] = ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%'];
            $ids = M('promote', 'tab_')->where($map)->getField('id', true);
            $ids[] = $queryPromote['id'];

            $map = [];
            $map['a.promote_id'] = ['in', $ids];
            $params['promote_ids'] = $ids;
        }
        if ($relationGameId > 0) {
            $map['g.relation_game_id'] = $relationGameId;
        }
        if ($sdkVersion > 0) {
            $map['a.sdk_version'] = $sdkVersion;
        }
        $serverJoin = '';
        if (!empty($serverId)) {
            $serverJoin = 'tab_server as s on s.game_id = a.game_id';
            $map['s.server_id'] = $serverId;
            $params['server_id'] = $serverId;
        }

        $params['begin_time'] = $begTime;
        $params['end_time'] = $endTime - 1;

        $data = M('Apply', 'tab_')->alias('a')
            ->field('a.game_id,a.game_name,a.sdk_version')
            ->join('tab_game as g on g.id = a.game_id')
            ->join($serverJoin)
            ->where($map)
            ->group('a.game_id')
            ->order('g.sort desc,g.id desc')
            ->page($page, $row)
            ->select();
        $count = M('Apply', 'tab_')->alias('a')
            ->join('tab_game as g on g.id = a.game_id')
            ->join($serverJoin)
            ->where($map)
            ->count('distinct a.game_id');
        $allGameIs = M('Apply', 'tab_')->alias('a')
            ->field('distinct a.game_id')
            ->join('tab_game as g on g.id = a.game_id')
            ->join($serverJoin)
            ->where($map)
            ->select();
        $allGameIs = array_column($allGameIs, 'game_id');

        $records = [];
        $allData = [];
        if (!empty($data)) {
            if (intval($endTime - $begTime) / (24 * 3600) <= 31) {
                $gameIds = array_column($data, 'game_id');
                $params['game_ids'] = $gameIds;

                $userRepository = new UserRepository();
                $spendRepository = new SpendRepository();
                $roleNumList = $userRepository->getCreateRoleCountByGame($params);//创角数
                $userNumList = $userRepository->getCreateRoleUserCountByGame($params);//创角用户
                $newUserNumList = $userRepository->getNewCreateRoleUserCountByGame($params);//新创角用户
                $newDeviceNumList = $userRepository->getNewCreateRoleDeviceCountByGame($params);//新创角设备
                $newIpNumList = $userRepository->getNewCreateRoleIpCountByGame($params);//新创角IP
                $loginUserNumList = $userRepository->getLoginCountGroupByGame($params);//登录用户数
                if ($this->canViewUserRecharge) {
                    $spendUserNumList = $spendRepository->getPayUserCountGroupByGame($params);//充值人数
                    $spendNumList = $spendRepository->getPayCountGroupByGame($params);//充值次数
                    $spendAllAmountList = $spendRepository->getPayAmountGroupByGameAndType($params);//充值总额
                    $params['pay_way'] = ['in', '1,2,3,4,5,6'];
                    $spendCashList = $spendRepository->getPayAmountGroupByGameAndType($params);//现金充值
                    $params['pay_way'] = 0;
                    $spendGenericList = $spendRepository->getPayAmountGroupByGameAndType($params);//通用币充值
                    $params['pay_way'] = -1;
                    $spendBindingList = $spendRepository->getPayAmountGroupByGameAndType($params);//绑定币充值
                }
                foreach ($data as &$list) {
                    $gameId = $list['game_id'];
                    $record = [
                        'game_id' => $gameId,
                        'game_name' => $list['game_name'],
                        'sdk_version' => $list['sdk_version'],
                        'role_num' => $roleNumList[$gameId],
                        'user_num' => $userNumList[$gameId],
                        'new_user_num' => $newUserNumList[$gameId],
                        'new_device_num' => $newDeviceNumList[$gameId],
                        'new_ip_num' => $newIpNumList[$gameId],
                        'login_user_num' => $loginUserNumList[$gameId],
                    ];
                    if ($this->canViewUserRecharge) {
                        $record['spend_user_num'] = $spendUserNumList[$gameId];
                        $record['spend_num'] = $spendNumList[$gameId];
                        $record['spend_all_amount'] = $spendAllAmountList[$gameId];
                        $record['spend_cash'] = $spendCashList[$gameId];
                        $record['spend_generic'] = $spendGenericList[$gameId];
                        $record['spend_binding'] = $spendBindingList[$gameId];
                        $record['spend_discount'] = 0;
                        $record['spend_voucher'] = 0;
                    }

                    $records[] = $record;
                }
                $params['all_data'] = 1;
                $params['game_ids'] = $allGameIs;
                $allData['role_num'] = $userRepository->getCreateRoleCountByGame($params);//创角数
                $allData['user_num'] = $userRepository->getCreateRoleUserCountByGame($params);//创角用户
                $allData['new_user_num'] = $userRepository->getNewCreateRoleUserCountByGame($params);//新创角用户
                $allData['new_device_num'] = $userRepository->getNewCreateRoleDeviceCountByGame($params);//新创角设备
                $allData['new_ip_num'] = $userRepository->getNewCreateRoleIpCountByGame($params);//新创角IP
                $allData['login_user_num'] = $userRepository->getLoginCountGroupByGame($params);//登录用户数
                if ($this->canViewUserRecharge) {
                    $allData['spend_user_num'] = $spendRepository->getPayUserCountByGame($params);//充值人数
                    $allData['spend_num'] = $spendRepository->getPayCountByGame($params);//充值次数
                    unset($params['pay_way']);
                    $allData['spend_all_amount'] = null_to_0($spendRepository->getPayAmountByGameAndType($params));//充值总额
                    $params['pay_way'] = ['in', '1,2,3,4,5,6'];
                    $allData['spend_cash'] = null_to_0($spendRepository->getPayAmountByGameAndType($params));//现金充值
                    $params['pay_way'] = 0;
                    $allData['spend_generic'] = null_to_0($spendRepository->getPayAmountByGameAndType($params));//通用币充值
                    $params['pay_way'] = -1;
                    $allData['spend_binding'] = null_to_0($spendRepository->getPayAmountByGameAndType($params));//绑定币充值
                    $allData['spend_discount'] = '0.00';
                    $allData['spend_voucher'] = '0.00';
                }
            }
        }

        $serverData = $this->getServer($relationGameId, $sdkVersion);

        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('meta_title', '数据汇总列表');
        $this->assign('loginPromote', $loginPromote);
        $this->assign('ownId', $ownId);
        $this->assign('allData', $allData);
        $this->assign('listData', $records);
        $this->assign('count', $count);
        $this->assign('setdate', date("Y-m-d"));
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('serverData', $serverData['data']);
        $this->display();
    }

    public function dabiao_game()
    {

        if (isset($_REQUEST['game_id']) && !empty($_REQUEST['game_id'])) {
            $game_id = M('game', 'tab_')->field('id')->where(array('relation_game_id' => $_REQUEST['game_id']))->select();
            $game_id = array_map('array_shift', $game_id);
            $gmap['game_id'] = array('in', $game_id);
            //unset($_REQUEST['game_id']);
        }

        if (isset($_REQUEST['server_name']) && !empty($_REQUEST['server_name'])) {
            $dmap['server_name'] = $_REQUEST['server_name'];
            unset($_REQUEST['server_name']);
        }

        if (isset($_REQUEST['server_id']) && !empty($_REQUEST['server_id'])) {
            $dmap['server_id'] = $_REQUEST['server_id'];
            unset($_REQUEST['server_id']);
        }

        if (isset($_REQUEST['game_level']) && !empty($_REQUEST['game_level'])) {
            $gamedata = M('game', 'tab_')->field('first_level,first_level_name,second_level_name,second_level,third_level,third_level_name')->where(array('relation_game_id' => $_REQUEST['game_id']))->find();
            if ($gamedata['first_level_name'] == $_REQUEST['game_level']) {
                $dmap['role_level'] = array('egt', $gamedata['first_level']);
            } elseif ($gamedata['second_level_name'] == $_REQUEST['game_level']) {
                $dmap['role_level'] = array('egt', $gamedata['second_level']);
            } elseif ($gamedata['third_level_name'] == $_REQUEST['game_level']) {
                $dmap['role_level'] = array('egt', $gamedata['third_level']);
            }
            unset($_REQUEST['game_level']);
        }

        if (isset($_REQUEST['begtime']) && isset($_REQUEST['endtime']) && !empty($_REQUEST['begtime']) && !empty($_REQUEST['endtime'])) {
            $dmap['play_time'] = array('BETWEEN', [strtotime($_REQUEST['begtime']), strtotime($_REQUEST['endtime']) + 86400]);
            unset($_REQUEST['begtime']);
            unset($_REQUEST['endtime']);
        } elseif (isset($_REQUEST['begtime']) && !empty($_REQUEST['begtime'])) {
            $dmap['play_time'] = array('BETWEEN', [strtotime($_REQUEST['begtime']), date("Y-m-d", strtotime("-1 day"))]);
            unset($_REQUEST['begtime']);
        } elseif (isset($_REQUEST['endtime']) && !empty($_REQUEST['endtime'])) {
            $dmap['play_time'] = array('ELT', strtotime($_REQUEST['endtime']) + 86400);
            unset($_REQUEST['endtime']);
        }
        $promote = $_REQUEST['promote_id'];

        if (PID == $promote) {

        } else {

            $pids = get_prmoote_chlid_account($promote);
            $pro_arr = array_column($pids, 'id');
            $pro_arr[] = $promote;
            $promote = implode(',', $pro_arr);

        }

        $game = M('apply', 'tab_')
            ->field('game_id,game_name')
            ->where($gmap)
            ->where(array('promote_id' => array('in', $promote), 'status' => 1))
            ->group('game_id')
            ->select();
        $game_count = count($game);
        for ($y = 0; $y <= $game_count; $y++) {
            $game_level = M('game', 'tab_')->field('first_level')->where(array('id' => $game[$y]['game_id']))->find();
            if ($dmap['role_level']) {
                $game_level['first_level'] = $dmap['role_level'][1];
            }
            $gdabiao = M('user_play_info', 'tab_')
                ->field('user_id')
                ->where($dmap)
                ->where(array('game_id' => $game[$y]['game_id'], 'role_level' => array('egt', $game_level['first_level']), 'promote_id' => array('in', $promote)))
                ->group('user_id')
                ->select();
            $gdabiao = count($gdabiao);
            $game[$y]['num'] = $gdabiao;
            if ($game[$y]['num'] == 0) {
                unset($game[$y]);
            }
        }
        $this->assign('list_data', $game);
        $this->display();
    }

    private function map_game_list()
    {
        $uid = session('promote_auth.pid');
        $map['tab_game.game_status'] = 1;
        $map['tab_apply.status'] = 1;
        $promote = $this->get_child_promote();
        array_push($promote, $uid);
        $map['tab_promote.id'] = array('in', $promote);
        $data = M('game', 'tab_')
            ->field('relation_game_name,relation_game_id')
            ->join('tab_apply on tab_apply.game_id = tab_game.id')
            ->join('tab_promote ON tab_apply.promote_id = tab_promote.id')
            ->where($map)
            ->group('relation_game_id')
            ->select();
        $this->assign("game_list", $data);
    }

    public function getServerAjax()
    {
        $serverData = $this->getServer(I('relation_game_id'), I('sdk_version'));

        $this->ajaxReturn($serverData);
    }

    public function getServer($relationGameId, $sdkVersion)
    {
        $result['status'] = 0;
        $result['data'] = [];

        if (empty($relationGameId)) {
            return $result;
        }

        $map['relation_game_id'] = intval($relationGameId);
        empty($sdkVersion) || $map['sdk_version'] = intval($sdkVersion);

        $gameIds = M('Game', 'tab_')
            ->where($map)
            ->getField('id', true);

        if (empty($gameIds)) {
            return $result;
        }

        $gameIds = implode(',', $gameIds);
        $where['game_id'] = ['in', $gameIds];
        $where['show_status'] = 1;

        $serverData = M('Server', 'tab_')
            ->field('server_id,server_name')
            ->where($where)
            ->order('server_version,start_time desc')
            ->select();
        $result['status'] = 1;
        $result['data'] = $serverData;

        return $result;
    }

    public function get_child_promote()
    {
        $uid = session('promote_auth.pid');
        $map['parent_id'] = $uid;
        $map['status'] = 1;
        $data = M('promote', 'tab_')
            ->field('id')
            ->where($map)
            ->select();
        return array_map('array_shift', $data);
    }

    //查看角色详情
    public function viewRole($p = 0)
    {
        $promoteId = D('User')->where('id = %d', I('get.id'))->getField('promote_id');
        $permission = hasPromotePermission(PID, $promoteId);//是否有该推广员权限

        if ($permission === false) {
            $this->error('无推广员权限');
        }

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

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

        if (!empty(I('begtime')) && empty(I('endtime'))) {
            $map['tab_user_play_info.play_time'] = ['egt', strtotime(I('begtime'))];
        } elseif (empty(I('begtime')) && !empty(I('endtime'))) {
            $map['tab_user_play_info.play_time'] = ['elt', strtotime(I('endtime')) + 86399];
        } elseif (!empty(I('begtime')) && !empty(I('endtime'))) {
            $map['tab_user_play_info.play_time'] = ['between', [strtotime(I('begtime')), strtotime(I('endtime')) + 86399]];
        }

        empty(I('relation_game_id')) || $map['tab_game.relation_game_id'] = I('relation_game_id');
        empty(I('sdk_version')) || $map['tab_game.sdk_version'] = I('sdk_version');
        empty(I('server_id')) || $map['tab_user_play_info.server_id'] = I('server_id');
        empty(I('role_name')) || $map['tab_user_play_info.role_name'] = ['like', '%' . I('role_name') . '%'];
        $map['tab_user_play_info.user_id'] = I('get.id');
        $map['tab_user_play_info.promote_id'] = $promoteId;

        $data = M('user_play_info', 'tab_')
            ->field('tab_user_play_info.user_account,tab_user_play_info.game_name,tab_user_play_info.sdk_version,tab_user_play_info.create_time,tab_user_play_info.server_name,tab_user_play_info.role_name')
            ->join('tab_game on tab_user_play_info.game_id = tab_game.id')
            ->where($map)
            ->order('tab_user_play_info.id desc')
            ->page($page, $row)
            ->select();

        $count = M('user_play_info', 'tab_')
            ->where($map)
            ->join('tab_game on tab_user_play_info.game_id = tab_game.id')
            ->count();

        if (!empty($data)) {
            foreach ($data as &$list) {
                $list['user_account'] = substr($list['user_account'], 0, 2) . '******' . substr($list['user_account'], 8);
            }
        }

        //分页
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');
        $parameter['id'] = I('get.id');
        empty(I('relation_game_id')) || $parameter['relation_game_id'] = I('relation_game_id');
        empty(I('sdk_version')) || $parameter['sdk_version'] = I('sdk_version');
        empty(I('server_id')) || $parameter['server_id'] = I('server_id');
        empty(I('role_name')) || $parameter['role_name'] = I('role_name');
        empty(I('begtime')) || $parameter['begtime'] = I('begtime');
        empty(I('endtime')) || $parameter['endtime'] = I('endtime');

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

        $serverData = $this->getServer(I('relation_game_id'), I('sdk_version'));

        $this->assign('listData', $data);
        $this->assign('count', $count);
        $this->assign('setdate', date("Y-m-d"));
        $this->assign('serverData', $serverData['data']);
        $this->meta_title = '角色详情';
        $this->display('view_role');
    }

    private function getLevelPromote()
    {
        $levelPromote = [];
        $levelPromote[] = I('level_promote_2', 0);
        $levelPromote[] = I('level_promote_3', 0);
        $levelPromote[] = I('level_promote_4', 0);
        return $levelPromote;
    }

    private function getQueryPromote($levelPromote)
    {
        $queryPromote = null;
        $promote = $this->getLoginPromote();
        $queryPromoteId = 0;
        foreach ($levelPromote as $item) {
            if ($item != 0) {
                $queryPromoteId = $item;
            }
        }
        if ($queryPromoteId == 0) {
            $queryPromote = $this->getLoginPromote();
        } else {
            $queryPromote = M('promote', 'tab_')->where(['id' => $queryPromoteId])->find();
        }
        return $queryPromote;
    }

    public function userRoles()
    {
        $relationGameId = I('relation_game_id', 0);
        $serverId = I('server_id', 0);
        $isSelf = I('is_self', 0);
        $roleName = I('role_name', '');
        $userAccount = I('user_account', '');
        $promoteId = I('promote_id', 0);
        $sdkVersion = I('sdk_version', 0);
        $roleLevelBegin = intval(I('role_level_begin', 0));
        $roleLevelEnd = intval(I('role_level_end', 0));
        $headmanPromoteId = I('headman_promote_id', 0);
        $createTime = I('create_time', '');

        $promote = $this->getLoginPromote();
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);

        $map[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map)->getField('id', true);

        $map = [];
        if (count($ids) > 0) {
            $map = ['promote_id' => ['in', $ids]];
        } else {
            $map['_string'] = '1<>1';
        }

        if ($relationGameId != 0 || $sdkVersion != 0) {
            $gameIds = gameSearch($relationGameId, $sdkVersion);
            $map['game_id'] = ['in', $gameIds];
        }
        if ($serverId != 0) {
            $map['server_id'] = $serverId;
        }
        if ($roleName != '') {
            $map['role_name'] = ['like', '%' . $roleName . '%'];
        }
        if ($userAccount != '') {
            $map['user_account'] = ['like', '%' . $userAccount . '%'];
        }
        if ($roleLevelBegin != 0 && $roleLevelEnd == 0) {
            $map['role_level'] = ['egt', $roleLevelBegin];
        } elseif ($roleLevelEnd != 0 && $roleLevelBegin == 0) {
            $map['role_level'] = ['elt', $roleLevelEnd];
        } elseif ($roleLevelEnd != 0 && $roleLevelBegin != 0) {
            $map['role_level'] = ['between', [$roleLevelBegin, $roleLevelEnd]];
        }
        if ($createTime != '') {
            $createTimeRow = explode(' 至 ', $createTime);
            $createTimeBegin = 0;
            $createTimeEnd = 0;
            if (count($createTimeRow) == 2) {
                $createTimeBegin = strtotime($createTimeRow[0] . ' 00:00:00');
                $createTimeEnd = strtotime($createTimeRow[1] . ' 23:59:59');
            } else {
                $createTimeBegin = strtotime($createTimeRow[0] . ' 00:00:00');
                $createTimeEnd = strtotime($createTimeRow[0] . ' 23:59:59');
            }
            $map['create_time'] = ['between', [$createTimeBegin, $createTimeEnd]];
        }
        if ($isSelf) {
            $map['promote_id'] = $queryPromote['id'];
        }
        $query = M('user_play_info', 'tab_')->where($map)->order('create_time desc');
        list($records, $pagination, $count) = $this->paginate($query);
//        var_dump($records);die();
        foreach ($records as $key => $value) {

            //订单隐藏算法
            $orderLen = strlen($value['user_account']);
            $strLen = 3;
            $hideChar = '';

            if ($orderLen <= 8) {
                $strLen = 2;
            }

            for ($i = 0; $i < $orderLen - $strLen * 2; $i++) {
                $hideChar .= '*';
            }

            $records[$key]['user_account'] = substr($value['user_account'], 0, $strLen) . $hideChar . substr($value['user_account'], $orderLen - $strLen);

        }

        $games = get_promote_serach_game();

        $this->assign('games', $games);
        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->assign('count', $count);
        $this->display('userRoles');
    }

    public function userRecharges()
    {
        $relationGameId = I('relation_game_id', 0);
        $serverId = I('server_id', 0);
        $isSelf = I('is_self', 0);
        $roleName = I('role_name', '');
        $userAccount = I('user_account', '');
        $sdkVersion = I('sdk_version', 0);
        $costBegin = I('cost_begin', '');
        $costEnd = I('cost_end', '');
        $lastSortName = trim(I('last_sort_name', ''));
        $sortName = trim(I('sort_name', ''));
        $sort = intval(I('sort', 1));
        $sortNameData = ['recharge_cost', 'recharge_count', 'recharge_cost_today', 'unlogin_day', 'register_time', 'user_game_login_count'];
        $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;
        $nowTime = strtotime($nowTime);
        $nowTimeEnd = $nowTime + 3600 * 24 - 1;

        $promote = $this->getLoginPromote();
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);

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

            $map = ['s.promote_id' => ['in', $ids]];
            $map['s.pay_status'] = 1;

            if ($relationGameId != 0 || $sdkVersion != 0) {
                $gameIds = gameSearch($relationGameId, $sdkVersion);
                $map['s.game_id'] = ['in', $gameIds];
            }
            if ($serverId != 0) {
                $map['s.server_id'] = $serverId;
            }
            if ($roleName != '') {
                $map['s.game_player_name'] = ['like', $roleName . '%'];
            }
            if ($userAccount != '') {
                $map['s.user_account'] = ['like', $userAccount . '%'];
            }
            if ($isSelf) {
                $map['s.promote_id'] = $queryPromote['id'];
            }

            $having = '1 = 1';
            if ($costBegin != '' || $costEnd != '') {
                if ($costBegin != '' && $costEnd != '') {
                    $having = 'recharge_cost between ' . $costBegin . ' and ' . $costEnd;
                } elseif ($costBegin != '' && $costEnd == '') {
                    $having = 'recharge_cost >= ' . $costBegin;
                } elseif ($costBegin == '' && $costEnd != '') {
                    $having = 'recharge_cost <= ' . $costEnd;
                }
            }

            $orderBy = 'recharge_cost desc';
            if (!empty($sortName)) {
                if (in_array($sortName, $sortNameData)) {
                    $desc = ' desc';
                    $asc = ' asc';
                    if ($sortName == 'unlogin_day') {
                        $sortName = 'login_time';
                        $desc = ' asc';
                        $asc = ' desc';
                    }
                    if ($lastSortName == 'unlogin_day') {
                        $lastSortName = 'login_time';
                    }
                    if ($lastSortName != $sortName) {
                        $sortString = $desc;
                        $sort = 1;
                    } else {
                        $sortString = ($sort == 1) ? $desc : $asc;
                    }
                    $orderBy = $sortName . $sortString;
                }
            }

            $map['s.pay_time'] = ['between', [$begTime, $endTime - 1]];
            $fieldS = "sum(s.pay_amount) recharge_cost, count(*) recharge_count, s.user_id, s.user_account, s.promote_id, s.promote_account, s.game_name, s.sdk_version, s.server_name, SUBSTRING_INDEX(GROUP_CONCAT(s.game_player_name order by s.id desc), ',', 1) as game_player_name";
            $fieldUser = 'u.register_time, u.login_time';

            $spendMap['_string'] = 'today.user_id = s.user_id and today.game_id = s.game_id and today.server_id = s.server_id and today.game_player_id = s.game_player_id and today.promote_id = s.promote_id';
            $spendMap['today.pay_status'] = 1;
            $spendMap['today.pay_time'] = ['between', [$nowTime, $nowTimeEnd]];
            $fieldToday = M('spend', 'tab_')->alias('today')
                ->field('sum(pay_amount) as recharge_cost_today')
                ->where($spendMap)
                ->buildSql();

            $loginRecordMap['lr.create_time'] = $map['s.pay_time'];
            $loginRecordMap['_string'] = 'lr.user_id = s.user_id and lr.game_id = s.game_id';
            $fieldLR = M('login_daily_record', 'tab_')->alias('lr')
                ->field("count(*) as count")
                ->where($loginRecordMap)
                ->buildSql();
            $field = "$fieldS, $fieldUser, $fieldToday as recharge_cost_today, $fieldLR as user_game_login_count";
            $subQuery = M('spend', 'tab_')->alias('s')
                ->field($field)
                ->join('join tab_user as u on u.id = s.user_id')
                ->where($map)
                ->group('s.game_player_id, s.server_id, s.game_id, s.user_id')
                ->having($having)
                ->buildSql();
            $query = M()->alias('record')
                ->table($subQuery)
                ->order($orderBy);

            list($records, $pagination, $count) = $this->paginate($query);

            $total = M('spend', 'tab_')->alias('s')
                ->field($fieldS)
                ->where($map)
                ->find();
            $map['s.pay_time'] = $spendMap['today.pay_time'];
            $total['recharge_cost_today'] = M('spend', 'tab_')->alias('s')
                ->field('sum(s.pay_amount) as recharge_cost_today')
                ->where($map)
                ->find()['recharge_cost_today'];
            $total['recharge_cost_today'] = empty($total['recharge_cost_today']) ? '0.00' : $total['recharge_cost_today'];

            if (!empty($records)) {
                $promoteService = new PromoteService();
                $promoteIds = array_column($records, 'promote_id');
                $promotes = M('promote', 'tab_')->field(['id', 'chain', 'account'])->where(['id' => ['in', $promoteIds]])->select();
                $promotes = index_by_column('id', $promotes);
                foreach ($records as &$list) {
                    $list['user_account'] = empty($list['user_account']) ? '--' : encryption($list['user_account']);
                    $list['game_name'] = empty($list['game_name']) ? '--' : $list['game_name'];
                    $list['sdk_version'] = empty($list['sdk_version']) ? '--' : getSDKTypeName($list['sdk_version']);
                    $list['server_name'] = empty($list['server_name']) ? '--' : $list['server_name'];
                    $list['game_player_name'] = empty($list['game_player_name']) ? '--' : $list['game_player_name'];
                    $list['unlogin_day'] = empty($list['login_time']) ? '--' : intval((strtotime(date('Y-m-d 00:00:00')) - strtotime(date('Y-m-d 00:00:00', $list['login_time']))) / (24 * 3600));
                    $list['login_time'] = empty($list['login_time']) ? '--' : date('Y-m-d H:i:s', $list['login_time']);
                    $list['register_time'] = empty($list['register_time']) ? '--' : date('Y-m-d H:i:s', $list['register_time']);
                    $list['promote_account'] = empty($list['promote_account']) ? '--' : $list['promote_account'];
                    $list['promote_group'] = isset($promotes[$list['promote_id']]) ? $promoteService->getGroupNameByChain($promotes[$list['promote_id']]['chain'], $list['promote_id']) : '';
                    $list['recharge_cost_today'] = empty($list['recharge_cost_today']) ? '0.00' : $list['recharge_cost_today'];
                }
            }
        }
        $games = get_promote_serach_game();

        $this->assign('games', $games);
        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->assign('count', $count);
        $this->assign('total', $total);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('sort', $sort);
        $this->assign('setdate', date('Y-m-d', $nowTime));
        $this->meta_title = '充值玩家';
        $this->display('userRecharges');
    }

    private function getGamesByPromote($promote)
    {
        return M('apply', 'tab_')->field(['game_id', 'game_name'])->where(['promote_id' => $promote['id']])->select();
    }

    private function getGroupPromotes($promote)
    {
        $promotes = [];
        if ($promote['parent_id'] == 0) {
            $promotes = M('promote', 'tab_')->field(['id', 'account', 'real_name'])->where(['parent_id' => $promote['id']])->select();
        }
        return $promotes;
    }

    public function getGameServers()
    {
        $gameId = I('game_id', 0);
        $sdkVersion = I('sdk_version', 0);
        $servers = [];
        if (!empty($gameId)) {
            $map['relation_game_id'] = $gameId;
            if (in_array($sdkVersion, [1, 2])) {
                $map['sdk_version'] = $sdkVersion;
            }
            $gameIds = M('game', 'tab_')->where($map)->getField('id', true);
            $servers = M('server', 'tab_')->field(['id', 'server_id', 'server_name'])->where(['game_id' => ['in', $gameIds]])->group('server_id')->order('server_id asc')->select();
        }
        $this->ajaxReturn([
            'status' => 1,
            'msg' => '成功',
            'data' => ['servers' => $servers]
        ]);
    }

    public function getSubPromotes()
    {
        $promoteId = I('promote_id', 0) ?: -1;
        $promotes = M('promote', 'tab_')->field(['id', 'account', 'real_name', 'group_remark'])->where(['parent_id' => $promoteId])->select();
        $this->ajaxReturn([
            'status' => 1,
            'msg' => '成功',
            'data' => ['promotes' => $promotes]
        ]);
    }

    /**
     * [充值详细信息]
     * @param $id [充值id]
     */
    public function viewSpendDetailed($id)
    {
        $spendData = array();

        if ($id > 0) {
            $promoteId = D('Spend')->where('id = %d', $id)->getField('promote_id');
            $permission = hasPromotePermission(PID, $promoteId);//是否有该推广员权限

            if ($permission) {
                $map['id'] = $id;

                $spendData = D('Spend')->where($map)->find();
                $spendData['pay_status'] = ($spendData['pay_status'] == 1) ? '成功' : '失败';
            }
        }

        $this->assign('list_data', $spendData);
        $this->meta_title = "订单详情";
        $this->display('view_spend_detailed');
    }

    private function getBetweenTime($time, $defaultBegin = 0, $defaultEnd = 0)
    {
        $delimiter = ' 至 ';
        $begin = $defaultBegin;
        $end = $defaultEnd;
        if ($time != '') {
            if (strpos($time, $delimiter) == -1) {
                $begin = strtotime($time . ' 00:00:00');
                $end = strtotime($time . ' 23:59:59');
            } else {
                $timeRow = explode($delimiter, $time);
                $begin = strtotime($timeRow[0] . ' 00:00:00');
                $end = strtotime($timeRow[1] . ' 23:59:59');
            }
        }
        return [$begin, $end];
    }

    public function achievement()
    {
        $time = I('time', date('Y-m-d'));
        if (!empty($time)) {
            $defaultTime = $time;
        } else {
            $defaultTime = date('Y-m-d', time());
        }
        $sdkVersion = I('sdk_version', 0);
        $relationGameId = I('relation_game_id', 0);
        $serverId = I('server_id', 0);
        $parentId = I('parent_id', 0);
        $promoteId = I('promote_id', 0);
        $status = I('status', 0);
        $searchLevel = 0;
        $searchLevelName = '';
        $currentDisplay = '';
        $prevParentId = 0;

        $promoteService = new PromoteService();
        $loginPromote = $this->getLoginPromote();

        $parent = null;
        if ($parentId > 0) {
            $parent = M('promote', 'tab_')->where(['id' => $parentId])->find();
            $currentDisplay = $promoteService->getLevelName($parent['level']) . '推广';
            $prevParentId = $parent['parent_id'] == $loginPromote['parent_id'] ? 0 : $parent['parent_id'];
        } else {
            $parent = $loginPromote;
            $currentDisplay = '自己';
        }
        $searchLevel = $parent['level'] + 1;
        $searchLevelName = $promoteService->getLevelName($searchLevel);

        $games = get_promote_serach_game();

        $subPromotes = M('promote', 'tab_')->field(['id', 'account', 'real_name', 'group_remark'])->where(['parent_id' => $parent['id']])->select();

        $map = ['parent_id' => $parent['id']];
        if ($promoteId > 0) {
            $map['id'] = $promoteId;
        }

        $query = M('promote', 'tab_')->field(['id', 'account', 'real_name', 'level', 'chain'])->where($map);
        list($promotes, $pagination, $count) = $this->paginate($query);

        $ids = array_column($promotes, 'id');

        $rows = [];
        if (count($ids) > 0) {
            $rows = M('promote', 'tab_')
                ->field(['id', 'chain'])
                ->where(['chain' => ['like', [$parent['chain'] . $parent['id'] . '/%']], 'level' => ['gt', $parent['level'] + 1]])
                ->select();
        }

        $basicPromotes = [];
        foreach ($ids as $id) {
            foreach ($rows as $row) {
                $needChain = $parent['chain'] . $parent['id'] . '/' . $id . '/';
                if (strpos($row['chain'], $needChain) !== false) {
                    $basicPromotes[$row['id']] = $id;
                }
            }
        }
        $params = [
            'isContainSubs' => true,
            'basicPromotes' => $basicPromotes,
        ];
        if ($relationGameId != 0 || $sdkVersion != 0) {
            $gameIds = gameSearch($relationGameId, $sdkVersion);
            $params['game_id'] = ['in', $gameIds];
        }
        if ($serverId > 0) {
            $params['server_id'] = $serverId;
        }
        if ($status > 0) {
            $params['lock_status'] = $status;
        }
        list($beginTime, $endTime) = $this->getBetweenTime($time);
        $params['begin_time'] = $beginTime;
        $params['end_time'] = $endTime;

        $timeout = 0;
        $records = [];
        if (intval($endTime - $beginTime) / (24 * 3600) <= 7) {
            $promoteRepository = new PromoteRepository();
            $createRoleCountList = $promoteRepository->getCreateRoleCountByIds($ids, $params);
            $createRoleUserCountList = $promoteRepository->getCreateRoleUserCountByIds($ids, $params);
            $newCreateRoleUserCountList = $promoteRepository->getNewCreateRoleUserCountByIds($ids, $params);
            // $newCreateRoleDeviceCountList = $promoteRepository->getNewCreateRoleDeviceCountByIds($ids, $params);
            $newCreateRoleIpCountList = $promoteRepository->getNewCreateRoleIpCountByIds($ids, $params);
            $loginUserCountList = $promoteRepository->getLoginUserCountByIds($ids, $params);
            
            $rechargeCountList = [];
            $rechargeUserCountList = [];
            $rechargeAmountList = [];
            if ($this->canViewUserRecharge) {
                $rechargeCountList = $promoteRepository->getRechargeCountByIds($ids, $params);
                $rechargeUserCountList = $promoteRepository->getRechargeUserCountByIds($ids, $params);
                $rechargeAmountList = $promoteRepository->getRechargeAmountByIds($ids, $params);
            }

            $promoteService = new PromoteService();

            if (I('p', 1) == 1) {
                $selfParams = $params;
                $selfParams['isContainSubs'] = false;
                $selfCreateRoleCountList = $promoteRepository->getCreateRoleCountByIds([$parent['id']], $selfParams);
                $selfCreateRoleUserCountList = $promoteRepository->getCreateRoleUserCountByIds([$parent['id']], $selfParams);
                $selfNewCreateRoleUserCountList = $promoteRepository->getNewCreateRoleUserCountByIds([$parent['id']], $selfParams);
                // $selfNewCreateRoleDeviceCountList = $promoteRepository->getNewCreateRoleDeviceCountByIds([$parent['id']], $selfParams);
                $selfNewCreateRoleIpCountList = $promoteRepository->getNewCreateRoleIpCountByIds([$parent['id']], $selfParams);
                $selfLoginUserCountList = $promoteRepository->getLoginUserCountByIds([$parent['id']], $selfParams);
                $record = [
                    'id' => $parent['id'],
                    'account' => $parent['account'],
                    'promote_group' => $promoteService->getGroupNameByChain($parent['chain'], $parent['id']),
                    'real_name' => hideRealName($parent['real_name']),
                    'level' => $parent['level'],
                    'create_role_count' => $selfCreateRoleCountList[$parent['id']],
                    'create_role_user_count' => $selfCreateRoleUserCountList[$parent['id']],
                    'new_create_role_user_count' => $selfNewCreateRoleUserCountList[$parent['id']],
                    // 'new_create_role_device_count' => $selfNewCreateRoleDeviceCountList[$parent['id']],
                    'new_create_role_ip_count' => $selfNewCreateRoleIpCountList[$parent['id']],
                    'login_user_count' => $selfLoginUserCountList[$parent['id']],
                    'current_display' => $currentDisplay,
                ];
                if ($this->canViewUserRecharge) {
                    $selfRechargeCountList = $promoteRepository->getRechargeCountByIds([$parent['id']], $selfParams);
                    $selfRechargeUserCountList = $promoteRepository->getRechargeUserCountByIds([$parent['id']], $selfParams);
                    $selfRechargeAmountList = $promoteRepository->getRechargeAmountByIds([$parent['id']], $selfParams);
                    $record['recharge_count'] = $selfRechargeCountList[$parent['id']];
                    $record['recharge_user_count'] = $selfRechargeUserCountList[$parent['id']];
                    $record['recharge_amount'] = $selfRechargeAmountList[$parent['id']]['ban_coin'] + $selfRechargeAmountList[$parent['id']]['coin'] + $selfRechargeAmountList[$parent['id']]['cash'];
                    $record['recharge_by_ban_coin'] = $selfRechargeAmountList[$parent['id']]['ban_coin'];
                    $record['recharge_by_coin'] = $selfRechargeAmountList[$parent['id']]['coin'];
                    $record['recharge_by_cash'] = $selfRechargeAmountList[$parent['id']]['cash'];
                }
                $records[] = $record;
            }
            foreach ($promotes as $promote) {
                $id = $promote['id'];
                $record = [
                    'id' => $id,
                    'account' => $promote['account'],
                    'promote_group' => $promoteService->getGroupNameByChain($promote['chain'], $promote['id']),
                    'real_name' => hideRealName($promote['real_name']),
                    'level' => $promote['level'],
                    'create_role_count' => $createRoleCountList[$id],
                    'create_role_user_count' => $createRoleUserCountList[$id],
                    'new_create_role_user_count' => $newCreateRoleUserCountList[$id],
                    // 'new_create_role_device_count' => $newCreateRoleDeviceCountList[$id],
                    'new_create_role_ip_count' => $newCreateRoleIpCountList[$id],
                    'login_user_count' => $loginUserCountList[$id],
                    'current_display' => '',
                ];
                if ($this->canViewUserRecharge) {
                    $record['recharge_count'] = $rechargeCountList[$id];
                    $record['recharge_user_count'] = $rechargeUserCountList[$id];
                    $record['recharge_amount'] = $rechargeAmountList[$id]['ban_coin'] + $rechargeAmountList[$id]['coin'] + $rechargeAmountList[$id]['cash'];
                    $record['recharge_by_ban_coin'] = $rechargeAmountList[$id]['ban_coin'];
                    $record['recharge_by_coin'] = $rechargeAmountList[$id]['coin'];
                    $record['recharge_by_cash'] = $rechargeAmountList[$id]['cash'];
                }
                $records[] = $record;
            }
        } else {
            $timeout = 1;
        }

        $this->assign('prevParentId', $prevParentId);
        $this->assign('searchLevelName', $searchLevelName);
        $this->assign('games', $games);
        $this->assign('parent', $parent);
        $this->assign('subPromotes', $subPromotes);
        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->assign('parentid', $parentId);
        $this->assign('count', $count);
        $this->assign('timeout', $timeout);
        $this->assign('time', $defaultTime);
        $this->display();
    }

    public function getChildPromoteList()
    {
        $promoteId = intval(I('post . promote_id', 0));
        $promoteId = empty($promoteId) ? PID : $promoteId;
        $promoteList = getAllPromoteListByType(3, false, $promoteId);
        $data['status'] = 1;
        $data['data'] = $promoteList;

        $this->ajaxReturn($data);
    }

    //推广员指标管理
    public function promoteQuota()
    {
        $nowTime = date('Y-m-d', time());
        $defaultTime = date('Y-m-d', strtotime('-6 day', time())) . " 至 " . $nowTime;
        $time = I('time', $defaultTime);
        if (!empty($time)) {
            $defaultTime = $time;
        }
        $sdkVersion = I('sdk_version', 0);
        $relationGameId = I('relation_game_id', 0);
        $serverId = I('server_id', 0);
        $parentId = I('get.parent_id', 0);
        $promoteId = I('promote_id', 0);
        $levelBegin = I('level_begin', '');
        $levelEnd = I('level_end', '');
        $prevParentId = 0;

        $promoteService = new PromoteService();
        $loginPromote = $this->getLoginPromote();

        $parent = null;
        if ($parentId > 0) {
            $parent = M('promote', 'tab_')->where(['id' => $parentId])->find();
            $currentDisplay = $promoteService->getLevelName($parent['level']) . '推广';
            $prevParentId = $parent['parent_id'] == $loginPromote['parent_id'] ? 0 : $parent['parent_id'];
        } else {
            $parent = $loginPromote;
            $currentDisplay = '自己';
        }
        $searchLevel = $parent['level'] + 1;
        $searchLevelName = $promoteService->getLevelName($searchLevel);

        $games = get_promote_serach_game();

        $subPromotes = M('promote', 'tab_')->field(['id', 'account', 'real_name'])->where(['parent_id' => $parent['id']])->select();

        $map = ['parent_id' => $parent['id']];
        if ($promoteId > 0) {
            $map['id'] = $promoteId;
        }

        $query = M('promote', 'tab_')->field(['id', 'account', 'real_name', 'level'])->where($map);
        list($promotes, $pagination, $count) = $this->paginate($query);
        $ids = array_column($promotes, 'id');

        $rows = [];
        if (count($ids) > 0) {
            $rows = M('promote', 'tab_')
                ->field(['id', 'chain'])
                ->where(['chain' => ['like', [$parent['chain'] . $parent['id'] . '/%']], 'level' => ['gt', $parent['level'] + 1]])
                ->select();
        }

        $basicPromotes = [];
        foreach ($ids as $id) {
            foreach ($rows as $row) {
                $needChain = $parent['chain'] . $parent['id'] . '/' . $id . '/';
                if (strpos($row['chain'], $needChain) !== false) {
                    $basicPromotes[$row['id']] = $id;
                }
            }
        }
        $params = [
            'isContainSubs' => true,
            'basicPromotes' => $basicPromotes,
        ];
        if ($relationGameId != 0 || $sdkVersion != 0) {
            $gameIds = gameSearch($relationGameId, $sdkVersion);
            $params['game_id'] = ['in', $gameIds];
        }
        if ($serverId > 0) {
            $params['server_id'] = $serverId;
        }
        $where = $params;
        if ($sdkVersion != 0) {
            $where['sdk_version'] = $sdkVersion;
        }
        $game = $this->getGame($where);

        if ($levelBegin !== '' || $levelEnd !== '') {
            if ($levelBegin !== '' && $levelEnd !== '') {
                $levelBegin = intval($levelBegin);
                $levelEnd = intval($levelEnd);
                if ($levelBegin > $levelEnd) {
                    $this->error('角色等级范围错误');
                }
                $params['role_level'] = ['between', [$levelBegin, $levelEnd]];
            } elseif ($levelBegin !== '' && $levelEnd === '') {
                $levelBegin = intval($levelBegin);
                $params['role_level'] = ['egt', $levelBegin];
            } elseif ($levelBegin === '' && $levelEnd !== '') {
                $levelEnd = intval($levelEnd);
                $params['role_level'] = ['elt', $levelEnd];
            }
        }
        list($beginTime, $endTime) = $this->getBetweenTime($time);
        $params['begin_time'] = $beginTime;
        $params['end_time'] = $endTime;

        $records = [];
        $promoteRepository = new PromoteRepository();
        $createRoleCountList = $promoteRepository->getCreateRoleCountByIds($ids, $params);

        if (I('p', 1) == 1 && empty($promoteId)) {
            $selfParams = $params;
            $selfParams['isContainSubs'] = false;
            $selfCreateRoleCountList = $promoteRepository->getCreateRoleCountByIds([$parent['id']], $selfParams);
            $record = [
                'id' => $parent['id'],
                'account' => $parent['account'],
                'real_name' => mb_strlen($parent['real_name'],'utf-8') == 2 ? mb_substr($parent['real_name'],0,1,'utf-8').'*':mb_substr($parent['real_name'],0,1,'utf-8').'**',
                'level' => $parent['level'],
                'game_name' => $game['game_name'],
                'sdk_version_text' => $game['sdk_version_text'],
                'server_name' => $game['server_name'],
                'role_num' => $selfCreateRoleCountList[$parent['id']],
                'current_display' => $currentDisplay,
            ];
            $records[] = $record;
        }
        foreach ($promotes as $promote) {
            $id = $promote['id'];
            $record = [
                'id' => $id,
                'account' => $promote['account'],
                'real_name' => mb_strlen($promote['real_name'],'utf-8') == 2 ? mb_substr($promote['real_name'],0,1,'utf-8').'*':mb_substr($promote['real_name'],0,1,'utf-8').'**',
                'level' => $promote['level'],
                'game_name' => $game['game_name'],
                'sdk_version_text' => $game['sdk_version_text'],
                'server_name' => $game['server_name'],
                'role_num' => $createRoleCountList[$id],
                'current_display' => '',
            ];
            $records[] = $record;
        }

        $this->assign('prevParentId', $prevParentId);
        $this->assign('searchLevelName', $searchLevelName);
        $this->assign('games', $games);
        $this->assign('parent', $parent);
        $this->assign('subPromotes', $subPromotes);
        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->assign('parentId', $parentId);
        $this->assign('count', $count);
        $this->assign('time', $defaultTime);
        $this->assign('meta_title', '推广员指标');
        $this->display();
    }

    public function quotaDtl()
    {
        $nowTime = date('Y-m-d', time());
        $defaultTime = date('Y-m-d', strtotime('-6 day', time())) . " 至 " . $nowTime;
        $time = I('time', $defaultTime);
        $relationGameId = I('relation_game_id', 0);
        $sdkVersion = I('sdk_version', 0);
        $serverId = I('server_id', 0);
        $roleLevelBegin = intval(I('level_begin', 0));
        $roleLevelEnd = intval(I('level_end', 0));
        $promoteId = I('promote_id', 0);
        $isSelf = I('is_self', 0);

        if ($relationGameId != 0 || $sdkVersion != 0) {
            $gameIds = gameSearch($relationGameId, $sdkVersion);
            $map['game_id'] = ['in', $gameIds];
        }
        if ($serverId != 0) {
            $map['server_id'] = $serverId;
        }
        if ($roleLevelBegin != 0 && $roleLevelEnd == 0) {
            $map['role_level'] = ['egt', $roleLevelBegin];
        } elseif ($roleLevelEnd != 0 && $roleLevelBegin == 0) {
            $map['role_level'] = ['elt', $roleLevelEnd];
        } elseif ($roleLevelEnd != 0 && $roleLevelBegin != 0) {
            $map['role_level'] = ['between', [$roleLevelBegin, $roleLevelEnd]];
        }
        list($beginTime, $endTime) = $this->getBetweenTime($time);
        $map['create_time'] = ['between', [$beginTime, $endTime]];
        if ($promoteId) {
            if ($isSelf) {
                $map['promote_id'] = $promoteId;
            } else {
                $promote = M('promote', 'tab_')->field(['id', 'chain'])->where(array('id' => $promoteId))->find();
                $promoteMap['chain'] = ['like', "{$promote['chain']}{$promote['id']}/%"];
                $promoteIds = M('promote', 'tab_')->where($promoteMap)->getField('id', true);
                $promoteIds[] = $promoteId;
                $map['promote_id'] = ['in', $promoteIds];
            }
        } else {
            $map = '1 = 2';
        }

        $query = M('user_play_info', 'tab_')->where($map)->order('create_time desc');
        list($records, $pagination, $count) = $this->paginate($query);
        foreach ($records as $key => $value) {
            //订单隐藏算法
            $orderLen = strlen($value['user_account']);
            $strLen = 3;
            $hideChar = '';

            if ($orderLen <= 8) {
                $strLen = 2;
            }

            for ($i = 0; $i < $orderLen - $strLen * 2; $i++) {
                $hideChar .= '*';
            }

            $records[$key]['user_account'] = substr($value['user_account'], 0, $strLen) . $hideChar . substr($value['user_account'], $orderLen - $strLen);
        }

        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->assign('count', $count);
        $this->display();
    }

    private function getGame($map = [])
    {
        $gameName = '全部游戏';
        $sdkVersionText = getSDKTypeName(0, true);
        $serverName = '--';
        if (isset($map['game_id']) || isset($map['sdk_version'])) {
            $where = [];
            if (!isset($map['game_id'])) {
                $sdkVersionText = getSDKTypeName($map['sdk_version'], true);
            } elseif (!isset($map['sdk_version'])) {
                $where['id'] = $map['game_id'];
                $gameName = M('game', 'tab_')->where($where)->getField('relation_game_name');
                if (isset($map['server_id'])) {
                    $serverName = $this->getServerName($map['game_id'], 0, $map['server_id']);
                }
            } else {
                $where['id'] = $map['game_id'];
                $where['sdk_version'] = $map['sdk_version'];
                $gameName = M('game', 'tab_')->where($where)->getField('game_name');
                $sdkVersionText = getSDKTypeName($map['sdk_version'], true);
                if (isset($map['server_id'])) {
                    $serverName = $this->getServerName($map['game_id'], $map['sdk_version'], $map['server_id']);
                }
            }
        }

        $game = [
            'game_name' => $gameName,
            'sdk_version_text' => $sdkVersionText,
            'server_name' => $serverName,
        ];
        return $game;
    }

    private function getServerName($gameIds, $serverVersion, $serverId)
    {
        $map['_string'] = '1 = 1';
        if ($gameIds) {
            $map['game_id'] = $gameIds;
        }
        if ($serverVersion) {
            $map['server_version'] = $serverVersion;
        }
        if ($serverId) {
            $map['server_id'] = $serverId;
        }
        return M('server', 'tab_')->where($map)->getField('server_name');
    }

    public function iosDownLoadData() {
        $page = intval(I('get.p', 1));
        $page = $page ? $page : 1; //默认显示第一页数据arraypage
        $row = intval(I('get.row', 10));
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
        $localId = $queryPromote['id'];
        $loginPromote = $this->getLoginPromote();
        $map = [];
        if ($queryPromote['level'] == 4) {
            $map['id'] = $queryPromote['id'];
        }else {
            $map['chain'] = ['like', $queryPromote['chain'] . $queryPromote['id'] . '%'];
        }
        $iostime = time();
        $sunday = strtotime('-1 sunday', $iostime) + 24 * 3600;
        if (I('begtime') && I('endtime')) {
            $iostime = strtotime(I('endtime'));
        }
        $iosTimeMap['register_time'] = ['between', [$sunday, $iostime]];
        $createTime = I('create_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 += 3600 * 24;
        $tfMap['create_time'] = ['between', [$begTime, $endTime]];
        $companyMap['create_time'] = ['between', [$begTime, $endTime]];
        $superMap['create_time'] = ['between', [$begTime, $endTime]];
        $map10['register_time'] = ['between', [$begTime, $endTime]];
        //var_dump($map);die();
        $query = M('promote', 'tab_')->field(['id'])->where($map);
        list($promotes, $pagination, $count) = $this->paginate($query);
        $ids = array_column($promotes, 'id');
        if ($localId !== PID && !in_array($localId, $ids)) {
            array_push($ids, $localId);
        }
        if ($page == 1 && !in_array(PID, $ids)) {
            array_push($ids, PID);
        }
        $allPromote = M('promote', 'tab_')->field(['id'])->where($map)->select();
        $allids = array_column($allPromote, 'id');
        if ($localId !== PID) {
            array_push($allids, $localId);
        }
        array_push($allids, PID);
        $map = [];
        $map['tab_package_download_log.promote_id'] = ['in', $ids];

      //  $data = M('package_download_log','tab_')->where($map)->select();
        $listData = [];
        $allUserMap['promote_id'] = ['in', $allids];
        $allUserMap['device_type'] = 2;
        $allUserMap['register_time'] = ['between', [$begTime, $endTime]];
        $allTFMap['promote_id'] = ['in', $allids]; 
        $allTFMap['type'] = 2;
        $allTFMap['create_time'] = ['between', [$begTime, $endTime]];
        $allSuperMap['promote_id'] = ['in', $allids]; 
        $allSuperMap['type'] = 3;
        $allSuperMap['create_time'] = ['between', [$begTime, $endTime]];
        $companyMap['promote_id'] = ['in', $allids]; 
        $companyMap['type'] = 1;
        $companyMap['create_time'] = ['between', [$begTime, $endTime]];
        $alliosMap['promote_id'] = ['in', $allids];
        $alliosMap['device_type'] = 2;
        $alliosMap['register_time'] = ['between', [$sunday, $iostime]];
        $allUsersCounts = M('user', 'tab_')->where($allUserMap)->count();
        $allIosCounts = M('user', 'tab_')->where($alliosMap)->count();
        
        $allTFCounts = M('package_download_log', 'tab_')->where($allTFMap)->count();
        $allSuperCounts = M('package_download_log', 'tab_')->where($allSuperMap)->count();
        $allCompanyCounts = M('package_download_log', 'tab_')->where($companyMap)->count();
        
        foreach ($ids as $key => $id) {
            $promote1 = M('promote', 'tab_')->field('account, level, parent_id, chain')->where(['id' => $id])->select();
            $promote = $promote1[0];
            $chain = $promote['chain'];
            $listData[$key]['promote_id'] = $id;
            if($id == PID) {
                $listData[$key]['account'] = $promote['account'].'<span style="color:blue;">'.'['.'自己'.']'.'</span>';
            }else {
                $listData[$key]['account'] = $promote['account'];
            }
            $iosTimeMap['promote_id'] = $id;
            $iosTimeMap['device_type'] = 2;
            $iosCount = M('user', 'tab_')->where($iosTimeMap)->count();
            $listData[$key]['ioscount'] = $iosCount;
            $tfMap['promote_id'] = $id;
            $tfMap['type'] = 2;
            $companyMap['promote_id'] = $id;
            $companyMap['type'] = 1;
            $superMap['promote_id'] = $id;
            $superMap['type'] = 3;
            $tfCounts = M('package_download_log', 'tab_')->where($tfMap)->count();   //TF下载量
            $companyCounts = M('package_download_log', 'tab_')->where($companyMap)->count();   //企业签下载量
            $superCounts = M('package_download_log', 'tab_')->where($superMap)->count();   //超级签下载量
            $listData[$key]['companycounts'] = intval($companyCounts);
            $listData[$key]['supercounts'] = intval($superCounts);
            $map10['promote_id'] = $id;
            $map10['device_type'] = 2;
            $usersCounts = M('user', 'tab_')->where($map10)->count();
            $listData[$key]['userscounts'] = intval($usersCounts);
            $listData[$key]['tfcounts'] = intval($tfCounts);
            $listData[$key]['tfpercent'] = number_format((intval($tfCounts) / intval($usersCounts)),2,'.','') * 100; 

            if (intval($usersCounts) == 0) {
                $listData[$key]['tfpercent'] = 0; 
            }
            if($promote['level'] == 1) {
                $listData[$key]['belongs_president'] = $promote['account'];
                $listData[$key]['belongs_department'] = "无所属部门长";
                $listData[$key]['belongs_group'] = "无所属组长";
            }
            if ($promote['level'] == 2) {
                $parentPromote = M('promote', 'tab_')->field('account')->where(['id'=>$promote['parent_id']])->select();
                $listData[$key]['belongs_president'] = $parentPromote[0]['account'];
                $listData[$key]['belongs_department'] = $promote['account'];
                $listData[$key]['belongs_group'] = "无所属组长";
            }
            if ($promote['level'] == 3) {
               $chainArr = explode('/', $chain);
               $presidentAccount = M('promote', 'tab_')->where(['id' => $chainArr[1]])->getField('account');
               $departmentAccount = M('promote', 'tab_')->where(['id' => $chainArr[2]])->getField('account');
               $listData[$key]['belongs_president'] = $presidentAccount;
               $listData[$key]['belongs_department'] = $departmentAccount;
               $listData[$key]['belongs_group'] = $promote['account'];
            }

            if ($promote['level'] == 4) {
               $chainArr = explode('/', $chain);
               $presidentAccount = M('promote', 'tab_')->where(['id' => $chainArr[1]])->getField('account');
               $departmentAccount = M('promote', 'tab_')->where(['id' => $chainArr[2]])->getField('account');
               $groupAccount = M('promote', 'tab_')->where(['id' => $chainArr[3]])->getField('account');
               $listData[$key]['belongs_president'] = $presidentAccount;
               $listData[$key]['belongs_department'] = $departmentAccount;
               $listData[$key]['belongs_group'] = $groupAccount;
            }
        }
        $totalpercent =  number_format($allTFCounts/$allUsersCounts,2,'.','') * 100; 
        if ($allUsersCounts == 0) {
            $totalpercent = '0';
        }
        $this->assign('totalpercent', $totalpercent);
        $this->assign('listdata', $listData);
        $this->assign('totaluserscounts', $allUsersCounts);
        $this->assign('totaltfcounts', $allTFCounts);
        $this->assign('totalsupercounts', $allSuperCounts);
        $this->assign('pagination', $pagination);
        $this->assign('totalcompanycounts', $allCompanyCounts);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->assign('allIosCounts', $allIosCounts);
        $this->assign('tfpercent', $tfpercent);
        $this->display();
    }

    public function iosDownLoadDetail() {
       $promote_id = $_REQUEST['promote_id'];
       $belongs_president = $_REQUEST['belongs_president'];
       $belongs_department = $_REQUEST['belongs_department'];
       $belongs_group = $_REQUEST['belongs_group'];
      // $createTime = I('create_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 += 3600 * 24;

       $map['create_time'] = ['between', [$begTime, $endTime]];
       $tfMap['create_time'] = ['between', [$begTime, $endTime]];
       $superMap['create_time'] = ['between', [$begTime, $endTime]];
       $companyMap['create_time'] = ['between', [$begTime, $endTime]];
        
       if(!empty(I('user_account'))) {
           $user_id = M('user', 'tab_')->where(['account'=>I('user_account')])->getField('id');
           $map['user_id'] = $user_id;
           $tfMap['user_id'] = $user_id;
           $superMap['user_id'] = $user_id;
           $companyMap['user_id'] = $user_id;
       }
       if(!empty(I('type'))) {
           $map['type'] = I('type');
           
       }
       $map['promote_id'] = $promote_id;
        //$packAges = M('package_download_log', 'tab_')->field('id,game_id,user_id,type,create_time')->where(['promote_id'=>$promote_id])->select();
       $query = M('package_download_log', 'tab_')->field('id,game_id,user_id,type,create_time')->where($map);
       list($packAges, $pagination, $count) = $this->paginate($query);
        foreach ($packAges as $key =>$package) {
            $user_id = $package['user_id'];
            $usersAccount = M('user', 'tab_')->where(['id' => $user_id])->getField('account');
            $packAges[$key]['account'] = $usersAccount;
            if ($package['type'] == 1) {
                $packAges[$key]['typename'] = "企业签下载";
            }
            if($package['type'] == 2) {
                $packAges[$key]['typename'] = "TF下载";
            }
            if($package['type'] == 3) {
                $packAges[$key]['typename'] = "超级签下载";
            }
            $packAges[$key]['create_time'] = date('Y-m-d H:i:s', $package['create_time']);
            $promoteInfo = M('promote', 'tab_')->field('account')->where(['id'=>$promote_id])->find();
            $packAges[$key]['promote_account'] = $promoteInfo['account'];
            $packAges[$key]['belongs_president'] = $belongs_president;
            $packAges[$key]['belongs_department'] = $belongs_department;
            $packAges[$key]['belongs_group'] = $belongs_group;
            $packAges[$key]['account'] = encryption($packAges[$key]['account']);

        }
        $tfMap['promote_id'] = $promote_id;
        $tfMap['type'] = 2; 
        $TFCounts = M('package_download_log', 'tab_')->where($tfMap)->count();

        $superMap['promote_id'] = $promote_id;
        $superMap['type'] = 3;
        $superCounts = M('package_download_log', 'tab_')->where($superMap)->count();
        
        $companyMap['promote_id'] = $promote_id;
        $companyMap['type'] = 1;
        $companyCounts = M('package_download_log', 'tab_')->where($companyMap)->count();
        $this->assign('promote_id', $promote_id);
        $this->assign('TFCounts', $TFCounts);
        $this->assign('superCounts', $superCounts);
        $this->assign('companyCounts', $companyCounts);
        $this->assign('belongs_president', $belongs_president);
        $this->assign('belongs_department', $belongs_department);
        $this->assign('belongs_group', $belongs_group);
        $this->assign('pagination', $pagination);
        $this->assign('datas', $packAges);
        $this->assign('initBegTime', $initBegTime);
        $this->assign('initEndTime', $initEndTime);
        $this->display();
    }
}