<?php

namespace Admin\Controller;

use Sdk\Controller\AgeController;
use Think\Log;
use User\Api\MemberApi as MemberApi;
use Org\WeixinSDK\Weixin;

class MemberController extends ThinkController
{
    /**
     *玩家列表信息
     */
    public function user_info($p=0){
        //设定默认时间
        if(!array_key_exists("time_start",$_REQUEST) && I('type') != 2){
            $this->redirect(ACTION_NAME, array('time_start' => date('Y-m-d',strtotime('-30 day')),"time_end"=>date('Y-m-d')));
        }
         //基础信息
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }
       
        //累计充值,账户平台币排序
        $order = '';
        if (I('key') == 1) {
            if (I('balance_status') == 1) {
                $order = 'balance,';
            } elseif (I('balance_status') == 2) {
                $order = 'balance desc,';
            }
        } else {
            if (I('recharge_status') == 1) {
                $order .= 'recharge_total,';
            } elseif (I('recharge_status') == 2) {
                $order .= 'recharge_total desc,';
            }
        }
        $order .= 'tab_user.id desc';
        //1条件筛选
        $map = [];
        $map['puid'] = array('eq', 0);
        $map['is_platform'] = 0;
        $havs=false;
        //1.1 user表相关
        if (isset($_REQUEST['user_id'])) {
            $map['tab_user.id'] = $_REQUEST['user_id'];
        }
        if (isset($_REQUEST['account'])) {
            $map['tab_user.account'] = ['like',I('account') . "%"];
        }
        if (isset($_REQUEST['time_start']) && isset($_REQUEST['time_end'])) {
            $map['tab_user.register_time'] = ['between', [strtotime(I('time_start')), strtotime(I('time_end')) + 86399]];
        } elseif (isset($_REQUEST['time_start'])) {
            $map['tab_user.register_time'] = ['GT', strtotime(I('time_start'))];
        } elseif (isset($_REQUEST['time_end'])) {
            $map['tab_user.register_time'] = ['LT', strtotime(I('time_end')) + 86399];
        }

        if (isset($_GET['register_way'])) {
            $map['tab_user.register_type'] = $_GET['register_way'];
        }else{
            if (I('type', 1) == 1) {
                $map['tab_user.register_type'] = ['not in', [0, 3, 4, 5, 6]];
            }else{
                $map['tab_user.register_type'] = ['in', [0, 3, 4, 5, 6]];
            }
        }


        if (isset($_REQUEST['status'])) {
            $map['lock_status'] = $_REQUEST['status'];
        }
        if (isset($_REQUEST['viplevel'])) {
            $havs = get_vip_level_limit('recharge_total', $_REQUEST['viplevel']);
        }
        //1.2 与游戏相关 查询游戏玩家表
        $gameplay =false;
        if (isset($_REQUEST['game_name']) || isset($_REQUEST['game_type'])) {
            $gameplay = " and tab_user_play.game_id in (" . implode(',', array_column(getGameByName($_REQUEST['game_name'], $_REQUEST['game_type']), 'id')) . ")";
        }
        //查询游戏角色表
        $game_map = false;
        if (isset($_REQUEST['server_id'])) { //有区服,一定有游戏
            $gameplay =false;
            $game_map = " and tab_user_play_info.server_id = '{$_REQUEST['server_id']}' ";
            $game_map .= " and tab_user_play_info.game_id in (" . implode(',', array_column(getGameByName($_REQUEST['game_name'], $_REQUEST['game_type']), 'id')) . ")";
            
        }
        //查询设备号
        if (isset($_REQUEST['device_number'])) {
            $map['tab_user.device_number'] = $_REQUEST['device_number'];
        }
        $promoteRoot = getPowerPromoteIds();

//        $data_empower_type = session('user_auth')['data_empower_type'];
////        var_dump($promoteRoot);die();
//
//        if ($promoteRoot) {
//            $map['tab_user.promote_id'] =array('in',$promoteRoot);
//        } else if(!$promoteRoot&&$data_empower_type!=1){
//            $map['tab_user.id'] = array('lt',1);
//        }
        setPowerPromoteIds($map,'tab_user.promote_id');

        //1.3 与推广员相关
        $promoterSelect = false;
        if ($_REQUEST['promote_id'] != '') {
            $promoterSelect = true;
            $spendprom = '';
            if ($_REQUEST['promote_id'] == 'UC') {
                $map['tab_user.promote_account'] = 'UC用户';
            } else if ($_REQUEST['promote_id'] == 0) {
                $map['tab_user.promote_id'] = 0;
            } else {

                if ($promoteRoot) {
                    $promoteRoot = " and id IN({$promoteRoot})";
                }
                if ($promoteRoot!='all') {
                    $promoteRoot = '';
                }


                $promoter_ids = D("Promote")->where("(chain like '%/{$_REQUEST['promote_id']}/%' or id={$_REQUEST['promote_id']})".$promoteRoot)->field('id')->select();
                if ($promoter_ids) {
                    $map['tab_user.promote_id'] = ['in', implode(',', array_column($promoter_ids, 'id'))];
                    $spendprom = " AND ss.promote_id IN (" . implode(',', array_column($promoter_ids, 'id')) . ") ";
                }
            }
        }
        
        //计算用户列表
        $data =  M("user","tab_")
        ->field("tab_user.id,`device_number`,`age_status`,`account`,`balance`,`gold_coin`,`alipay`,tab_user.promote_id,`register_type`,tab_user.promote_account,`register_time`,`lock_status`,lock_remark,`register_way`,`register_ip`,`login_time`,`check_status`,IFNULL(sum(ss.pay_amount), 0) AS recharge_total")
        ->where($map)
        ->group("tab_user.id")
        // ->page($page, $row)
        ->order($order);
        if(!isset($_REQUEST['export'])){
            $data ->page($page, $row);
        }
        if($havs){
            $data->having($havs);
        }
        if($gameplay){
            $data->join("
                (select user_id from tab_user_play where 1 $gameplay group by tab_user_play.user_id) a ON a.user_id = tab_user.id
            ");
        }
        if($game_map){
            $data->join("
                (select user_id from tab_user_play_info where 1 $game_map group by tab_user_play_info.user_id) a ON a.user_id = tab_user.id
            ");
        }
        if($promoterSelect){
            $data->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1".$spendprom,"left");
        }else{
            $data->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1","left");
        }
        $data = $data->select();
        if(isset($_REQUEST['export'])){
            $isadmin =  is_administrator();
            //获取等级
            $tool = M('tool',"tab_")->field('config,status')->where(['name'=>'viplevel'])->find();
            $viplevel = false;
            if(!empty($tool) && $tool['status']==1){
                $viplevel = json_decode($tool['config'],true);   
                $len = count($viplevel);
                if(empty($viplevel)) {$viplevel = false;}
            }
            
            foreach ($data as $k => &$v) {
                $v['register_type'] = get_registertype($v['register_type']);
                if(!$isadmin){
                    $v['account'] = encryptStr($v['account']);
                    $v['promote_account'] = encryptStr($v['promote_account']);
                    $v['device_number'] = encryptStr($v['device_number']);
                }
                empty($v['alipay']) && $v['alipay']="--";
                empty($v['small_count']) && $v['small_count']="--";
                $v['gold_coin']?:'0.00';

                if($viplevel){
                    $vl=0;
                    $money = intval($v['recharge_total']*10000);
                    foreach($viplevel as $k=>$value) {
                        $i = intval(str_replace('vip','',$k));
                        if($money<intval($value*10000)) {$vl = $i-1;break;}
                        if($i == $len) {$vl = $i;}
                    }
                    $v['vip_level'] = $vl;
                }else{
                    $v['vip_level'] = 0;
                }

                $v['register_time'] = date('Y-m-d H:i:s',$v['register_time']);
                $v['login_time'] = date('Y-m-d H:i:s',$v['login_time']);
                $v['lock_status'] = get_info_status($v['lock_status'],4);
                $v['check_status'] = $v['check_status']==1 ? "正常" :"拉黑";
                // $data[$k] = $v;
            }
            
            $field = array(
                "id"=>"账号ID","account"=>"玩家账号","promote_account"=>"所属推广员","balance"=>"账户平台币","recharge_total"=>"累计充值","gold_coin"=>"金币",
                "small_count"=>"小号","vip_level"=>"VIP等级","register_type"=>"注册方式","register_time"=>"注册时间","register_ip"=>"注册IP","login_time"=>"最后登录时间",
                "device_number"=>"设备号","lock_remark"=>"锁定备注","lock_status"=>"账号状态","check_status"=>"拉黑状态"
            );
            data2csv($data,"玩家_玩家列表",$field);
        }

        if($havs){ 
            //判断是否需要vip等级分类
            $user_count =  M("user","tab_")
            ->field("tab_user.id,IFNULL(sum(ss.pay_amount), 0) AS recharge_total")
            ->where($map)
            ->group("tab_user.id")
            ->having($havs);
            if($game_map){
                $user_count->join("
                    (select user_id from tab_user_play_info where 1 $game_map group by tab_user_play_info.user_id) a ON a.user_id = tab_user.id
                ");
            }
            if($gameplay){
                $user_count->join("
                    (select user_id from tab_user_play where 1 $gameplay group by tab_user_play.user_id) a ON a.user_id = tab_user.id
                ");
            }
            if($promoterSelect){
                $user_count->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1".$spendprom,"left");
            }else{
                $user_count->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1","left");
            }
            $user_count = $user_count->select(false);
            $count = M()->table('(' . $user_count . ') as a ')->field("count(*) user_count,sum(a.recharge_total) recharge_total")->find();
            $user_count =  $count['user_count'];
            $now_count =  $count['recharge_total'];
            
        }else{
            //计算总人数
            $user_count = M("user","tab_")
            ->field("count(*) user_count")
            ->where($map);
            if($game_map){
                $user_count->join("
                    (select user_id from tab_user_play_info where 1 $game_map group by tab_user_play_info.user_id) a ON a.user_id = tab_user.id
                ");
            }
            if($gameplay){
                $user_count->join("
                    (select user_id from tab_user_play where 1 $gameplay group by tab_user_play.user_id) a ON a.user_id = tab_user.id
                ");
            }
            $user_count = $user_count->find()['user_count'];
            //计算累计充值总额
            $now_count = M("user","tab_")
            ->field("IFNULL(sum(ss.pay_amount), 0) AS recharge_total")
            ->where($map);
            if($game_map){
                $now_count->join("
                    (select user_id from tab_user_play_info where 1 $game_map group by tab_user_play_info.user_id) a ON a.user_id = tab_user.id
                ");
            }
            if($gameplay){
                $now_count->join("
                    (select user_id from tab_user_play where 1 $gameplay group by tab_user_play.user_id) a ON a.user_id = tab_user.id
                ");
            }
            if($promoterSelect){
                $now_count->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1".$spendprom,"left");
            }else{
                $now_count->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1","left");
            }
            // dump($now_count->select(false));die();
            $now_count = $now_count->find()['recharge_total'];
        }


        //如果存在推广员只计算所属的推广员充值记录
        if($promoterSelect){
            $maps = $map;
            unset($maps['tab_user.promote_id']);
            $history_count = M("user","tab_")
            ->field("IFNULL(sum(ss.pay_amount), 0) AS recharge_total")
            ->join("tab_spend AS ss ON ss.user_id = tab_user.id AND ss.pay_status = 1".$spendprom,"left")
            ->where($maps);
            if($havs){
                $history_count->having($havs);
            }
            if($game_map){
                $history_count->join("(select user_id from tab_user_play_info where 1 $game_map group by tab_user_play_info.user_id) a ON a.user_id = tab_user.id");
            }
            if($gameplay){
                $history_count->join("
                    (select user_id from tab_user_play where 1 $gameplay group by tab_user_play.user_id) a ON a.user_id = tab_user.id
                ");
            }
            $history_count = $history_count->find()['recharge_total'];
            $this->assign('history_count', $history_count?:0);
        }


        $this->assign('user_count',$user_count);
        $this->assign('now_count', $now_count?:0);

        $page = set_pagination($user_count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('list_data', $data);
        //$this->assign("is_admin",is_administrator());
        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $this->assign('show_data_power', $show_data_power);
        $this->display();
    }

    /**
     * 用户列表旧版
     */
    public function user_info2($p = 0)
    {
        $hav = '';
        if ($_REQUEST['promote_id'] != '') {
            if ($_REQUEST['promote_id'] == 'UC') {
                $maps['tab_user.promote_account'] = 'UC用户';
                $hav .= "tab_user.promote_account = 'UC用户' ";
            } else if ($_REQUEST['promote_id'] == 0) {
                $maps['tab_user.promote_id'] = 0;
                $hav .= "tab_user.promote_id = 0";
            } else {
                $promoter_ids = D("Promote")->where("chain like '%/{$_REQUEST['promote_id']}/%' or id={$_REQUEST['promote_id']}")->field('id')->select();
                if ($promoter_ids) {
                    $maps['tab_user.promote_id'] = ['in', implode(',', array_column($promoter_ids, 'id'))];
                    $hav .= "tab_user.promote_id in (" . implode(',', array_column($promoter_ids, 'id')) . ") ";
                    $spendprom = " AND ss.promote_id IN (" . implode(',', array_column($promoter_ids, 'id')) . ") ";
                }
            }
        }
        if (I('type', 1) == 1) {
            if (isset($_GET['register_way'])) {
                if ($_GET['register_way'] == 1) {
                    empty($hav) || $hav .= ' AND ';
                    $hav .= ' tab_user.register_type in (1)';
                    $maps['tab_user.register_type'] = 1;
                } elseif ($_GET['register_way'] == 7) {
                    empty($hav) || $hav .= ' AND ';
                    $hav .= ' tab_user.register_type in(7)';
                    $maps['tab_user.register_type'] = 7;
                } else {
                    empty($hav) || $hav .= ' AND ';
                    $hav .= ' tab_user.register_type in(2)';
                    $maps['tab_user.register_type'] = 2;
                }
            } else {
                empty($hav) || $hav .= ' AND ';
                $hav .= ' tab_user.register_type in (1,2,7)';
                $maps['tab_user.register_type'] = ['in', [1, 2, 7]];
            }
        } else {
            if (isset($_GET['register_type'])) {
                empty($hav) || $hav .= ' AND ';
                $hav .= ' tab_user.register_type = ' . $_GET['register_type'];
                $maps['tab_user.register_type'] = $_GET['register_type'];

            } else {
                empty($hav) || $hav .= ' AND ';
                $hav .= ' tab_user.register_type in (0,3,4,5,6)';
                $maps['tab_user.register_type'] = ['in', [0, 3, 4, 5, 6]];
            }
        }

        if (isset($_REQUEST['user_id'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= "tab_user.id = '{$_REQUEST['user_id']}'";
            $maps['tab_user.id'] = $_REQUEST['user_id'];
            unset($_REQUEST['user_id']);
        }

        if (isset($_REQUEST['account'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= "tab_user.account like '%" . I('account') . "%'";
            $maps['tab_user.account'] = ['like', "%" . I('account') . "%"];
            unset($_REQUEST['account']);
        }
        if (isset($_REQUEST['device_number'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= "tab_user.device_number = '{$_REQUEST['device_number']}'";
            $maps['tab_user.device_number'] = $_REQUEST['device_number'];
            unset($_REQUEST['device_number']);
        }
        if (isset($_REQUEST['age_status'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= 'tab_user.age_status =' . I('age_status');
            $maps['tab_user.age_status'] = I('age_status');
            unset($_REQUEST['age_status']);
        }
        if (isset($_REQUEST['time_start']) && isset($_REQUEST['time_end'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= 'tab_user.register_time BETWEEN ' . strtotime(I('time_start')) . ' AND ' . (strtotime(I('time_end')) + 24 * 60 * 60 - 1);
            $maps['tab_user.register_time'] = ['between', [strtotime(I('time_start')), strtotime(I('time_end')) + 86399]];
            unset($_REQUEST['time_start']);
            unset($_REQUEST['time_end']);
        } elseif (isset($_REQUEST['time_start'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= 'tab_user.register_time > ' . strtotime(I('time_start'));
            $maps['tab_user.register_time'] = ['GT', strtotime(I('time_start'))];
            unset($_REQUEST['time_start']);
        } elseif (isset($_REQUEST['time_end'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= 'tab_user.register_time < ' . (strtotime(I('time_end')) + 86399);
            $maps['tab_user.register_time'] = ['LT', strtotime(I('time_end')) + 86399];
            unset($_REQUEST['time_end']);
        }
        if (isset($_REQUEST['start']) && isset($_REQUEST['end'])) {
            empty($hav) || $hav .= ' AND ';
            $hav .= 'tab_user.register_time BETWEEN ' . strtotime(I('start')) . ' AND ' . strtotime(I('end'));
            $maps['tab_user.register_time'] = array('between', [strtotime(I('start')), strtotime(I('end'))]);
            unset($_REQUEST['start']);
            unset($_REQUEST['end']);
        }
        if (!empty(I('line_day'))) {
            $day = strtotime(date('Y-m-d')) - intval(I('line_day')) * 86400;
            empty($hav) || $hav .= ' AND ';
            $hav .= $day . '> tab_user.login_time';
            $maps['tab_user.login_time'] = ['lt', $day];
        }
        if (isset($_REQUEST['status'])) {
            $map['lock_status'] = $_REQUEST['status'];
            unset($_REQUEST['status']);
        }

        $game_map = "";

        if (isset($_REQUEST['game_name'])) {
            $game_map .= " and tab_user_play.game_id in (" . implode(',', array_column(getGameByName($_REQUEST['game_name'], $_REQUEST['game_type']), 'id')) . ")";
        }
        $game_play_map = '';
        if (isset($_REQUEST['server_name'])) {
            $game_play_map .= " and tab_user_play_info.server_name = '{$_REQUEST['server_name']}' ";
        }

        if (isset($_REQUEST['viplevel'])) {

            $havs = get_vip_level_limit('recharge_total', $_REQUEST['viplevel']);
        }

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

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

        //排序
        $order = '';
        if (I('key') == 1) {
            if (I('balance_status') == 1) {
                $order = 'balance,';
            } elseif (I('balance_status') == 2) {
                $order = 'balance desc,';
            }
        } else {
            if (I('recharge_status') == 1) {
                $order .= 'recharge_total,';
            } elseif (I('recharge_status') == 2) {
                $order .= 'recharge_total desc,';
            }
        }
        $order .= 'a.id desc';

        $user = M('user', 'tab_');
        $map['puid'] = array('eq', 0);
        $map['is_platform'] = 0;
        //数据
        $usermodel = M('user', 'tab_');

        $userField = "tab_user.id,device_number,age_status,account,balance,gold_coin,alipay,tab_user.promote_id,register_type,tab_user.promote_account,register_time,lock_status,register_way,register_ip,login_time,check_status";

        $sql1 = $usermodel->field("{$userField},IFNULL(sum(b.pay_amount),0) as deposit_total")
            ->join('left join tab_deposit AS b ON tab_user.id = b.user_id AND b.pay_status = 1')
            ->where($map)
            ->group('tab_user.id')
            ->where($hav)
            // ->order($order)
            ->select(false);
        // $data = $usermodel->table('(' . $sql1 . ') as a ')->field('a.id,a.device_number,a.age_status,a.account,a.balance,a.gold_coin,a.alipay,a.promote_id,a.register_type,a.promote_account,a.register_time,a.lock_status,a.register_way,a.register_type,a.register_ip,a.login_time,IFNULL(sum(ss.pay_amount),0) as recharge_total,check_status')
        //     ->join('left join  tab_spend as ss on ss.user_id=a.id AND ss.pay_status = 1')
        //     ->join($game_map ? "tab_user_play on tab_user_play.user_id = a.id $game_map" : false)
        //     ->join($game_play_map ? "tab_user_play_info on tab_user_play_info.user_id = a.id $game_play_map" : false)
        //     ->page($page, $row)
        //     ->having($havs)
        //     ->group('a.id')
        //     ->order($order)
        //     ->select();
        if($_REQUEST['promote_id'] && $_REQUEST['promote_id'] > -1){
            $data = $usermodel->table('(' . $sql1 . ') as a ')->field('a.id,a.device_number,a.age_status,a.account,a.balance,a.gold_coin,a.alipay,a.promote_id,a.register_type,a.promote_account,a.register_time,a.lock_status,a.register_way,a.register_type,a.register_ip,a.login_time,IFNULL(sum(ss.pay_amount),0) as recharge_total,check_status')
                ->join('left join  tab_spend as ss on ss.user_id=a.id AND ss.pay_status = 1'.$spendprom)
                ->join($game_map ? "tab_user_play on tab_user_play.user_id = a.id $game_map" : false)
                ->join($game_play_map ? "tab_user_play_info on tab_user_play_info.user_id = a.id $game_play_map" : false)
                ->page($page, $row)
                ->having($havs)
                ->group('a.id')
                ->order($order)
                ->select();
            // echo $data;die();
        }else{
            $data = $usermodel->table('(' . $sql1 . ') as a ')->field('a.id,a.device_number,a.age_status,a.account,a.balance,a.gold_coin,a.alipay,a.promote_id,a.register_type,a.promote_account,a.register_time,a.lock_status,a.register_way,a.register_type,a.register_ip,a.login_time,IFNULL(sum(ss.pay_amount),0) as recharge_total,check_status')
                ->join('left join  tab_spend as ss on ss.user_id=a.id AND ss.pay_status = 1')
                ->join($game_map ? "tab_user_play on tab_user_play.user_id = a.id $game_map" : false)
                ->join($game_play_map ? "tab_user_play_info on tab_user_play_info.user_id = a.id $game_play_map" : false)
                ->page($page, $row)
                ->having($havs)
                ->group('a.id')
                ->order($order)
                ->select();
        }

        //计数
        $sql = M('user', 'tab_')->field('tab_user.id,IFNULL(sum(ss.pay_amount),0) AS recharge_total')
            ->join('left join  tab_spend as ss on ss.user_id=tab_user.id AND ss.pay_status = 1')
            ->join($game_map ? "tab_user_play on tab_user_play.user_id = tab_user.id $game_map" : false)
            ->join($game_play_map ? "tab_user_play_info on tab_user_play_info.user_id = tab_user.id $game_play_map" : false)
            ->where($map)
            ->group('tab_user.id')
            ->where($hav)
            ->having($havs)->select(false);

        $allcountsql = str_replace("tab_user.promote_id","ss.promote_id",$sql);
        //获取总额
        $allcount = M()->field('count(a.id) as count,sum(a.recharge_total) recharge_total')->table('(' . $allcountsql . ') as a')->select();
        $this->assign('history_count', $allcount[0]['recharge_total']?:0);

        //替换为新表
        if($_REQUEST['promote_id'] && $_REQUEST['promote_id'] > -1){
            $sql = M('user', 'tab_')->field('tab_user.id,IFNULL(sum(ss.pay_amount),0) AS recharge_total')
                ->join('left join  tab_spend as ss on ss.user_id=tab_user.id AND ss.pay_status = 1'.$spendprom)
                ->join($game_map ? "tab_user_play on tab_user_play.user_id = tab_user.id $game_map" : false)
                ->join($game_play_map ? "tab_user_play_info on tab_user_play_info.user_id = tab_user.id $game_play_map" : false)
                ->where($map)
                ->group('tab_user.id')
                ->where($hav)
                ->having($havs)->select(false);
        }

        $jcount = M('User', 'tab_')->field('count(a.id) as count,sum(a.recharge_total) recharge_total')->table('(' . $sql . ') as a')->select();
        $count = $jcount[0]['count'] ?:0 ;
        $this->assign('user_count', $count);
        // var_dump($jcount);die();
        $this->assign('now_count', $jcount[0]['recharge_total']?:0);

        $model = M('Model')->getByName('user');

        if ($data) {

            $ids = array_column($data, 'id');
            /* 在手里 */
            $small = M('user', 'tab_')->field('count(id) as count,puid')->where(['puid' => array('in', $ids)])->group('puid')->select();
            /* 出售中 */
            $small2 = M('user', 'tab_')->field('count(id) as count,source_puid')->where(['source_puid' => array('in', $ids), 'source_time' => 0])->group('source_puid')->select();

            foreach ($data as $k => $v) {
                $data[$k]['small_count'] = 0;
                foreach ($small as $s) {
                    if ($s['puid'] == $v['id']) {
                        $data[$k]['small_count'] += $s['count'];
                        break;
                    }
                }
                foreach ($small2 as $s) {
                    if ($s['source_puid'] == $v['id']) {
                        $data[$k]['small_count'] += $s['count'];
                        break;
                    }
                }
            }

        }

        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('list_data', $data);
        $this->assign('model', $model);
        $this->meta_title = "用户信息";

        $this->m_title = '玩家列表';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Member/user_info', 'status' => 1])->find());
        
        $this->display();
    }

    /**
     * 小号列表
     * @author 鹿文学
     */
    public function small_list($p = 1)
    {

        //$map['puid'] = $_GET['id'];
        $pid = intval($_GET['id']);
        if (is_numeric($pid) && $pid > 0) {
            $map['_string'] = ' (puid = ' . $pid . ') or (source_puid = ' . $pid . ' and source_time = 0) ';
            $page = intval($p);
            $page = $page ? $page : 1; //默认显示第一页数据

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

            if ($_REQUEST['small']) {
                $map['account'] = array('like', '%' . $_REQUEST['small'] . '%');
            }

            $data = M('User', 'tab_')
                ->field('id,account,register_time,puid,source_puid,source_time,fgame_id,fgame_name,cumulative,balance,lock_status,DATEDIFF(curdate(),FROM_UNIXTIME(register_time,"%Y-%m-%d")) as day')
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order('register_time desc')
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

            /* 查询记录总数 */
            $count = M('User', 'tab_')->where($map)->count();

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

            $this->assign('list_data', $data);
            $this->assign('pid', $pid);
        }
        $this->display();

    }

    /**
     * 公用小号列表
     * @author 鹿文学
     */
    public function public_small_list($p = 1)
    {
        $pid = intval($_GET['id']);
        if (is_numeric($pid) && $pid > 0) {
            $page = intval($p);
            $page = $page ? $page : 1; //默认显示第一页数据
            if (isset($_REQUEST['row'])) {
                $row = $_REQUEST['row'];
            } else {
                $row = 10;
            }
            $map['u.puid'] = $pid;

            if ($_REQUEST['small']) {
                $map['u.account'] = array('like', '%' . $_REQUEST['small'] . '%');
            }

            $data = M('User', 'tab_')->alias('u')
                ->field('u.id,u.account,u.register_time,u.cumulative,u.balance,fgame_id,fgame_name,u.lock_status,DATEDIFF(curdate(),FROM_UNIXTIME(u.register_time,"%Y-%m-%d")) as day')
                ->join('tab_merchandise as m on ((m.status = 3 or m.status=0 or m.status = 4) and m.small_id = u.id) ')
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order('u.register_time desc')
                /* 数据分页 */
                ->page($page, $row)
                /* 执行查询 */
                ->select();

            /* 查询记录总数 */
            $count = M('User', 'tab_')->alias('u')
                ->join('tab_merchandise as m on ((m.status = 3 or m.status=0 or m.status = 4) and m.small_id = u.id) ')
                ->where($map)->count();

            //分页

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

            $this->assign('list_data', $data);
        }
        $this->display();
    }

    /**
     * 金币提现记录
     * @author  鹿文学
     */
    public function gold_coin($p = 1, $user_id = '')
    {

        if (is_numeric($user_id) && $user_id > 0) {

            $wgc = D('WithdrawGoldCoin');

            $list = $wgc->listsByUser($p, $user_id);

            $map = array('pay_status' => 1, 'user_id' => $user_id);

            $total = null_to_0($wgc->where($map)->sum('coin'));
            $ttotal = null_to_0($wgc->where('create_time' . total(1))->where($map)->sum('coin'));
            $poundage = null_to_0($wgc->where($map)->sum('poundage'));
            $this->assign('total', $total);
            $this->assign('ttotal', $ttotal);
            $this->assign('poundage', $poundage);

            $this->assign('list_data', $list);

        }

        $this->display();

    }

    public function role_list($p = 1, $user_id = '', $row = 10)
    {
        $limit = ($p - 1) * $row . ", $row";

        $list = M("user_play_info", 'tab_')->where(['user_id' => $user_id])->limit($limit)->order('play_time desc')->select();
        $count = M("user_play_info", 'tab_')->where(['user_id' => $user_id])->count();
        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('list', $list);
        $this->display();
    }

    /**
     * 公用账户
     * @author  鹿文学
     */
    public function public_account()
    {

        if (IS_POST) {
            $user = new MemberApi();
            if (!empty($data['account'])) {
                $data['account'] = str_replace('pa_', '', $data['account']);
            }
            $res = $user->updateUserInfo($_POST);

            if ($res['status'] !== false) {
                \Think\Log::actionLog("Member/public_account", "Member", $id);
                $this->success($res['msg'], U('public_account'));
            } else {
                $this->error($res['msg']);
            }

        } else {

            $map['is_platform'] = 1;
            $user = D('User');
            $data = $user->where($map)->find();

            if ($data['id']) {
                $data['small_count'] = $user->alias('u')->join('tab_merchandise as m on ((m.status = 3 or m.status=0 or m.status=4) and m.small_id = u.id) ')
                    ->where(['u.puid' => $data['id']])->count();
            }

            $this->assign('data', $data);
            $this->meta_title = "公用账户信息";

            $this->m_title = '公用账户信息';
            $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Member/public_account', 'status' => 1])->find());

            $this->display();
        }
    }

    //设置状态
    public function set_status($model = 'User')
    {
        if (isset($_REQUEST['model'])) {
            $model = $_REQUEST['model'];
            unset($_REQUEST['model']);
        }
        parent::set_status($model);
    }

    public function edit($id = null)
    {
        if (IS_POST) {
            $member = new MemberApi();
            $data = $_REQUEST;
            if (empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['real_name']) && (\mb_strlen($data['real_name']) > 5 || \mb_strlen($data['real_name']) <= 1)) {
                $this->error('请填写正确的名字');
            }

           /* if (!empty($data['idcard']) && !preg_match('/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/', $data['idcard'])) {
                $this->error('请输入正确的身份证号码');
            }*/

            $res = $member->updateInfo($data);
            if ($res !== false) {
                \Think\Log::actionLog("Member/edit", "Member", $id);
                $this->success("修改成功", U('user_info'));
            } else {
                $this->error("修改失败");
            }

        } else {
            $user = A('User', 'Event');
            $data = $user->user_entity($id);
            if (is_numeric($data['head_img'])) {
                $data['head_img'] = get_cover($data['head_img'], 'cover');
            }
            if (empty($data['head_img'])) {
                $data['head_img'] = $data['sex'] == 1 ? C('TMPL_PARSE_STRING.__IMG__') . '/head_women.png' : C('TMPL_PARSE_STRING.__IMG__') . '/logoo.png';
            }
            $this->assign('data', $data);
            $this->meta_title = "玩家信息";

            $spend_totle = M('spend', 'tab_')->where(['user_id' => $id, 'pay_status' => 1])->sum('pay_amount');
            $deposit_totle = M('deposit', 'tab_')->where(['user_id' => $id, 'pay_status' => 1])->sum('pay_amount');

            $this->assign('recharge_total', $spend_totle + $deposit_totle);

            $this->m_title = '玩家列表';

            $this->assign("is_admin",is_administrator());
            $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
            $this->assign('show_data_power', $show_data_power);
            $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Member/user_info', 'status' => 1])->find());
            $this->display();
        }

    }

    public function bind_balance($p = 1)
    {
        $map['user_id'] = $_REQUEST['id'];
        $data = M("user_play", "tab_")
            // 查询条件
            ->where($map)
            ->group('user_account,game_name')
            /* 执行查询 */
            ->select();
        $this->assign('list_data', $data);
        $this->display();
    }

    public function balance($p = 1)
    {
        $map['user_id'] = $_REQUEST['id'];
        $data = M("user", "tab_")
            // 查询条件
            ->where($map)
            /* 执行查询 */
            ->select();
        $this->assign('list_data', $data);
        $this->display();
    }

    /**
     * 系统非常规MD5加密方法
     * @param string $str 要加密的字符串
     * @return string
     */
    function think_ucenter_md5($str, $key = 'ThinkUCenter')
    {
        return '' === $str ? '' : md5(sha1($str) . $key);
    }

    public function checkpwd()
    {
        $res = D('Member')->check_sc_pwd(I('second_pwd'));
        if ($res) {
            $this->ajaxReturn(array("status" => 1, "msg" => "成功"));
        } else {
            $this->ajaxReturn(array("status" => -1, "msg" => "二级密码错误"));
        }
    }

    public function balance_edit()
    {
        $res = D('Member')->check_sc_pwd($_REQUEST['second_pwd_']);
        if ($res) {
            $map['id'] = $_REQUEST['id'];
            $data = array(
                'balance' => $_REQUEST['balance']
            );
            $user = M('user', 'tab_')->where($map)->find();
            $pro = M("user", "tab_")->where($map)->setfield('balance', $_REQUEST['balance']);
            if ($pro !== false) {
                $data = array(
                    'user_id' => $_REQUEST['id'],
                    'user_account' => get_user_account($_REQUEST['id']),
                    'game_id' => '',
                    'game_name' => '',
                    'prev_amount' => $user['balance'],
                    'amount' => $_REQUEST['balance'],
                    'type' => 0,
                    'op_id' => UID,
                    'op_account' => get_admin_name(UID),
                    'create_time' => time()
                );
                M('balance_edit', 'tab_')->add($data);
                $this->ajaxReturn(array("status" => 1, "msg" => "成功"));
            } else {
                $this->ajaxReturn(array("status" => -1, "msg" => "失败"));
            }
        } else {
            $this->ajaxReturn(array("status" => -1, "msg" => "二级密码错误"));
        }

    }

    public function bind_balance_edit($p = 1)
    {
        $map['id'] = $_REQUEST['id'];
        $map['user_id'] = $_REQUEST['user_id'];
        $map['game_id'] = $_REQUEST['game_id'];
        $res = D('Member')->check_sc_pwd($_REQUEST['second_pwd']);
        if ($res) {
            $user_play = M('user_play', 'tab_')->where($map)->find();
            $pro = M("user_play", "tab_")
                ->where($map)
                ->setField('bind_balance', $_REQUEST['bind_balance']);
            if ($pro !== false) {
                $data = array(
                    'user_id' => $_REQUEST['user_id'],
                    'user_account' => get_user_account($_REQUEST['user_id']),
                    'game_id' => $_REQUEST['game_id'],
                    'game_name' => get_game_name($_REQUEST['game_id']),
                    'prev_amount' => $user_play['bind_balance'],
                    'amount' => $_REQUEST['bind_balance'],
                    'type' => 1,
                    'op_id' => is_login(),
                    'op_account' => get_admin_nickname(is_login()),
                    'create_time' => time()
                );
                M('balance_edit', 'tab_')->add($data);
                $this->ajaxReturn(array("status" => 1, "msg" => "成功"));
            } else {
                $this->ajaxReturn(array("status" => 0, "msg" => "失败"));
            }
        } else {
            $this->ajaxReturn(array("status" => 0, "msg" => "二级密码错误"));
        }
    }

    public function chax($p = 1)
    {
        $map['user_account'] = get_user_account($_REQUEST['id']);
        $map['pay_status'] = 1;
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = 10;

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

        //$new_model = D($name);
        $data = M("spend", "tab_")
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order('pay_time desc')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();

        /* 查询记录总数 */
        $count = M("spend", "tab_")->where($map)->count();
        //分页

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

        $total = null_to_0(D('spend')->where($map)->sum('pay_amount'));
        $ttotal = null_to_0(D('spend')->where('pay_time' . total(1))->where($map)->sum('pay_amount'));
        $ytotal = null_to_0(D('spend')->where('pay_time' . total(5))->where($map)->sum('pay_amount'));
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function changephone()
    {
        if (preg_match('/^[1][3578][0-9]{9}/', $_POST['phone'])) {
            //重复判断
            $where['phone'] = $_POST['phone'];
            $user = M('User', 'tab_')->where($where)->field('id,account')->find();
            if ($user) {
                $this->ajaxReturn(array("status" => 0, "msg" => "该手机号已被" . $user['account'] . "(" . $user['id'] . ")绑定"));
            }

            $map['id'] = $_POST['id'];
            $pro = M("User", "tab_")
                ->where($map)
                ->setField('phone', $_POST['phone']);
            if ($pro !== false) {
                $this->ajaxReturn(array("status" => 1, "msg" => "手机修改成功"));
            } else {
                $this->ajaxReturn(array("status" => 0, "msg" => "手机修改失败"));
            }
        } else {
            $this->ajaxReturn(array("status" => 0, "msg" => "手机输入错误"));
        }
    }


    public function changeprelname()
    {
        if (preg_match('/^([\xe4-\xe9][\x80-\xbf]{2}){2,4}$/', $_POST['real_name'])) {
            //重复判断
            $map['id'] = $_POST['id'];
            $pro = M("User", "tab_")
                ->where($map)
                ->setField('real_name', $_POST['real_name']);
            if ($pro !== false) {
                $this->ajaxReturn(array("status" => 1, "msg" => "真实姓名修改成功"));
            } else {
                $this->ajaxReturn(array("status" => 0, "msg" => "真实姓名修改失败"));
            }
        } else {
            $this->ajaxReturn(array("status" => 0, "msg" => "真实姓名输入错误"));
        }
    }


    public function changepidcard()
    {
        if (preg_match('/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/', $_POST['idcard'])) {
            //重复判断
            //$where['idcard'] = $_POST['idcard'];
            /*$user = M('User', 'tab_')->where($where)->field('id,account')->find();
            if ($user) {
                $this->ajaxReturn(array("status" => 0, "msg" => "该身份证号码已被" . $user['account'] . "(" . $user['id'] . ")绑定"));
            }*/

            $map['id'] = $_POST['id'];
            $pro = M("User", "tab_")
                ->where($map)
                ->setField('idcard', $_POST['idcard']);
            if ($pro !== false) {
                $this->ajaxReturn(array("status" => 1, "msg" => "身份证号码修改成功"));
            } else {
                $this->ajaxReturn(array("status" => 0, "msg" => "身份证号码修改失败"));
            }
        } else {
            $this->ajaxReturn(array("status" => 0, "msg" => "请输入正确的身份证号码"));
        }
    }

    public function denglu($p = 1)
    {
        $map['user_id'] = $_REQUEST['id'];
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = 10;

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

        $data = M("user_login_record", "tab_")
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order('login_time desc')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();
        /* 查询记录总数 */
        $count = M("user_login_record", "tab_")->where($map)->count();
        //分页

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

        $this->assign('list_data', $data);
        $this->display();
    }

    /**
     *用户登录记录
     */
    public function login_record($p = 1)
    {
        if (isset($_REQUEST['game_name'])) {
            $map['game_name'] = ['like', $_REQUEST['game_name'] . "%"];
            unset($_REQUEST['game_name']);
        }
        if (isset($_REQUEST['game_type'])) {
            $map['sdk_version'] = $_REQUEST['game_type'];
            unset($_REQUEST['game_type']);
        }
        if (isset($_REQUEST['login_ip'])) {
            $map['login_ip'] = $_REQUEST['login_ip'];
            unset($_REQUEST['login_ip']);
        }
        if (isset($_REQUEST['timestart']) && isset($_REQUEST['timeend'])) {
            $map['login_time'] = array('BETWEEN', array(strtotime($_REQUEST['timestart']), strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1));
            unset($_REQUEST['timestart']);
            unset($_REQUEST['timeend']);
        } elseif (isset($_REQUEST['timestart'])) {
            $map['login_time'] = array('GT', strtotime($_REQUEST['timestart']));
            unset($_REQUEST['timestart']);
        } elseif (isset($_REQUEST['timeend'])) {
            $map['login_time'] = array('lt', (strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1));
            unset($_REQUEST['timeend']);
        }
        if (isset($_REQUEST['start']) && isset($_REQUEST['end'])) {
            $map['login_time'] = array('BETWEEN', array(strtotime($_REQUEST['start']), strtotime($_REQUEST['end']) + 24 * 60 * 60 - 1));
            unset($_REQUEST['start']);
            unset($_REQUEST['end']);
        }
        if (isset($_REQUEST['account'])) {
            $map['user_account'] = array('like',  trim($_REQUEST['account']) . '%');
            unset($_REQUEST['account']);
        }
        if (isset($_REQUEST['server_id'])) {
            $map['server_id'] = $_REQUEST['server_id'];
            unset($_REQUEST['server_id']);
        }

//        $promoteRoot = getPowerPromoteIds();
//        $data_empower_type = session('user_auth')['data_empower_type'];
//
//        if ($promoteRoot) {
//            $map['promote_id'] =array('in',$promoteRoot);
//        } else if(!$promoteRoot&&$data_empower_type!=1){
//            $map['id'] = array('lt',1);
//        }
        setPowerPromoteIds($map,'promote_id');

        if (isset($_REQUEST['promote_id'])) {
            if (I('promote_level') ==1) {
                $promote_ids = getOffspringByPromoteId($_REQUEST['promote_id']);
                $map['promote_id'] = ['exp', "in($promote_ids)"];
            } else {
                $map['promote_id'] = $_REQUEST['promote_id'];
            }
            unset($_REQUEST['promote_id']);
        } elseif (I('promote_level') ==1) {
            $promote_ids = getOffspringByPromoteId();
            if ($promote_ids != 'all') {
                $map['promote_id'] = ['exp', "in($promote_ids)"];
            }
        }
        // $map['type'] = 1;
        // $map['login_time'] = ['exp', 'login_time<>0'];
        $extend = array();
        $extend['map'] = $map;
        $count = M('UserLoginRecord','tab_')
//            ->table('tab_user_login_record FORCE INDEX(user_id_promote_idx)')
            ->field('user_id')->where($extend['map'])
            ->group('user_id')
            ->select(false);
        $sql = "select count(user_id) as count from ({$count})t";
//        dd($sql);
        $count = M('UserLoginRecord','tab_')->query($sql);

        $this->m_title = '登录记录';
        $this->assign('user_count',$count[0]['count']);
        $this->assign("is_admin",is_administrator());
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Member/login_record', 'status' => 1])->find());
        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $this->assign('show_data_power', $show_data_power);
        parent::lists("UserLoginRecord", $p, $extend['map']);
    }

    public function del($model = null, $ids = null)
    {
        $map = array();
        if (isset($_REQUEST['id'])) {
            $map['id'] = $_REQUEST['id'];
            $data = M('user_login_record', 'tab_')->where($map)->delete();
            \Think\Log::actionLog('Member/del', 'Member', $_REQUEST['id']);
            $this->success('删除成功!', U('login_record'), 2);
        } else {
            $this->error('请选择要操作的数据!');
        }
    }

    public function delprovide($ids = null)
    {
        if (empty($ids)) {
            $this->error('请选择要操作的数据!');
        }
        $list = M("user_login_record", "tab_");
        $map['id'] = array("in", $ids);
        //$map['status'] = 0;
        $delete = $list->where($map)->delete();
        if ($delete) {
            \Think\Log::actionLog('Member/delprovide', 'Member', 1);
            $this->success("批量删除成功!", U("login_record"));
        } else {
            $this->error("批量删除失败!", U("login_record"));
        }
    }

    /**
     * 锁定玩家
     * @param $id
     * @param $lock_status
     */
    public function lock_status($id="", $lock_status, $accounts = "")
    {
        if ($accounts) $map['account'] = ['in', array_unique(explode("\n", $accounts))];
        if ($id) $map['id'] = ['in', array_unique(explode("\n", $id))];
        $users =  M('user', 'tab_')->where($map)->field('id')->select();
        if($_POST['lock_remark']){
            $res = M('user', 'tab_')->where($map)->setField(['lock_status' => $lock_status,"lock_remark" => $_POST['lock_remark']]);
        }else{
            $res = M('user', 'tab_')->where($map)->setField(['lock_status' => $lock_status]);
        }

        if ($res) {
            foreach ($users as $item) {
                \Think\Log::actionLog('Member/lock_status', 'Member', $item['id']);
            }
            $this->success('操作成功!');
        } else {
            $this->error('操作失败!');
        }
    }

    /**
     * 对年龄的审核
     */
    public function age_check()
    {
        $id = I("id");
        $arr = explode(',', $id);
        $i = 0;
        $q = 0;
        $t = 0;
        //已经审核过的不审核 信息为空的也不审核
        foreach ($arr as $key) {
            $where['id'] = $key;
            $where['status'] = array('neq', '2');
            $res = D("User")->where($where)->select();
            if (empty($res[0]['idcard']) || empty($res[0]['real_name'])) {
                $i++;
            } else {
                $return = age_verify($res[0]['idcard'], $res[0]['real_name']);
                if ($return == 1 && $return > 0) {
                    $q++;
                    $data['id'] = $key;
                    $data['age_status'] = 2;
                } elseif ($return == 2 && $return > 0) {
                    $q++;
                    $data['id'] = $key;
                    $data['age_status'] = 3;
                } elseif ($return == -1) {
                    echo json_encode(array('status' => 2, 'info' => '短信数量已经使用完'));
                    exit;
                } elseif ($return == -2) {
                    echo json_encode(array('status' => 2, 'info' => '连接失败,请检查数据库配置'));
                    exit;
                } else {
                    $t++;
                    $data['id'] = $key;
                    $data['age_status'] = 1;
                }
                $re = D("User")->data($data)->save();
            }
        }
        echo json_encode(array('status' => 1, 'info' => '未填写' . $i . "个,审核通过" . $q . "个,审核未通过" . $t . "个"));
        exit;
    }

    /**
     * @函数或方法说明
     * @防刷预警设置
     * @param int $cate_id
     * @param int $group_id
     *
     * @author: 郭家屯
     * @since: 2019/4/29 15:03
     */
    public function brush_set()
    {
        $cate_id = I('cate_id', 8);
        $group_id = I('group_id', 0);

        $this->m_title = '站点设置(PC官网)';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Site/media', 'status' => 1])->find());
        $map['status'] = 1;
        $map['category'] = $cate_id;
        $map['group'] = $group_id;
        $list = M("Config")->where($map)->field('id,name,title,extra,value,remark,type')->order('sort')->select();
        if ($list) {
            $this->assign('list', $list);
        }
        $this->assign('id', $group_id);
        $this->meta_title = '防刷预警设置';
        $this->display();
    }

    /**
     * @函数或方法说明
     * @保存防刷预警参数
     * @author: 郭家屯
     * @since: 2019/4/30 10:08
     */
    public function brush_save($config)
    {
        if ($config && is_array($config)) {
            $Config = M('Config');
            foreach ($config as $name => $value) {
                $map = array('name' => $name);
                if ($name == 'CACHE_TYPE' && $value != 0) {
                    $res = $this->check_cache($value, $config['CACHE_TYPE_HOST']);
                    if ($res) {
                        $this->set_config($name, $value);
                    } else {
                        $this->error('缓存服务器连接不上,开启缓存失败');
                    }
                } elseif ($name == 'CACHE_TYPE_HOST' || $name == 'CACHE_TYPE_TIME') {
                    $this->set_config($name, $value);
                }
                $Config->where($map)->setField('value', $value);
            }
        }
        S('DB_CONFIG_DATA', null);
        $this->success('保存成功!');
    }

    /**
     *设置config
     */
    private function set_config($name = "", $config = "")
    {
        $config_file = "./Application/Common/Conf/pay_config.php";
        if (file_exists($config_file)) {
            $configs = include $config_file;
        } else {
            $configs = array();
        }
        #定义一个数组
        $data = array();
        #给数组赋值
        $data[$name] = $config;
        $configs = array_merge($configs, $data);
        $result = file_put_contents($config_file, "<?php\treturn " . var_export($configs, true) . ";");
    }

    /**
     * @函数或方法说明
     * @黑名单列表
     * @author: 郭家屯
     * @since: 2019/5/5 17:11
     */
    public function blacklist($p = 1)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }
        //排序
        if ($_REQUEST['account']) {
            $map['account'] = ['like', '%' . $_REQUEST['account'] . '%'];
        }
        $map['check_status'] = 0;
        $order = 'block_time desc';
        $black = M('user', 'tab_')->field('id,account,block_time')->where($map)->order($order)->page($p, $row)->select();
        $count = M('user', 'tab_')->where($map)->count();
        $this->assign('list_data', $black);
        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->meta_title = '黑名单列表';
        $this->display();
    }

    /**
     * @函数或方法说明
     * @拉黑设置
     * @author: 郭家屯
     * @since: 2019/5/5 17:12
     */
    public function blockconfig()
    {
        $cate_id = I('cate_id', 9);
        $group_id = I('group_id', 0);

        $this->m_title = '站点设置(PC官网)';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Site/media', 'status' => 1])->find());
        $map['status'] = 1;
        $map['category'] = $cate_id;
        $map['group'] = $group_id;
        $list = M("Config")->where($map)->field('id,name,title,extra,value,remark,type')->order('sort')->select();
        if ($list) {
            $this->assign('list', $list);
        }
        $this->assign('id', $group_id);
        $this->meta_title = '拉黑设置';
        $this->display();
    }

    /**
     * @函数或方法说明
     * @平台币订单
     * @author: 郭家屯
     * @since: 2019/5/6 10:50
     */
    public function deposit_order()
    {
        $user_id = I('id', 0, 'intval');
        $user_entity = get_user_entity($user_id);
        //平台币充值订单
        $brush_map['user_id'] = $user_entity['id'];
        $brush_map['pay_status'] = 1;
        $brush_map['create_time'] = ['egt', $user_entity['check_time']];
        $deposit_order = M('deposit', 'tab_')->where($brush_map)->field('id,order_number,pay_order_number,user_id,pay_amount,check_sign,create_time,pay_way,pay_ip')->select();
        $abnormal = 0;
        $deposit_money = 0;
        $weixn = new Weixin();
        $alipay = new \Think\Pay('alipay');
        foreach ($deposit_order as $key => $v) {
            $sign = get_check_sign($v['user_id'], $v['order_number'], $v['pay_amount'], $v['create_time']);
            if ($sign != $v['check_sign']) {
                $deposit_order[$key]['error_type'] = '订单标识违规';
                $abnormal++;
            }
            if ($v['pay_way'] == 2 || $v['pay_way'] == 3) {
                $deposit_order[$key]['weixin_pay_money'] = $weixn->weixin_block_orderquery($v['order_number']);
            }
            if ($v['pay_way'] == 1) {
                $deposit_order[$key]['alipay_money'] = $alipay->alipay_orderquery($v['order_number'], $v['pay_order_number']);
            }
            $deposit_money += $v['pay_amount'];
        }
        $this->assign('deposit_order', $deposit_order);
        //发放平台币金额
        $batch_map['user_id'] = $user_entity['id'];
        $batch_map['status'] = 1;
        $batch_map['create_time'] = ['egt', $user_entity['check_time']];
        $batch_order = M('provide_user', 'tab_')->field('order_number,pay_order_number,amount,create_time')->where($batch_map)->select();
        $batch_amount = 0;
        foreach ($batch_order as $key => $v) {
            $batch_amount += $v['amount'];
        }
        $this->assign('batch_order', $batch_order);
        //积分兑换平台币
        $point_map['user_id'] = $user_entity['id'];
        $point_map['good_type'] = 3;
        $point_map['create_time'] = ['egt', $user_entity['check_time']];
        $point_order = M('point_shop_record', 'tab_')->field('number,create_time')->where($point_map)->select();
        $point_money = 0;
        foreach ($point_order as $key => $v) {
            $point_money += $v['number'];
        }
        $this->assign('point_order', $point_order);
        //分享获取平台币
        $share_map['invite_id'] = $user_entity['id'];
        $share_map['create_time'] = ['egt', $user_entity['check_time']];
        $share_order = M('share_record', 'tab_')->field('order_number,award_coin as amount,create_time')->where($share_map)->select();
        $share_amount = 0;
        foreach ($share_order as $key => $v) {
            $share_amount += $v['amount'];
        }
        $this->assign('share_order', $share_order);
        //消费平台币金额
        $spend_map['user_id'] = $user_entity['id'];
        $spend_map['pay_status'] = 1;
        $spend_map['pay_way'] = 0;
        $spend_map['pay_time'] = ['egt', $user_entity['check_time']];
        $spend_order = M('spend', 'tab_')->field('order_number,pay_order_number,user_id,pay_amount,spend_ip,pay_time')->where($spend_map)->select();
        $spend_amount = 0;
        foreach ($spend_order as $key => $v) {
            $spend_amount += $v['pay_amount'];
        }
        //统计标识金额
        $total_money = floatval($user_entity['balance']) - $deposit_money - $batch_amount - $point_money - $share_amount + floatval($spend_amount) - $user_entity['check_money'];
        $this->assign('total_money', abs(round((float)$total_money, 2)));
        $this->assign('spend_order', $spend_order);
        $this->assign('abnormal', $abnormal);
        $this->assign('user', $user_entity);
        $this->display();
    }

    /**
     * @函数或方法说明
     * @绑币订单
     * @author: 郭家屯
     * @since: 2019/5/6 10:51
     */
    public function bind_order()
    {
        $user_id = I('id', 0, 'intval');
        $user_entity = get_user_entity($user_id);
        $brush_map['user_id'] = $user_entity['id'];
        $brush_map['pay_status'] = 1;
        $brush_map['create_time'] = ['egt', $user_entity['check_time']];
        $bind_recharge_order = M('bind_recharge', 'tab_')->where($brush_map)->field('id,user_id,order_number,pay_order_number,amount,user_id,real_amount,check_sign,create_time,zhekou,recharge_ip,pay_way')->select();
        $bind_recharge_amount = 0;
        $abnormal = 0;
        $weixn = new Weixin();
        $alipay = new \Think\Pay('alipay');
        foreach ($bind_recharge_order as $key => $v) {
            $sign = get_check_sign($v['user_id'], $v['order_number'], $v['amount'], $v['create_time']);
            if ($sign != $v['check_sign']) {
                $bind_recharge_order[$key]['error_type'] = '订单标识违规';
                $abnormal++;
            }
            if ($v['pay_way'] == 2 || $v['pay_way'] == 3) {
                $bind_recharge_order[$key]['weixin_pay_money'] = $weixn->weixin_block_orderquery($v['order_number']);
            }
            if ($v['pay_way'] == 1) {
                $bind_recharge_order[$key]['alipay_money'] = $alipay->alipay_orderquery($v['order_number'], $v['pay_order_number']);
            }
            $bind_recharge_amount += $v['amount'];
        }
        $this->assign('bind_recharge_order', $bind_recharge_order);
        //发放绑币金额
        $batch_map['user_id'] = $user_entity['id'];
        $batch_map['status'] = 1;
        $batch_map['create_time'] = ['egt', $user_entity['check_time']];
        $batch_order = M('provide', 'tab_')->field('order_number,pay_order_number,amount,create_time')->where($batch_map)->select();
        $batch_amount = 0;
        foreach ($batch_order as $key => $v) {
            $batch_amount += $v['amount'];
        }
        $this->assign('batch_order', $batch_order);
        //消费返利
        $rebate_map['user_id'] = $user_entity['id'];
        $rebate_map['create_time'] = ['egt', $user_entity['check_time']];
        $rebate_order = M("rebate_list", "tab_")->field('pay_order_number,ratio_amount as amount,create_time')->where($rebate_map)->select();
        $rebate_money = 0;
        foreach ($rebate_order as $key => $v) {
            $rebate_money += $v['amount'];
        }
        $this->assign('rebate_order', $rebate_order);
        //会长代充
        $agent_map['user_id'] = $user_entity['id'];
        $agent_map['pay_status'] = 1;
        $agent_map['create_time'] = ['egt', $user_entity['check_time']];
        $agent_order = M('agent', 'tab_')->field('order_number,pay_order_number,amount,real_amount,create_time,zhekou,pay_way')->where($agent_map)->select();
        $agent_amount = 0;
        foreach ($agent_order as $key => $v) {
            $agent_amount += $v['amount'];
        }
        $this->assign('agent_order', $agent_order);
        //消费平台币金额
        $spend_map['user_id'] = $user_entity['id'];
        $spend_map['pay_status'] = 1;
        $spend_map['pay_way'] = -1;
        $spend_map['pay_time'] = ['egt', $user_entity['check_time']];
        $spend_order = M('spend', 'tab_')->field('order_number,pay_order_number,user_id,pay_amount,spend_ip,pay_time')->where($spend_map)->select();
        $spend_amount = 0;
        foreach ($spend_order as $key => $v) {
            $spend_amount += $v['pay_amount'];
        }
        $this->assign('spend_order', $spend_order);
        $this->assign('abnormal', $abnormal);
        //检查绑币金额
        $check_map['user_id'] = $user_entity['id'];
        $check_money = M('user_play', 'tab_')->where($check_map)->sum('check_money');
        $sum_money = M('user_play', 'tab_')->where($check_map)->sum('bind_balance');
        //统计标识金额
        $total_money = $sum_money - $bind_recharge_amount - $batch_amount - $rebate_money - $agent_amount + $spend_amount - $check_money;
        $this->assign('total_money', abs(round((float)$total_money, 2)));
        $this->assign('user', $user_entity);
        $this->display();
    }

    /**
     * @函数或方法说明
     * @移除拉黑状态
     * @author: 郭家屯
     * @since: 2019/5/6 10:35
     */
    public function block_status()
    {
        $user_id = I('id', 0, 'intval');
        $user_entity = get_user_entity($user_id);
        if (!$user_entity) {
            $this->error('账号不存在');
        }
        $model = M('user', 'tab_');
        $result = $model->execute("update tab_user set check_money=balance,check_status=1,check_time=" . time() . " where id=" . $user_id);
        $result1 = $model->execute("update tab_user_play set check_money=bind_balance where user_id=" . $user_id);
        if ($result !== false && $result1 !== false) {
            $this->success('移除成功');
        } else {
            $this->error('移除失败');
        }
    }

    public function device_bans_list($row = 10, $type = '', $tag = '', $p = 1)
    {
        $map = [];
        if (!empty($type)) {
            $map['type'] = $type;
        }
        if (!empty($tag)) {
            $map['tag'] = $tag;
        }
        $list = M('device_bans', 'tab_')->where($map)->page($p, $row)->select();
        $count = M('device_bans', 'tab_')->where($map)->count();
        if (!empty($list)) {
            foreach ($list as &$item) {
                switch ($item['type']) {
                    case '1':
                        $item['type_name'] = '设备号';
                        break;
                    case '2':
                        $item['type_name'] = 'IP';
                        break;
                    case '3':
                        $item['type_name'] = '落地页链接';
                        break;
                    case '4':
                        $item['type_name'] = '下载链接';
                        break;
                }
            }
        }
        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('list_data', $list);
        $this->display();
    }

    public function save_device_bans($id = '', $type = '', $tag = '')
    {
        if (empty($id)) {
            if (IS_GET) {
                return $this->display('device_bans_edit');
            } else {
                $map = [];
                if (empty($type) || empty($tag)) {
                    return $this->error("请填写完整信息");
                }
                if (\in_array($type, [3,4]) && !preg_match("/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/i", $tag)) {
                    return $this->error("请填写正确的url地址");
                }
                if ($type == 2 && !preg_match("/(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/i", $tag)) {
                    return $this->error("请填写正确的ip信息,如127.0.0.1");
                }
                if ($type == 1 && (preg_match("/(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/i", $tag) || preg_match("/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/i", $tag))) {
                    return $this->error("请填写正确的设备信息");
                }
                $map['type'] = $type;
                $map['tag'] = $tag;
                $item = M('device_bans', 'tab_')->where($map)->find();
                if ($item) {
                    return $this->error("该禁用已经存在(ID:{$item['id']})");
                }
                M('device_bans', 'tab_')->add(['type' => $type, 'tag' => $tag, 'create_time' => time(), 'operator_id' => is_login()]);
            }

            return $this->success("新增成功", U('Member/device_bans_list'));
        } else {
            M('device_bans', 'tab_')->where(['id' => $id])->delete();
            return $this->success("解除成功");
        }
    }
}