<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * 用户相关
 */
class User extends MY_Controller
{

    protected $pageNum = 15;//分页

    public $data = array('referer' => '', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    public $postdata = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
    protected $feedbackType = array(1 => '支付问题', 2 => '账号问题', 3 => '游戏BUG', 4 => '游戏建议');
    protected $vipLevelList = [1 => 'VIP1', 2 => 'VIP2', 3 => 'VIP3', 4 => 'VIP4'];
    protected $newPlayerList = ['NPAFB' => '安卓FB', 'NPIFB' => '苹果FB', 'NPAV' => '安卓游客', 'NPIV' => '苹果游客', 'NPAL' => '安卓LINE', 'NPIL' => '苹果LINE', 'NPAH' => '安卓华为'];

    protected $page = 10;//分页

    protected $pageConfig = array(
        'first_tag_open' => '<li>',
        'first_tag_close' => '</li>',
        'last_tag_open' => '<li>',
        'last_tag_close' => '</li>',
        'next_tag_open' => '<li>',
        'next_tag_close' => '</li>',
        'prev_tag_open' => '<li>',
        'prev_tag_close' => '</li>',
        'cur_tag_open' => "<li class='active'><a hef='#'>",
        'cur_tag_close' => "</a></li>",
        'num_tag_open' => "<li>",
        'num_tag_close' => "</li>",
    );

    public $typeMap = [
        'money' => [
            'id' => 14,
            'text' => '金币',
        ],
        'spins' => [
            'id' => 15,
            'text' => '体力',
        ],
        'shield' => [
            'id' => 16,
            'text' => '盾牌',
        ],
        'star' => [
            'id' => 42,
            'text' => '星星',
        ],
        'petExp' => [
            'id' => 8,
            'text' => '宠物经验'
        ],
        'petFood' => [
            'id' => 9,
            'text' => '宠物粮食'
        ],
        'card' => [
            'id' => 17,
            'text' => '卡片',
        ],
        'diamond' => [
            'id' => 22,
            'text' => '钻石',
        ],
    ];

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->library('pagination');

        $this->env = get_cookie($this->_wenenv);

        $this->load->model('oo');
    }

    public function index($uid = 0)
    {
        $data = [];
        if ($uid) {
            $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
            $postData = $this->postdata;
            $postData['mod'] = 'user';
            $postData['act'] = 'getUserInfo';
            $postData['uid'] = $uid;
            ($this->env == 2) && $postData['demo'] = 1;
            $res = $this->curl->req($url, $postData);
            $retData = json_decode($res, 1);
            if (!empty($retData)) {
                //当天获得金币
                $tb = otable::Assetslog(date("Ymd"), $uid);

                //当天获得金币,体力,钻石
                $sql = "SELECT SUM(num) num, type FROM {$tb} WHERE uid = {$uid} AND type IN('diamond','spins','money') AND crease = '+' GROUP BY type";
                $retArr = oo::commonOprDb('log')->getAll($sql, 1);
                $tmp = $retArr ? array_column($retArr, 'num', 'type') : [];
                $retData['todayMoney'] = isset($tmp['money']) ? $tmp['money'] : 0; //金币
                $retData['todaySpins'] = isset($tmp['spins']) ? $tmp['spins'] : 0; //体力
                $retData['todayDiamond'] = isset($tmp['diamond']) ? $tmp['diamond'] : 0; //钻石

                $this->load->database();
                $query = $this->db->query("SELECT * FROM t_robot WHERE uid={$uid}");
                $retData['isRobot'] = ($query && (!empty($query->row_array()))) ? '是' : '否';
                $retData['isVistor'] = (oo::commonOprModel('member')->getSiteuidByUid($uid) < 1) ? '是' : '否';
//                $retData['isVistor'] = ($retData['isVistor'] == 1)?'是':'否';
                $retData['isVip'] = ($retData['vip'] == 1 && $retData['vip_expire'] > time()) ? '是' : '否';
                $retData['userAdjustGroup'] = oo::commonOprModel('member')->getUserAdjustGroup($uid);

                //邀请次数
                $tb = otable::buryingPointLog();
                $sql = "SELECT count(*) as count FROM {$tb} WHERE uid = {$uid} AND event_id = 'invite_friend'";
                $ret = oo::commonOprDb('log')->getOne($sql, 1);
                $retData['invite_number'] = $ret['count'];

                //邀请成功人数
                $tb = otable::userinvitegiftbag();
                $sql = "SELECT * FROM {$tb} WHERE uid = {$uid}";
                $ret = oo::commonOprDb('slavedb')->getOne($sql, 1);
                $retData['invite_success'] = $ret['invitenum'];

                //国家
                $tb = otable::useraddress();
                $sql = "SELECT * FROM {$tb} WHERE uid = {$uid}";
                $ret = oo::commonOprDb('slavedb')->getOne($sql, 1);
                $retData['country_code'] = $ret['country_code'];

                $data = $retData;
            }
        }

        $data['propsConfig'] = oo::commonOprModel('config')->getPropsConfigFromLocal();
        $cardArr = oo::commonOprDb('slavedb')->getAll(sprintf("SELECT cgid,ciid,ci_name_zh FROM %s", otable::cardinfo_config()), MYSQLI_ASSOC);
        $cardGroupArr = oo::commonOprDb('slavedb')->getAll(sprintf("SELECT cgid,cg_name_zh as name FROM %s", otable::cardgroup_config()), MYSQLI_ASSOC);
        $cardGroupArr = array_column($cardGroupArr, null, 'cgid');
        foreach ($cardArr as $row) {
            $cardGroupArr[$row['cgid']]['card'][] = $row;
        }

        $data['cardConfig'] = $cardGroupArr;
        $data['oos_debug'] = $this->config->item('oos_debug');
        $data['vipLevelList'] = $this->vipLevelList;
        $data['slotTitle'] = [1 => "打", 2 => "偷", 3 => "体力", 4 => "盾牌", 5 => "1金币", 6 => "2金币", 7 => "3金币", 8 => "1金币袋", 9 => "2金币袋", 10 => "3金币袋", 11 => "空", 12 => "1收集物", 13 => "2收集物", 14 => "3收集物", 15 => "小玩法物1", 16 => "小玩法物2", 17 => "小玩法物3"];
        $this->load->view('user/index', $data);
    }

    /**
     * 拥有钻石的玩家信息
     */
    public function userDiamond($limit = 0)
    {
        $userid = (int)get_cookie('userid');
        $tb = otable::gh_gameserver();

        $totalSql = "SELECT COUNT(*) AS total FROM {$tb} WHERE  diamond > 0";
        if ($userid > 0) {
            $totalSql .= " AND mid = ${userid}";
        }
        $total = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);

        $sql = "SELECT * FROM {$tb} WHERE diamond > 0";
        if ($userid > 0) {
            $sql .= " AND mid = ${userid}";
        }
        $sql .= " ORDER BY diamond DESC LIMIT {$limit},{$this->pageNum}";
        $arr = oo::commonOprDb('slavedb')->getAll($sql, 1);
        $data['list'] = $arr;
        $data['total'] = $total['total'];
        $data['userid'] = $userid;

        //分页
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#user/userDiamond');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $this->pageNum;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $this->page;

        $this->load->view('user/userDiamond', $data);
    }

    /**
     * 清除用户所有数据
     */
    public function clearAcc()
    {
        $userid = $this->input->post('uid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'user';
        $postData['act'] = 'clear';
        $postData['uid'] = $userid;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        echo $retData['code'];
        exit();


    }


    /**
     *    查询用户信息
     */
    public function searchuser($uid = 0)
    {
        $data = $this->data;
        $data['message'] = '查询失败';
        $userid = $uid = $this->input->post('userid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        set_cookie('userid', $userid, 600);
        $postData = $this->postdata;
        $postData['mod'] = 'User';
        $postData['act'] = 'getUserInfo';
        if (is_numeric($userid)) {
            $postData['uid'] = $userid;
            $data['type'] = 'uid';
        } else {
            $postData['nick'] = $userid;
            $data['type'] = 'nick';
        }
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, 1);
        if (!empty($retData)) {
            if ($data['type'] == 'uid') {

                $this->load->database();
                $tb = otable::Robot();
                $ret = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE uid={$userid}", 1);

                $retData['isRobot'] = (!empty($ret)) ? '是' : '否';
                $retData['isVistor'] = (oo::commonOprModel('member')->getSiteuidByUid($userid) < 1) ? '是' : '否';
                $retData['userAdjustGroup'] = oo::commonOprModel('member')->getUserAdjustGroup($uid);

                //邀请次数
                $tb = otable::buryingPointLog();
                $sql = "SELECT count(*) as count FROM {$tb} WHERE uid = {$userid} AND event_id = 'invite_friend'";
                $ret = oo::commonOprDb('log')->getOne($sql, 1);
                $retData['invite_number'] = $ret['count'];

                //邀请成功人数
                $tb = otable::userinvitegiftbag();
                $sql = "SELECT * FROM {$tb} WHERE uid = {$userid}";
                $ret = oo::commonOprDb('slavedb')->getOne($sql, 1);
                $retData['invite_success'] = $ret['invitenum'];

                //国家
                $tb = otable::useraddress();
                $sql = "SELECT * FROM {$tb} WHERE uid = {$userid}";
                $ret = oo::commonOprDb('slavedb')->getOne($sql, 1);
                $retData['country_code'] = $ret['country_code'];

                $userDynamicsData = oo::commonOprModel('member')->getUserDynamicsData($uid);
                if (empty($userDynamicsData['groupId2'])) {
                    $retData['userGroupName'] = "未归类分组";
                } else {
                    $tb = otable::UserGroupConfig(2);
                    $userGroup = trim($userDynamicsData['groupId2'], ',');
                    $sql = "SELECT name FROM {$tb} WHERE id IN ({$userGroup})";
                    $ret = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);
                    $retData['userGroupName'] = implode(',', array_column($ret, 'name'));
                }
                if (empty($userDynamicsData['groupId3'])) {
                    $retData['userGroupNameSS'] = "未归类分组";
                } else {
                    $tb = otable::UserGroupConfig(2);
                    $userGroup = trim($userDynamicsData['groupId3'], ',');
                    $sql = "SELECT name FROM {$tb} WHERE id IN ({$userGroup})";
                    $ret = oo::commonOprDb('slavedb')->getAll($sql, MYSQLI_ASSOC);
                    $retData['userGroupNameSS'] = implode(',', array_column($ret, 'name'));
                }
            }
            $tb2 = otable::userEmailNew($userid);
            $sql2 = "SELECT * FROM {$tb2} where uid={$userid}";
            $emailInfo = oo::commonOprDb('slavedb')->getOne($sql2, 1);

            $retData['sumMoney'] = oo::commonOprModel('payment')->getUserTotalPayNum($userid);
            $data['state'] = 'success';
            $data['message'] = '成功';
            $data['emailInfo'] = $emailInfo;
            $retData['emailNew'] = $emailInfo['email'];
            $data['userinfo'] = $retData;
            $data['spinslost'] = oo::commonOprRedis('games')->hGetAll("USER_SLOTSPINSLOST:{$userid}");
        }
        die(json_encode($data));

    }

    /**
     *    操作用户金币
     */
    public function actionusermoney()
    {
        $data = $this->data;
        $data['message'] = '操作金币失败';
        $userid = $this->input->post('actionuid');
        $money = $this->input->post('newmoney');
        $newspins = $this->input->post('newspins');//体力
        $newshield = $this->input->post('newshield');//盾牌
        $newstar = $this->input->post('newstar');//星星
        $newdiamond = $this->input->post('newdiamond');//钻石
        $oos_debug = $this->config->item('oos_debug');
        if (!$oos_debug) {
            if ($money > 10000000) {
                $data['message'] = '单次操作金币不能大于10000000';
                die(json_encode($data));
            }
            if ($newspins > 1000) {
                $data['message'] = '单次操作体力不能大于1000';
                die(json_encode($data));
            }
            if ($newshield > 5) {
                $data['message'] = '单次操作盾牌不能大于5';
                die(json_encode($data));
            }
            if ($newstar > 100) {
                $data['message'] = '单次操作星星不能大于100';
                die(json_encode($data));
            }
        }


        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'user';
        $postData['act'] = 'actionUser';
        $postData['uid'] = $userid;
        $postData['money'] = $money;
        $postData['spins'] = $newspins;
        $postData['shield'] = $newshield;
        $postData['star'] = $newstar;
        $postData['diamond'] = $newdiamond;
        $isTest = 0;
        //记录后台操作的信息(内网不需要)
        if ($this->env == 1) {
            $recordData = json_encode(array('money' => $money, 'spins' => $newspins, 'shield' => $newshield, 'diamond' => $newdiamond));
            $username = get_cookie('username');
            $now = time();
            $this->load->database();
            $this->db->query("INSERT INTO userupdatemone(uum_name, uum_uid, uum_info, uum_time, is_test ) VALUES('{$username}', '{$userid}', '{$recordData}', {$now}, {$isTest})");
        }

        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);


        $retData = json_decode($res);
        if (!empty($retData)) {
            $data['state'] = 'success';
            $data['message'] = '成功';
            $data['retdata'] = $retData;
            $data['uid'] = $userid;
            $data['mylevel'] = 0;
        }
        die(json_encode($data));
    }

    /*
    *	认证LINE
    */
    public function actionline()
    {
        $data = $this->data;
        $data['message'] = '认证LINE失败';
        $userid = $this->input->post('actionuid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'user';
        $postData['act'] = 'actionLine';
        $postData['uid'] = $userid;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if (!empty($retData)) {
            $data['state'] = 'success';
            $data['message'] = '成功';
            $data['retdata'] = $retData['code'];
        }
        die(json_encode($data));
    }

    public function actionvip()
    {
        $uid = $this->input->post('vipuid');
        $level = $this->input->post('vip');
        $days = $this->input->post('vipdays');
        $oldLevel = $this->input->post('vipLevel');

        $data = $this->data;
        if (empty($uid) || empty($level) || empty($days) || ($oldLevel > 0 && $oldLevel != $level)) {
            $data['message'] = '参数错误';
            $data['retdata'] = [];
            die(json_encode($data));
        }

        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['uid'] = $uid;
        $postData['level'] = $level;
        $postData['days'] = $days;
        $postData['mod'] = 'user';
        $postData['act'] = 'addVip';
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if (!empty($retData)) {
            $data['state'] = 'success';
            $data['message'] = '成功';
            $data['retdata'] = $retData['list'];
        }
        die(json_encode($data));

    }


    public function actiondismiss()
    {
        $data = $this->data;
        $data['message'] = '驳回LINE失败';
        $userid = $this->input->post('actionuid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'user';
        $postData['act'] = 'actiondismiss';
        $postData['uid'] = $userid;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if (!empty($retData)) {
            $data['state'] = 'success';
            $data['message'] = '成功';
            $data['retdata'] = $retData['code'];
        }
        die(json_encode($data));
    }

    /**
     *    玩家牌局日志
     */
    public function pokerlog($page = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        if ($uid = intval(get_cookie('userid'))) {
            $data['uid'] = $uid;
            $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');

            //时间查询
            $dateArr = array();
            if ($stime = get_cookie('pokerlog_stime')) {
                $data['stime'] = $stime;
                $dateArr['stime'] = strtotime($stime);
            }
            if ($etime = get_cookie('pokerlog_etime')) {
                $data['etime'] = $etime;
                $dateArr['etime'] = strtotime($etime);
            }

            //获取数据
            $postData = array_merge($dateArr, $this->postdata);
            $postData['mod'] = 'pokerlog';
            $postData['act'] = 'getuserpokerlog';
            $postData['uid'] = $uid;
            $postData['limit'] = $this->page;
            $postData['page'] = $page;
            ($this->env == 2) && $postData['demo'] = 1;
            $res = $this->curl->req($url, $postData);
            $retData = json_decode($res, TRUE);

            //获取后的处理
            if (!empty($retData)) {
                $data['list'] = $retData['list'];
                $data['total'] = $retData['total'];

                //分页
                $pageConfig = $this->pageConfig;
                $pageConfig['base_url'] = base_url('#user/pokerlog');
                $pageConfig['total_rows'] = $retData['total'];
                $pageConfig['per_page'] = $this->page;
                $this->pagination->initialize($pageConfig);
                $pageurl = $this->pagination->create_links();
                $data['pageurl'] = $pageurl;
            }
        }
        $this->load->view('user/pokerlog', $data);
    }

    /**
     *    牌局详情
     */
    public function getpokerdetail()
    {
        $data = array('code' => 0, 'msg' => '');
        $inner_id = $this->input->post('inner_id');
        $tid = $this->input->post('tid');
        $month = $this->input->post('month');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');

        //获取数据
        $postData = $this->postdata;
        $postData['mod'] = 'pokerlog';
        $postData['act'] = 'getpokerdetail';
        $postData['inner_id'] = $inner_id;
        $postData['tid'] = $tid;
        $postData['month'] = $month;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if (!empty($retData)) {
            $data['code'] = 1;
            $data['msg'] = $retData;
        }
        die(json_encode($data));
    }

    /**
     *    玩家的金币流水查询
     */
    public function moneylog($page = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        $uid = $this->input->post('uid') ? $this->input->post('uid') : $this->input->get('uid');

//        if(empty($uid)){
//            echo json_encode($this->withNodata());exit;
//        }
        $data['uid'] = $uid;
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');

        //获取数据
        $postData = $this->postdata;
        $postData['mod'] = 'moneylog';
        $postData['act'] = 'getActionId';
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        $data['actionIdType'] = $retData['actionIdType'];

        $uid = $this->input->post('uid') ? $this->input->post('uid') : $this->input->get('uid');
        $data['uid'] = $uid;
        $this->load->view('user/moneylog', $data);
    }

    /**
     *    玩家的金币流水查询
     */
    public function moneylogData()
    {
//		$data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        $uid = $this->input->post('uid') ? $this->input->post('uid') : $this->input->get('uid');

        if (empty($uid)) {
            echo json_encode($this->withNodata());
            exit;
        }
        $data['uid'] = $uid;
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');

        $type = $this->input->post('type');//操作类型
        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
        $start = (int)$this->input->post('start');
        $length = (int)$this->input->post('length');

        //时间查询
        $dateArr = array();
        if ($stime) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        }
        if ($etime) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'moneylog';
        $postData['act'] = 'getusermoneylog';
        $postData['uid'] = $uid;
        $postData['type'] = $type;
        $postData['limit'] = $length;
        $postData['page'] = $start;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        //获取后的处理
        if (!empty($retData)) {
            //处理actionIdType
            $actionIdType = $retData['actionIdType'];
            foreach ($retData['list'] as &$v) {
                $v['actIdType'] = $actionIdType[$v['actID']] ?? '';
                $v['actionDate'] = date('Y-m-d H:i:s', $v['actiontime']);
                if ($v['gameid'] == 2) {
                    $v['gameid'] = '比赛场';
                } elseif ($v['gameid'] == 3) {
                    $v['gameid'] = '奥马哈';
                } elseif ($v['gameid'] == 4)
                    $v['gameid'] = '百人场';
                else {
                    $v['gameid'] = '德州';
                }
            }
            $data['recordsTotal'] = $retData['total'];
            $data['recordsFiltered'] = $retData['total'];
            $data['data'] = $retData['list'];
        } else {
            $data = $this->withNodata();
        }

        echo json_encode($data);
    }


    /**
     *    钻石流水
     */
    public function diamondlog($page = 0)
    {
        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');
        $uid = $this->input->post('uid') ? $this->input->post('uid') : $this->input->get('uid');
        $data['uid'] = $uid;
        $this->load->view('user/diamondlog', $data);
    }

    /**
     *    玩家的金币流水查询
     */
    public function diamondlogData()
    {
        $uid = $this->input->post('uid') ? $this->input->post('uid') : $this->input->get('uid');

        if (empty($uid)) {
            echo json_encode($this->withNodata());
            exit;
        }
        $data['uid'] = $uid;
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');

        $stime = $this->input->post('stime');
        $etime = $this->input->post('etime');
        $start = (int)$this->input->post('start');
        $length = (int)$this->input->post('length');

        //时间查询
        $dateArr = array();
        if ($stime) {
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime);
        }
        if ($etime) {
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime);
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);
        $postData['mod'] = 'moneylog';
        $postData['act'] = 'getuserdiamondlog';
        $postData['uid'] = $uid;
        $postData['limit'] = $length;
        $postData['page'] = $start;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        //获取后的处理
        if (!empty($retData)) {
            //处理actionIdType
            $actionIdType = $retData['actionIdType'];
            foreach ($retData['list'] as &$v) {
                $v['actIdType'] = $actionIdType[$v['actID']] ?? '';
                $v['actionDate'] = date('Y-m-d H:i:s', $v['actiontime']);
                if ($v['gameid'] == 2) {
                    $v['gameid'] = '比赛场';
                } elseif ($v['gameid'] == 3) {
                    $v['gameid'] = '奥马哈';
                } else {
                    $v['gameid'] = '德州';
                }
            }
            $data['recordsTotal'] = $retData['total'];
            $data['recordsFiltered'] = $retData['total'];
            $data['data'] = $retData['list'];
        } else {
            $data = $this->withNodata();
        }

        echo json_encode($data);
    }


    /**
     *    删除账号
     */
    public function clearAccount()
    {
        $userid = $this->input->post('uid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'user';
        $postData['act'] = 'clearAccount';
        $postData['uid'] = $userid;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        if ($retData['code'] == 1) {
            $tbl = otable::userChannel();
            oo::commonOprDb('games')->query("delete from {$tbl} where uid={$userid}");
        }
        echo $retData['code'];
        exit();
    }

    /**
     *    封账号
     */
    public function suspendAccount()
    {
        $userid = $this->input->post('uid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'user';
        $postData['act'] = 'suspendAccount';
        $postData['uid'] = $userid;
        ($this->env == 2) && $postData['demo'] = 1;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);
        echo $retData['code'];
        exit();
    }

    /**
     *    玩家的反馈
     */
    public function feedback($page = 0)
    {
        if (IS_POST) {
            $url = $this->config->item('officialNewUrl');
            $uid = $this->input->post('user_id');
            $postData['api'] = '/v1_1/sys/feedback/list';
            $postData['user_id'] = $uid;
            $res = $this->curl->req($url, $postData);
            die($res);
        }

        if ($page == 0) {
            $page = 50;
        } else {
            $page += 50;
        }

        $data = array('list' => '', 'uid' => 0, 'stime' => '', 'etime' => '', 'total' => '', 'pageurl' => '');

        $url = $this->config->item('officialNewUrl');
        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('feedback_stime')) {
            $data['stime'] = $stime;
            $dateArr['start_at'] = strtotime($stime . ' 0:0:1');
        }
        if ($etime = get_cookie('feedback_etime')) {
            $data['etime'] = $etime;
            $dateArr['end_at'] = strtotime($etime . '23:59:59');
        }
        if ($replyStatus = get_cookie('replyStatus')) {
            $data['replyStatus'] = $replyStatus;
            $dateArr['have_read'] = ($replyStatus == 1) ? 1 : 0;
        }
        //用户UID
        if ($uid = get_cookie('feedback_uid')) {
            $data['uid'] = $uid;
            $dateArr['user_id'] = $uid;
        }

        //获取数据
        $postData = array_merge($dateArr, $this->postdata);

        $postData['api'] = '/v1_1/sys/feedback/list';
        $postData['limit'] = 50;
        $postData['orientation'] = 1;
        $postData['page'] = $page / 50;


        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);


        //获取后的处理
        if (!empty($retData)) {
            $data['list'] = $retData['data'];
            $data['total'] = $retData['total'];

            //用户版本号
            $uidss = [];
            foreach ($data['list'] as $k => $v) {
                $uidss[] = $v['user_id'];
            }
            $uidss = json_encode($uidss);
            $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
            $postData = $this->postdata;

            $postData['uidss'] = $uidss;
            $postData['mod'] = 'Feedback';
            $postData['act'] = 'getUsersInfo';
            $res = $this->curl->req($url, $postData);

            $retData2 = json_decode($res, TRUE);

            $usersInfo = [];
            foreach ($retData2['data'] as $k => $v) {
                $usersInfo[$v['uid']] = $v['version'];
            }

            foreach ($data['list'] as $k => $v) {
                $data['list'][$k]['version2'] = $usersInfo[$v['user_id']];
            }

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#user/feedback');
            $pageConfig['total_rows'] = $retData['total'];
            $pageConfig['per_page'] = 50;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $this->load->view('user/feedback', $data);
    }

    /**
     *    回复玩家
     */
    public function actionfeedback()
    {
        $uid = $this->input->post('user_id');
        $reply = $this->input->post('content');
        $url = $this->config->item('officialNewUrl');
        $postData['api'] = '/v1_1/sys/feedback/add';
        $postData['user_id'] = $uid;
        $postData['type'] = "客服回复";
        $postData['content'] = $reply;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res, TRUE);

        $url = $this->config->item('officialUrl');
        $post = $this->postdata;
        $post['mod'] = 'Push';
        $post['act'] = 'feedback';
        $post['uid'] = $uid;
        $post['content'] = $reply;
        $this->curl->req($url, $post);
        if ($retData['code'] == 1) {
            $data['state'] = 1;
            $data['message'] = '成功';
        } else {
            $data['state'] = 0;
            $data['message'] = '失败';
        }
        die(json_encode($data));
    }

    /**
     *    标识已回复
     */
    public function updateFeedback()
    {
        $uid = $this->input->post('uid');
        $url = $this->config->item('officialNewUrl');
        $postData['api'] = '/v1_1/sys/feedback/have_read';
        $postData['user_id'] = $uid;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res);
        if ($retData->code == 1) {
            return $this->response(0, '操作成功');
        }
        return $this->response(-1, '操作失败');
    }

    public function delfeedback()
    {
        $uid = $this->input->post('uid');
        $url = $this->config->item('officialNewUrl');
        $postData['api'] = '/v1_1/sys/feedback/delete';
        $postData['user_id'] = $uid;
        $res = $this->curl->req($url, $postData);
        $retData = json_decode($res);
        if ($retData->code == 1) {
            return $this->response(0, '操作成功');
        }
        return $this->response(-1, '操作失败');
    }

    /**
     * line申请认证列表
     */
    public function lineauth($page = 0)
    {
        $data = array('list' => array(), 'total' => 0, 'pageurl' => '');
        $data['remarkStatus'] = [1 => '未认证', 2 => '已认证未加好友', 3 => '已认证加好友', 4 => '已认证入群'];
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        if ($remark = get_cookie('remark_lineauth')) {
            $this->postdata['remark'] = $remark;
        }

        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'lineauth';
        $this->postdata['limit'] = $this->page;
        $this->postdata['page'] = $page;
        $retData = $this->curl->req($url, $this->postdata);
        $list = json_decode($retData, TRUE);
        //print_r($list);
        if (is_array($list) && !empty($list)) {
            $data['list'] = $list['list'];
            $data['total'] = $list['count'];

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#user/lineauth');
            $pageConfig['total_rows'] = $data['total'];
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $data['remark'] = $remark;
        $this->load->view('user/lineauth', $data);
    }

    /**
     *    获取消息接口
     */
    public function newsList()
    {
        $data = array('list' => array(), 'total' => 0);
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'getSendNewsList';
        $retData = $this->curl->req($url, $this->postdata);
        $list = json_decode($retData, TRUE);
        //print_r($list);
        if (is_array($list) && !empty($list)) {
            $data['list'] = $list['list'];
            $data['total'] = $list['count'];

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#user/newsList');
            $pageConfig['total_rows'] = $list['count'];
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $this->load->view('user/newslist', $data);
    }

    /**
     *    新增消息
     */
    public function actionAddNews()
    {
        $usertype = $this->input->post('usertype');
        if ($usertype == 2) {
            $uidlist = $this->input->post('uidlist');
            $uidList = explode("\n", $uidlist);
            $this->postdata['uidlist'] = implode(',', $uidList);
        }
        $userContent = $this->input->post('news_content');
        if (empty($userContent)) {
            $this->data['state'] = 'error';
            $this->data['message'] = '内容不能为空';
            $this->data['refresh'] = false;
            die(json_encode($this->data));
        }
        $this->postdata['news_content'] = $this->input->post('news_content');
        $this->postdata['usertype'] = $usertype;

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'actionAddNews';
        $retData = $this->curl->req($url, $this->postdata);
        $r = json_decode($retData, 1);

        if ($r['code'] == 1) {
            $this->data['state'] = 'success';
            $this->data['message'] = '成功';
            $this->data['refresh'] = true;
        }
        die(json_encode($this->data));
    }

    /**
     *    新增公告
     */
    public function actionAddNotice()
    {
        $this->postdata['notice_stime'] = $this->input->post('notice_stime');
        $this->postdata['notice_etime'] = $this->input->post('notice_etime');
        $this->postdata['notice_content'] = $this->input->post('notice_content');
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'actionAddNotice';
        $retData = $this->curl->req($url, $this->postdata);
        $r = json_decode($retData, 1);
        if ($r['code'] == 1) {
            $this->data['state'] = 'success';
            $this->data['message'] = '成功';
            $this->data['refresh'] = true;
        }
        die(json_encode($this->data));
    }

    /**
     * 编辑备注
     * @return json
     */
    public function actionremark()
    {
        $uid = $this->input->post('uid');
        $remark = $this->input->post('remark');
        if (empty($uid) || empty($remark)) {
            return $this->response(1, '参数错误');
        }

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['uid'] = $uid;
        $this->postdata['remark'] = $remark;
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'actionremark';
        $retData = $this->curl->req($url, $this->postdata);
        $re = json_decode($retData, 1);
        if (isset($re['code']) && $re['code'] == 1) {
            return $this->response(0, '操作成功');
        }
        return $this->response(2, '操作失败');
    }


    /**
     * 玩家异常金流查询
     */
    public function anomalymoney($p = 0)
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('useranomalymoney_stime')) {
            $data['stime'] = date('Y-m-d', $stime);
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        } else {
            $data['stime'] = date("Y-m-d", strtotime('-1 days'));
        }

        if ($etime = get_cookie('useranomalymoney_etime')) {
            $data['etime'] = date('Y-m-d', $etime);
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d", strtotime(' -1 day'));
        }

        if ($uid = get_cookie('useranomalymoney_uid')) {
            $data['uid'] = $uid;
            $dateArr['uid'] = $uid;
        }

        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'abnormalSta';
        $this->postdata['limit'] = $this->page;
        $this->postdata['page'] = $p;
        $this->postdata['type'] = 1;
        $postData = array_merge($dateArr, $this->postdata);
        $retData = $this->curl->req($url, $postData);
        $re = json_decode($retData, 1);
        if ($re) {
            foreach ($re['list'] as $key => $row) {
                $re['list'][$key]['time'] = date('Y-m-d H:i:s', $row['time']);
            }
            $list = $re['list'];
            $total = $re['total'];
            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#user/anomalymoney');
            $pageConfig['total_rows'] = intval($total);
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $data['list'] = $list;
        $data['total'] = $total;
        $data['type'] = 1;
        $this->load->view('user/anomalymoney', $data);
    }

    /**
     * 玩家异常金流查询
     */
    public function anomalyspins($p = 0)
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        //时间查询
        $dateArr = array();
        if ($stime = get_cookie('useranomalymoney_stime')) {
            $data['stime'] = date('Y-m-d', $stime);
            $data['stime'] = $stime;
            $dateArr['stime'] = strtotime($stime . ' 0:0:1');
        } else {
            $data['stime'] = date("Y-m-d", strtotime('-1 days'));
        }

        if ($etime = get_cookie('useranomalymoney_etime')) {
            $data['etime'] = date('Y-m-d', $etime);
            $data['etime'] = $etime;
            $dateArr['etime'] = strtotime($etime . ' 23:59:59');
        } else {
            $data['etime'] = date("Y-m-d", strtotime(' -1 day'));
        }

        if ($uid = get_cookie('useranomalymoney_uid')) {
            $data['uid'] = $uid;
            $dateArr['uid'] = $uid;
        }

        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'abnormalSta';
        $this->postdata['limit'] = $this->page;
        $this->postdata['page'] = $p;
        $this->postdata['type'] = 2;
        $postData = array_merge($dateArr, $this->postdata);
        $retData = $this->curl->req($url, $postData);
        $re = json_decode($retData, 1);
        if ($re) {
            foreach ($re['list'] as $key => $row) {
                $re['list'][$key]['time'] = date('Y-m-d H:i:s', $row['time']);
            }
            $list = $re['list'];
            $total = $re['total'];
            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#user/anomalyspins');
            $pageConfig['total_rows'] = intval($total);
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
        }
        $data['list'] = $list;
        $data['total'] = $total;
        $data['type'] = 2;
        $this->load->view('user/anomalymoney', $data);
    }


    /**
     * 零牌局新玩家
     */
    public function zeronewplayer($p = 0)
    {
        $dateArr = $data = array();
        $str = '';

        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'zeronewplayer';
        $this->postdata['limit'] = $this->page;
        $this->postdata['page'] = $p;
        $postData = array_merge($dateArr, $this->postdata);
        $retData = $this->curl->req($url, $postData);
        $re = json_decode($retData, 1);
        if ($re) {
            $total = $re['total'];
            $userList = json_decode($re['zeroUserList'], 1);
            $dayList = $re['dayList'];

            $zeroUserArr = [];
            foreach ($dayList as $day) {
                $zeroUserTmp = json_decode($userList[$day], 1);
                foreach ($this->newPlayerList as $k => $v) {
                    $numTmp = $zeroUserTmp[$k] ?? 0;
                    !isset($zeroUserArr[$k]) && $zeroUserArr[$k] = [];
                    array_push($zeroUserArr[$k], $numTmp);
                }
            }

            foreach ($this->newPlayerList as $k2 => $v2) {
                $str .= $this->getSerialStr($v2, $zeroUserArr[$k2]) . ',';
            }

            $data['dayList'] = $dayList;
            $data['str'] = rtrim($str, ',');

            //分页
            $pageConfig = $this->pageConfig;
            $pageConfig['base_url'] = base_url('#user/zeronewplayer');
            $pageConfig['total_rows'] = intval($total);
            $pageConfig['per_page'] = $this->page;
            $this->pagination->initialize($pageConfig);
            $pageurl = $this->pagination->create_links();
            $data['pageurl'] = $pageurl;
            $data['list'] = $re['list'];
            $data['total'] = $total;
        }

        $this->load->view('user/zeronewplayer', $data);
    }


    public function getTotalMoneyRank()
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'getTotalMoneyRank';
        $postData = $this->postdata;
        $retData = $this->curl->req($url, $postData);
        $re = json_decode($retData, 1);
        $data['list'] = $re['list'];

        $this->load->view('user/total_money_rank', $data);
    }

    /**
     * 设置vip等级
     */
    public function setVipPoint()
    {
        if (!$this->config->item('oos_debug')) {
            return $this->response(-1, '操作失败1');
        }
        $uid = $this->input->post('actionuid');
        $updateInfo = [
            'svipPoint' => $this->input->post('vipPoint'),
        ];
        if (empty($updateInfo['svipPoint']) && $updateInfo['svipPoint'] != 0) {
            return $this->response(-1, '操作失败2');
        }
        oo::commonOprModel('member')->getUserInfo($uid, NULL, true, $updateInfo);
        die(json_encode(['state' => "success", 'message' => '操作成功',]));
    }

    public function openVip()
    {
        $uid = $this->input->post('uid');
        $day = $this->input->post('day');
        $url = $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['uid'] = $uid;
        $postData['day'] = $day;
        $postData['act'] = "openVip";
        $postData['mod'] = "Vip";
        $res = $this->curl->req($url, $postData);
//        $res = json_decode($res, true);
        die($res);
    }

    public function setLevel()
    {
        $uid = $this->input->post('actionuid');
        $levelId = $this->input->post('levelId');
        $url = $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['uid'] = $uid;
        $postData['levelId'] = $levelId;
        $postData['act'] = "setLevel";
        $postData['mod'] = "User";
        $res = $this->curl->req($url, $postData);
        if ($res >= 1) {
            die(json_encode([
                'state' => "success"
            ]));
        }
        return $this->response(-1, '操作失败');
    }

    public function log($uid, $type, $crease = 0, $sort = '')
    {
        if ($this->env == 1) {
            $url = $this->config->item('officialUrl');
        } else {
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }

        if ($date = get_cookie('date')) {
            $data['date'] = $date;
            $date = strtotime($date);
        } else {
            $data['date'] = date('Y-m-d');
            $date = strtotime($data['date']);
        }
        $rid = get_cookie('rid');


        /*
        $retData = $this->curl->req($url, [
            'frombg' => 1, 'mod' => 'User', 'act' => 'getTotalLog', 'lid' => 1, 'sid' => 1,'uid'=>$uid, 'stime'=>$stime, 'etime'=>$etime,
        ]);
        $retData= json_decode($retData, TRUE);
		*/
        $oos_debug = $this->config->item('oos_debug');
        if (!$oos_debug && time() - $date >= 8 * 24 * 3600) {
            $database = 'log2';
            $tb = otable::Assetslog2(date("Ymd", $date), $uid);
        } else {
            $database = 'log';
            $tb = otable::Assetslog(date("Ymd", $date), $uid);
        }

        $symbol = ['+' => 'add', '-' => 'low'];
        $types = ['money', 'spins', 'shield', 'star'];
        foreach ($symbol as $k => $v) {
            foreach ($types as $name) {
                $sql = "SELECT SUM(num) AS num FROM {$tb} WHERE uid = {$uid} AND type = '{$name}' AND crease = '{$k}'";
                $ret = oo::commonOprDb($database)->getOne($sql, 1);
                $retData[$name . $v] = $ret['num'];
            }
        }
        $data = array_merge($retData, ['uid' => $uid, 'type' => $type, 'crease' => $crease, 'sort' => $sort, 'date' => $data['date'], 'rid' => $rid]);
        $data['typeMap'] = $this->typeMap;
        $this->load->view('user/log', $data);
    }

    public function getlog()
    {
        $date = $this->input->post('date');

        $start = $this->input->post('start');
        $length = $this->input->post('length');
        $uid = $this->input->get('uid');
        $type = $this->input->get('type');
        $crease = $this->input->get('crease');
        $sort = $this->input->get('sort');

        $rid = $this->input->get('rid');
        /*
        if( $this->env == 1 ){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postdata['demo'] = 1;
        }
        $this->postdata['mod'] = 'User';
        $this->postdata['act'] = 'log';
        $this->postdata['start'] = $start;
        $this->postdata['length'] = $length;
        $this->postdata['uid'] = $uid;
        $this->postdata['type'] = $type;
        $this->postdata['crease'] = $crease;
        $this->postdata['sort'] = $sort;
        $this->postdata['stime'] = $stime;
        $this->postdata['etime'] = $etime;

        $retData = $this->curl->req($url, $this->postdata);
        $retData= json_decode($retData, TRUE);
        foreach ($retData['list'] as $row){
            $temp = $row;
            $temp['time'] = date('Y-m-d H:i:s',$temp['time']);
            $list[] = $temp;
        }
        */
        $oos_debug = $this->config->item('oos_debug');
        if (!$oos_debug && time() - $date >= 8 * 24 * 3600) {
            $database = 'log2';
            $tb = otable::Assetslog2(date("Ymd", $date), $uid);
        } else {
            $database = 'log';
            $tb = otable::Assetslog(date("Ymd", $date), $uid);
        }
        if ($type != 'all') {
            $sql = " SELECT * FROM {$tb} WHERE uid={$uid} ";
            $sql2 = " SELECT count(1) as total FROM {$tb} WHERE uid={$uid} ";
            $typeId = $this->typeMap[$type]['id'];
            $whereType = " AND type in ('{$type}', {$typeId}) ";
            $sql .= $whereType;
            $sql2 .= $whereType;
        } else {
            $sql = "SELECT * FROM {$tb} WHERE uid={$uid}";
            $sql2 = " SELECT count(1) as total FROM {$tb} WHERE uid={$uid}";
        }
        if ($crease == 1) {
            $sql = $sql . " AND crease='+'";
            $sql2 = $sql2 . " AND crease='+'";
        } else if ($crease == 2) {
            $sql = $sql . " AND crease='-'";
            $sql2 = $sql2 . " AND crease='-'";
        }
        if (!empty($stime)) {
            $sql = $sql . " AND time >= '{$stime}'";
            $sql2 = $sql2 . " AND time >= '{$stime}'";
        }
        if (!empty($etime)) {
            $sql = $sql . " AND time <= '{$etime}'";
            $sql2 = $sql2 . " AND time <= '{$etime}'";
        }

        //根据来源查
        if (!empty($rid)) {
            $sql = $sql . " AND rid={$rid}";
            $sql2 = $sql2 . " AND rid={$rid}";
        }

        if (!empty($sort)) {
            if ($sort == 'DESC') {
                $sql = $sql . " ORDER BY `num` DESC,`time` DESC LIMIT {$start}, {$length}";
            } else {
                $sql = $sql . " ORDER BY `num` ASC,`time` DESC LIMIT {$start}, {$length}";
            }
        } else {
            $sql = $sql . " ORDER BY `time` DESC LIMIT {$start}, {$length}";
        }


        $list = oo::commonOprDb($database)->getAll($sql, MYSQLI_ASSOC);
        foreach ($list as $k => $v) {
            $list[$k]['time'] = date("Ymd H:i:s", $v['time']);
        }
        $list2 = oo::commonOprDb($database)->getOne($sql2, MYSQLI_ASSOC);
        $actProp = ["25" => "建筑大师", "26" => "气球", "27" => "体力加速", "28" => "金币爆炸", "31" => "疯狂倍率", "32" => "建筑打折", "33" => "卡片爆炸", "34" => "商场优惠券"];
        if (!empty($list)) {
            $reason = oo::commonOprModel('statistics')->reason;
            $propCfg = oo::cfg('props');
            foreach ($list as $key => $row) {
                $list[$key]['rid'] = $reason[$row['rid']] ? $reason[$row['rid']] : $row['rid'];
                if (in_array($row['type'], array_keys($propCfg))) {
                    $list[$key]['type'] = $propCfg[$row['type']]['name'];
                    if (in_array($row['type'], array_keys($actProp))) {
                        $list[$key]['num'] = $list[$key]['num'] . "分钟";
                    }
                }
            }
            $data['data'] = $list;
            $data['recordsTotal'] = $list2['total'];
            $data['recordsFiltered'] = $list2['total'];
        } else {
            $data = $this->withNodata();
        }

        die(json_encode($data));
    }

    public function chatLock()
    {
        $uid = $this->input->post('uid');
        $remark = $this->input->post('remark');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'User';
        $postData['act'] = 'chatLock';
        $postData['uid'] = $uid;
        $postData['remark'] = $remark;
        $res = $this->curl->req($url, $postData);
        if ($res) {
            die($res);
        }
        die($res);
    }


    /*
    * 添加道具
    */
    public function actionProps()
    {
        $props = $this->input->post('props');
        $uid = $this->input->post('actionuid');
        $url = ($this->env == 2) ? $this->config->item('localUrl') : $this->config->item('officialUrl');
        $postData = $this->postdata;
        $postData['mod'] = 'User';
        $postData['act'] = 'actionProps';
        $postData['props'] = json_encode($props, JSON_NUMERIC_CHECK);
        $postData['uid'] = $uid;
        $retData = $this->curl->req($url, $postData);
        $retData = json_decode($retData, 1);
        if ($retData['code'] == 1) {
            $data['state'] = 'success';
            $data['message'] = '添加成功';
        } else {
            $data['state'] = '';
            $data['message'] = '添加失败';
        }
        die(json_encode($data));
    }

    public function gift()
    {
        $posts = ['frombg' => 1, 'lid' => 1, 'sid' => 1];
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $props = $data['props'] = json_decode($config, true)['props'];
        if (oo::isPost()) {
            $input = $this->input->post();
            $stime = strtotime($input['stime']);
            $etime = strtotime($input['etime'] . " 23:59:59");
            $start = $input['start'];
            $length = $input['length'];
            $uid = $input['uid'];
            $where = "WHERE created_at >= '{$stime}' AND created_at <= '{$etime}'";
            if (!empty($uid)) {
                $where .= " AND uid='{$uid}'";
            }
            $tb = otable::UserGiftList();
            $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} {$where} ORDER BY `created_at` DESC LIMIT {$start}, {$length}", MYSQLI_ASSOC);
            $ret2 = oo::commonOprDb('slavedb')->getOne("SELECT count(*) as total FROM {$tb} {$where}", MYSQLI_ASSOC);
            if (!empty($ret)) {
                foreach ($ret as $key => $v) {
                    $reward = '';
                    $rewardInfo = json_decode($v['reward'], true);
                    if (!empty($rewardInfo) && is_array($rewardInfo)) {
                        foreach ($rewardInfo as $type => $num) {//遍历奖励
                            $reward .= " 道具:";
                            foreach ($num as $row) {
                                $reward .= $props[$row['propsId']]['msg'] . "X" . $row['num'] . ",";
                            }
                            $reward = trim($reward, ',');
                        }
                        $ret[$key]['reward'] = $reward;
                    }
                    $ret[$key]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
                    $ret[$key]['expired_at'] = date('Y-m-d H:i:s', $v['expired_at']);
                    if ($v['rewarded_at']) {
                        $ret[$key]['rewarded_at'] = date('Y-m-d H:i:s', $v['rewarded_at']);
                    } else {
                        $ret[$key]['rewarded_at'] = "未领取";
                    }
                    if ($v['from'] == 1) {
                        $ret[$key]['from'] = "补偿礼包";
                    } else if ($v['from'] == 2) {
                        $ret[$key]['from'] = "AIHelp礼包";
                    }
                }
                $data['data'] = $ret;
                $data['recordsTotal'] = $ret2['total'];
                $data['recordsFiltered'] = $ret2['total'];
            } else {
                $data = $this->withNodata();
            }
            die(json_encode($data));
        }
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-6 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d');
        $data['uid'] = get_cookie('uid') ?? "";
        $this->load->view('user/gift', $data);
    }

    public function actionGift()
    {
        $input = $this->input->post();
        $props = $input['props'];
        foreach ($props['id'] as $key => $row) {
            if ($props['num'][$key] <= 0) {
                continue;
            } else {
                $reward['props'][] = [
                    'propsId' => $row,
                    'num' => $props['num'][$key],
                ];
            }
        }
        if (empty($reward)) {
            return $this->response(1, '奖励空');
        }
        $uid = intval($input['uid']);
        $from = 1;
        $created_at = time();
        $expired_at = strtotime($input['expired_at']);
        $remark = $input['remark'];
        $reward = json_encode($reward, JSON_NUMERIC_CHECK);
        $tb = otable::UserGiftList();
        oo::commonOprDb('games')->query("INSERT INTO {$tb}(uid,`from`,reward,created_at,expired_at,remark) VALUES('{$uid}', '{$from}', '{$reward}', '{$created_at}','{$expired_at}', '{$remark}')");
        oo::commonOprModel('Workerman')->push($uid, "User_gift", []);
        return $this->response(0, '操作成功');
    }

    public function actionGiftDel()
    {
        $id = $this->input->post('id');
        $tb = otable::UserGiftList();
        oo::commonOprDb('games')->query("DELETE FROM {$tb} WHERE id={$id}");
        return $this->response(0, '操作成功');
    }

    public function customize()
    {
        $adminid = get_cookie('adminid');
        $this->config->load('menu', TRUE);
        $menu = $this->config->item('menu', 'menu');
        $this->load->database();
        $query = $this->db->get_where('permission', array('adminid' => $adminid));
        $row = $query->row_array();
        if ($row) {
            $permission = unserialize($row['list']);
            if (!$this->isAdmin() && $this->session->userdata("role")) {
                $role = $this->db->get_where('cmsrole', array('id' => $this->session->userdata("role")))->row_array();
                $permission = array_merge($permission, unserialize($role['rule']));
            }
            foreach ($menu as $k => &$v) {
                if (!$this->isAdmin()) {
                    if ($v['url'] && !in_array($v['url'], $permission)) {
                        unset($menu[$k]);
                    }
                    if ($v['child']) {
                        $needDelK = true;
                        foreach ($v['child'] as $t => $val) {
                            if (!in_array($val['url'], $permission)) {
                                unset($menu[$k]['child'][$t]);
                            } else {
                                $needDelK = false;
                            }
                        }
                        if ($needDelK) unset($menu[$k]);
                    }
                }
            }
        }
        //循环处理一下child下的key
        foreach ($menu as $tempk => &$tempv) {
            if ($tempv['child']) {
                $tempv['child'] = array_values($tempv['child']);//有key的话,memu就不显示
            }
        }
        $data['menu'] = $menu;

        $tb = otable::cmsPermission();
        $ret = oo::commonOprDb('default')->getOne("SELECT * FROM {$tb} WHERE adminid={$adminid} LIMIT 1", MYSQLI_ASSOC);
        $data['rule'] = json_decode($ret['customize'], true);

        $this->load->view('user/customize', $data);
    }

    public function actionCustomize()
    {
        $list = $this->input->post("urllist");
        $adminid = get_cookie('adminid');
        $list = addslashes(json_encode(array_values(array_filter(array_unique($list)))));
        $tb = otable::cmsPermission();
        oo::commonOprDb('default')->query("UPDATE {$tb} SET `customize`='{$list}' WHERE adminid={$adminid} LIMIT 1");
        return $this->response(0, '操作成功');
    }

    public function props()
    {
        $uid = $this->input->post("uid");
        $config = oo::commonOprModel('config')->getPropsConfig();
        $userProps = oo::commonOprModel('config')->getUserPropsData($uid);
        foreach ($userProps as &$props) {
            $props['name'] = $config[$props['id']]['name'];
            unset($props['type']);
            unset($props['status']);
            unset($props['status']);
            unset($props['expire']);
            unset($props['time']);
        }
        return $this->response(0, '操作成功', $userProps);
    }

    public function card()
    {
        $uid = $this->input->post("uid");
        $cacheKey = okeys::UserCardInfo($uid);
        $cache = oo::commonOprRedis('games')->get($cacheKey);
        if (!$cache) {
            $tb = otable::usercard_config($uid);
            $sql = "SELECT * FROM {$tb} WHERE uid={$uid} ";
            $ret = oo::commonOprDb('slavedb')->getOne($sql, MYSQLI_ASSOC);
            $ciidArr = json_decode($ret['ciid'], true) ?? [];
        } else {
            $cache = json_decode($cache, true);
            $ciidArr = $cache['ciid'];
        }
        ksort($ciidArr);
        $out = [];
        if (!empty($ciidArr)) {
            $tb = otable::cardinfo_config();
            $sqlKey = implode(',', array_keys($ciidArr));
            $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE ciid IN ({$sqlKey})", 1);
            $sqlKey = implode(',', array_column($ret, 'cgid'));
            $ret = array_column($ret, null, 'ciid');

            $cardGroupArr = oo::commonOprDb('slavedb')->getAll(sprintf("SELECT cgid,cg_name_zh as name FROM %s WHERE cgid IN (%s)", otable::cardgroup_config(), $sqlKey), MYSQLI_ASSOC);
            $cardGroupArr = array_column($cardGroupArr, null, 'cgid');
            foreach ($ciidArr as $ciid => $row) {
                $cardGroupArr[$ret[$ciid]['cgid']]['card'][] = [
                    'num' => $row,
                    'name' => $ret[$ciid]['ci_name_zh']
                ];
            }
            $out = $cardGroupArr;
        }
        return $this->response(0, '操作成功', $out);
    }

    public function actionCard()
    {
        $uid = $this->input->post("actionuid");
        $inputCard = $this->input->post("card");
        $postData = $this->postdata;
        $postData['mod'] = 'card';
        $postData['act'] = 'actionAddUserCard';
        $postData['uid'] = $uid;
        $card = [];
        foreach ($inputCard['id'] as $key => $row) {
            $card[$row] = $inputCard['num'][$key];
        }
        if (!empty($card)) {
            $postData['card'] = json_encode($card, JSON_NUMERIC_CHECK);
            $this->curl->req($this->config->item('officialUrl'), $postData);
        }
        return $this->response(0, '操作成功');
    }

    public function pet()
    {
        $uid = $this->input->post("uid");
        $cacheKey = okeys::UserPet2($uid);
        $userPetArr = oo::commonOprRedis('games')->hGetAll($cacheKey);
        if (empty($userPetArr)) {
            $tb = otable::UserPet($uid);
            $userPetArr = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE uid={$uid}", MYSQLI_ASSOC);
        } else {
            $userPetArr = array_values($userPetArr);
            foreach ($userPetArr as $key => $row) {
                $userPetArr[$key] = json_decode($row, true);
            }
        }
        $name = [
            1 => "偷宠物",
            2 => "盾牌宠物",
            3 => "攻击宠物",
        ];
        foreach ($userPetArr as $key => $row) {
            $userPetArr[$key]['name'] = $name[$row['petId']];
        }
        return $this->response(0, '操作成功', $userPetArr);
    }

    //多天流水查询
    public function manyDaysLog($uid = 0)
    {
        $data['stime'] = get_cookie('stime') ?? date('Y-m-d', strtotime("-1 days"));
        $data['etime'] = get_cookie('etime') ?? date('Y-m-d');
        $data['uid'] = empty($uid) ? get_cookie('uid') : $uid;
        $data['rid'] = get_cookie('rid') ?? 0;

        /*
        //运营需求改成ajax请求
        $pageTemp['page'] = $page;
        $pageTemp['limit'] = 100;
        $ret = oo::commonOprModel('statistics')->manyDaysLog($data['uid'],$data['stime'],$data['etime']," rid = {$data['rid']} AND uid = {$data['uid']}",$pageTemp);
        $data['list'] = $ret['list'];
        $data['total'] = $ret['total'];
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#user/manyDaysLog');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 100;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;
        */

        $this->load->view('user/manyDaysLog2', $data);
    }

    public function getmanyDaysLog()
    {
        $start = $this->input->post('start');
        $length = $this->input->post('length');
        $uid = $this->input->get('uid');
        $rid = $this->input->get('rid');
        $stime = $this->input->get('stime');
        $etime = $this->input->get('etime');
        $pageTemp['page'] = $start;
        $pageTemp['limit'] = $length;
        $list = oo::commonOprModel('statistics')->manyDaysLog($uid, $stime, $etime, " rid = {$rid} AND uid = {$uid}", $pageTemp);
        $actProp = ["25" => "建筑大师", "26" => "气球", "27" => "体力加速", "28" => "金币爆炸", "31" => "疯狂倍率", "32" => "建筑打折", "33" => "卡片爆炸", "34" => "商场优惠券"];
        if (!empty($list['list'])) {
            $reason = oo::commonOprModel('statistics')->reason;
            foreach ($list['list'] as $key => $row) {
                $list['list'][$key]['rid'] = $reason[$row['rid']] ? $reason[$row['rid']] : $row['rid'];
                $list['list'][$key]['time'] = date("Ymd H:i:s", $row['time']);
                if (in_array($row['type'], array_keys($actProp))) {//活动道具
                    $list['list'][$key]['type'] = $actProp[$row['type']];
                    $list['list'][$key]['num'] = $list['list'][$key]['num'] . "分钟";
                }
            }
            $data['data'] = $list['list'];
            $data['recordsTotal'] = $list['total'];
            $data['recordsFiltered'] = $list['total'];
        } else {
            $data = $this->withNodata();
        }
        die(json_encode($data));
    }

    public function activityData($uid, $activity = "")
    {
        if (empty($activity)) {
            $this->load->view('user/activityData/index', ["uid" => $uid, "list" => ["treasure" => "宝藏探索"]]);
        } else {
            $data["tips"] = "";
            $key = okeys::userBindActivity($activity, $uid);
            $aid = oo::commonOprRedis('games')->get($key);
            if (!$aid) {
                $data["tips"] = "用户当前无该类型活动";
            }
            switch ($activity) {
                case "treasure":
                    $data["bonus"] = intval(oo::commonOprRedis('games')->hGet(okeys::TreasureSpend($aid), "BONUS_" . $uid));
                    $data["total"] = intval(oo::commonOprRedis('games')->hGet(okeys::TreasureSpend($aid), "TOTAl_" . $uid));
                    break;
            }
            $this->load->view('user/activityData/' . $activity, $data);
        }

    }

    public function setTrafficPermit()
    {
        $data = $this->input->post();
        $postData = $this->postdata;
        $postData['mod'] = 'Activitynew';
        $postData['act'] = 'operateUserTrafficPermit';
        $postData['option'] = $data['option'];
        $postData['lv'] = $data['lv'];
        $postData['uid'] = $data['uid'];
        $postData['type'] = $data['type'];
        $url = $this->config->item('officialUrl');
        $res = $this->curl->req($url, $postData);
        echo $res;
    }


    public function getGleicheUinfo()
    {
        $siteuid = $this->input->post('siteuid');
        $tb1 = otable::userinfo();
        $sql1 = "Select uid from {$tb1} where  siteuid={$siteuid}  order by createtime desc limit 5";
        $uidList = oo::commonOprDb('games')->getAll($sql1, 1);
        $uidListN = array_column($uidList, 'uid');
        $account = oo::commonOprModel('member')->getAccount($siteuid);
        $data['gleicheUidList'] = implode(',', $uidListN);
        $data['ssuid'] = $account['uid'];
        $data['list'] = $uidList;
        $this->response(1, '', $data);
    }

    public function changeUid()
    {
        $uid2 = $this->input->post('useUid');
        $uid = $this->input->post('toChangeUid');

        if (empty($uid) || $uid == 0) {
            return $this->response(-1, '操作失败 变更uid 不为空');
        }

        $tb1 = otable::userinfo();
        $sql1 = "Select * from {$tb1} where  uid in ({$uid},{$uid2})";
        $list = oo::commonOprDb('games')->getAll($sql1, 1);
        $uList = array_column($list, null, 'uid');
        if ($uList[$uid]['siteuid'] != $uList[$uid2]['siteuid']) {
            return $this->response(-1, '两个账号信息不一致', $uList);
        }
        if ($uList[$uid]['status'] != 1) {
            oo::commonOprModel('member')->updateUserInfo($uid, ["status" => 1]);
            oo::commonOprModel('member')->updateUserInfo($uid2, ["status" => 3]);
        }
        $siteUid = $uList[$uid2]['siteuid'];
        $tb = otable::taccount();
        $sql = "UPDATE {$tb} SET uid={$uid} WHERE uid={$uid2} AND siteuid='{$siteUid}'";
        $res = oo::commonOprDb('games')->query($sql, 1);
        if (!$res) {
            return $this->response(-1, '数据库操作失败', ['sql' => $sql]);
        }
        oo::commonOprRedis('games')->setex(okeys::account($siteUid), $uid, 14 * 86400);
        return $this->response(0, '操作成功');
    }

    //邀请信息查询
    public function inviteQuery()
    {
        $this->load->view("user/inviteQuery", []);
    }

    //邀请信息查询
    public function searchInviteData()
    {
        return $this->response(0, '操作成功', $this->getInviteData($this->input->post()));
    }

    private function getInviteData($params)
    {
        $info = [];
        switch ($params['type']) {
            case 'invitee':
                $uid = intval($params['invitee']);
                $tb = "crazygod_api_adjuststa.t_adjust_sta_" . $uid % 100;
                $sql = "select * from {$tb} where uid = {$uid};";
                $results = oo::commonOprDb('slavedb')->getOne($sql);

                $where = "";
                if ($results['android']) {
                    $where .= "gps_adid = '" . $results['android'] . "'";
                } elseif ($results['ios']) {
                    $where .= "adid = '" . $results['ios'] . "' or idfa = '" . $results['ios'] . "'";
                } else {
                    $where = "0=1";
                }

                $sql = "select tracker_name,created_at,label,tracker_token from crazygod_api_adjuststa.t_adjust_data where {$where};";
                $info = oo::commonOprDb('slavedb')->getAll($sql);
                foreach ($info as &$oneInfo) {
                    $oneInfo['label'] = !is_null($oneInfo['label']) ? base64_decode($oneInfo['label']) : '';
                    $oneInfo['created_at'] = date('Y-m-d H:i:s', $oneInfo['created_at']);
                }

                break;
            case 'inviter':
                $uid = intval($params['inviter']);

                $sql = "select * from crazygod_api_userinvite.invite_suc where is_senduid = {$uid};";
                $info = oo::commonOprDb('slavedb')->getAll($sql);
                foreach ($info as &$oneInfo) {
                    $oneInfo['is_time'] = date('Y-m-d H:i:s', $oneInfo['is_time']);
                }
                break;
        }

        return $info;
    }
}
