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

/**
 * 配置相关
 */
class Config extends MY_Controller
{
    public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    //老虎机title
    private $_role_title = ['关卡','攻击<br/>(概率)','偷袭<br/>(概率)','体力<br/>(概率)','护盾<br/>(概率)','1个金币<br/>(概率,金币)','2个金币<br/>(概率,金币)','3个金币<br/>(概率,金币)','1个钱袋<br/>(概率,金币)','2个钱袋<br/>(概率,金币)','3个钱袋<br/>(概率,金币)','没有奖励<br/>(概率)','活动<br/>(概率)'];
    private $_role_title2 = ['关卡','攻击<br/>(权重)','偷袭<br/>(权重)','体力<br/>(权重)','护盾<br/>(权重)','1个金币<br/>(权重,金币)','2个金币<br/>(权重,金币)','3个金币<br/>(权重,金币)','1个钱袋<br/>(权重,金币)','2个钱袋<br/>(权重,金币)','3个钱袋<br/>(权重,金币)','没有奖励<br/>(权重)','活动物品1<br/>(权重)','活动物品2<br/>(权重)','活动物品3<br/>(权重)','小玩法物品1<br/>(权重)','小玩法物品2<br/>(权重)','小玩法物品3<br/>(权重)','一个偷<br/>(权重)','两个偷<br/>(权重)','一个打<br/>(权重)','两个打<br/>(权重)','1体力瓶<br/>(权重)','2体力瓶<br/>(权重)'];

    //大转盘title
    private $_turn_title = ['关卡','id0<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id1<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id2<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id3<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id4<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id5<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id6<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id7<br/>概率<br/>支付概率<br/>广告概率<br/>金币'];
    private $_turn_title2 = ['关卡','id0<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id1<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id2<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id3<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id4<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id5<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id6<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id7<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id8<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id9<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id10<br/>概率<br/>支付概率<br/>广告概率<br/>金币','id11<br/>概率<br/>支付概率<br/>广告概率<br/>金币'];

    private $_turn_spins_title = ['关卡','id0<br/>概率,体力','id1<br/>概率,体力','id2<br/>概率,体力','id3<br/>概率,体力','id4<br/>概率,体力','id5<br/>概率,体力','id6<br/>概率,体力','id7<br/>概率,体力'];
    // 建筑物价格
    private $_build_title = ['关卡','建筑','雕像','风景','生物','科技'];
    // 关卡配置
    private $level_title;
    // 矿工配置
    private $mining_title = ['关卡','初始收益','收益上限','矿工一(价格，收益)','矿工二','矿工三','矿工四','矿工五'];
    // 任务配置
    private $task_type = ['任务ID','名称','名称（英文）','名称（繁體）','名称（法语）','名称（德语）','名称（西班牙）','名称（葡萄牙）','名称（泰语）','任务类型','类型:1金币,2体力,3卡片,4星星','奖励数量','任务目标值'];
    // 成就配置
    private $achi_type = ['成就ID',
        '名称','名称（英文）','名称（繁體）','名称（法语）','名称（德语）','名称（西班牙）','名称（葡萄牙）','名称（泰语）',
        '成就内容','成就内容（英文）','成就内容（繁體）','成就内容（法语）','成就内容（德语）','成就内容（西班牙）','成就内容（葡萄牙）','成就内容（泰语）',
        '目标阶段','成就奖励（体力，金币）'
    ];
    // 基礎配置
    private $base_type = ['ID','名称','配置模块','配置类型','配置值'];

    private $symbol_type = ['进度','数量','奖励类型(1金币,2体力,3卡片)','奖励数量(卡片ID)'];

    //服务器读取配置 老虎机配置类
    private $_SlotConfigPath = './public/config/SlotConfig.json';
    //服务器读取配置 大转盘配置类
    private $_TurnConfigPath = './public/config/TurnConfig.json';
    //服务器读取配置 建筑升级价格配置
    private $_BuildConfigPath = './public/config/BuildConfig.json';
    //备份文件
    private $_ConfigPathBak = '/home/wwwroot/crazy_god_CMS/public/config/bak/data_';
    //能编辑的权限
    private $editUserList = ['yzt','yjb'];
    //预设表名
    private $dbTable = ['slot','turn'];

    private $treasurepro_title = ['关卡','转盘','小王子*3','狐狸*3','小王子*2','王冠*3','小王子*1','黑桃*3','红桃*3','方块*3','黑桃+红桃+方块','没有奖励','转盘1','转盘2','转盘3','转盘4','转盘5','转盘6','转盘7'];

    public function __construct()
    {
//        date_default_timezone_set("Asia/Shanghai");
        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->_url = $this->config->item('officialUrl');
        //判断model是否存在
        if (file_exists(APPPATH.'models/Common.php'))
        {
            $this->load->model('common');
        }
        $levelTiele = oo::cfg('lang')['lang_level'];
        $this->level_title = array_merge(["关卡"],array_values($levelTiele),['图标ID','奖励','奖励配置']);
    }

    public function setPath($config){
        $this->load->library('uploader', $config);
    }

    /***
     * 配置数据处理
     */
    public function actionBasic_config()
    {
        $postData = $this->input->post();
        $username = get_cookie('username');
        $table = get_cookie('setTable');  //看看是处理那个表
        //不在范围内的直接退出
        if(!in_array($table,$this->dbTable)){
            $this->data['message'] = "a数据库错误！！！";
            die(json_encode($this->data));
        }
        //获取配置文件
        if($table == "slot"){
            $fileName = $this->_SlotConfigPath;
        }else if($table == "turn"){
            $fileName = $this->_TurnConfigPath;
        }else{
            $this->data['message'] = "b数据库错误！！！";
            die(json_encode($this->data));
        }
        if(!file_exists($fileName)){
            $list = [];
        }else{
            $list = json_decode(file_get_contents($fileName), 1);
        }
        if($postData['type'] == 1){
            //修改
            foreach ($list as $k=>$v){

                if($postData['data'][$k]){

                    $list[$k] = $postData['data'][$k];
                    //执行修改数据库方法
                    $posts = $this->postData;
                    $posts['mod'] = 'Config';
                    $posts['act'] = 'optConfig';
                    $posts['actStatus'] = $postData['type'];
                    $posts['levelId'] = $k;
                    $posts['tb'] = $table; // 表
                    $posts['slotpro'] = json_encode($postData['data'][$k]);
                    $posts['update_desc'] =$username.date('Y-m-d H:i:s',time());
                    $url = $this->config->item('officialUrl');
                    $retData = $this->curl->req($url, $posts);
                }
            }
        }else{
            //添加到数据库
            $posts = $this->postData;
            $posts['mod'] = 'Config';
            $posts['act'] = 'optConfig';
            $posts['actStatus'] = $postData['type'];
            $posts['tb'] = $table; // 表
            $posts['slotpro'] = json_encode($postData['data'][0]);
            $posts['update_desc'] =$username.date('Y-m-d H:i:s',time());
            $url = $this->config->item('officialUrl');
            $retData = $this->curl->req($url, $posts);
            $list[$retData] = $postData['data'][0];
        }
        if($retData>0){
            $bakName = $this->_ConfigPathBak.$table.$username.'_'.date('Ymd_His');
            //备份修改前文件
            exec("cp {$fileName} {$bakName}");
            $flag = file_put_contents($fileName, json_encode($list));
            if($flag){
                $data['state'] = 'success';
                $data['message'] = '更新成功1';
                $data['refresh'] = TRUE;
            }
        }
        die(json_encode($data));
    }

    /**
     * 修改虎机配置请求
     */
    public function actionSolt()
    {
        $username = get_cookie('username');
        $fileName = $this->_SoltConfigPath;
        $bakName = $this->_SoltConfigPathBak.$username.'_'.date('Ymd_His');
        $this->actionTemplate($fileName, $bakName, 'soltConfig');
        return true;
    }

    public function actionTemplate($fileName, $bakName, $configKey, $charKeyList = [])
    {
        oo::logs()->adminlog($this->router->fetch_method());

        $username = get_cookie('username');
        if(!in_array($username, $this->editUserList)){
            return $this->response(-1, '没有权限');
        }
        if(!file_exists($fileName)){
            return $this->response(-3, '获取数据失败');
        }else{
            //备份修改前文件
            exec("cp {$fileName} {$bakName}");
            $list = json_decode(file_get_contents($fileName), 1);
        }
        $tableContent = $this->input->post('tableContent');
        $data = $this->get_td_array($tableContent);
        if(empty($data)){
            return $this->response(-1, '参数错误');
        }
        if(!file_exists($fileName)){
            $list = [];
        }else{
            $ret = json_decode(file_get_contents($fileName), 1);
            $list = isset($ret[$configKey]) ? $ret[$configKey] : [];
        }
        print_r($data);
        exit();
        array_shift($data);
        foreach ($data as &$val){
            foreach ($val as $k => &$v){
                if(in_array($k, $charKeyList)){
                    continue;
                }
                if($configKey != 'EnemyBasic_config'){
                    $v = floatval($v);
                }
            }
        }
        //修改更新标识文件,让客户端知道修改了配置
        file_put_contents($this->_updateFilePath, time());
        $list[$configKey] = $data;
        $flag = file_put_contents($fileName, json_encode($list));
        if(!$flag){
            return $this->response(-2, '操作失败');
        }
        return $this->response(0, '操作成功');
    }

    /**
     * 版本号管理
     */
    public function versionSet() {
        $postData = $this->input->post();
        $tb = otable::versionSet();
        if(!empty($postData)){
            $content = !empty($postData['content']) ? $postData['content'] : '';
            $content = str_replace("，",",",$content);
            $content = str_replace(" ","",$content);
            $arr = array_unique(explode(',', $content));
            $content = implode(',', $arr);
            if(empty($content)){
                return $this->response(-2, '操作失败');
            }
            $sql = "UPDATE {$tb} set content = '{$content}'";
            oo::commonOprDb('games')->query($sql);
            return $this->response(0, '操作成功');
        }
        $sql = "SELECT * from {$tb} LIMIT 1";
        $rs = oo::commonOprDb('games')->getOne($sql,1);
        $this->load->view('config/versionSet', $rs);
    }
    // -----------------------------------------------------------------------------------------------------------------
    /**
     * 老虎机配置  --首页
     */
    public function slotConfig($page = 0)
    {
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->_role_title;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getSoltConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/slotConfig');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/slotConfig', $data);
    }

    /**
     *老虎机配置
     */
    public function actionSoltConfig(){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);
        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'slotpro' =>$row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveSoltConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $postData['page'];
        $posts['data'] = json_encode($upload,JSON_UNESCAPED_UNICODE);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);;

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeBeginGuideJson();
            return $this->response(0, '操作成功');
        }
    }
    //========================================
    //老虎机权重配置
    public function slotWeightCfg($page = 0)
    {
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->_role_title2;

        $start = ($page/10 -1)*50;
        $length = 50;

        $tb = otable::slotWeightCfg();
        $sql = "SELECT * from {$tb} LIMIT {$start},{$length}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[$v['levelId']] = json_decode($v['slotpro'],true);
        }
        $sql = "SELECT COUNT(*) as num from {$tb}";
        $rs = oo::commonOprDb('slavedb')->getOne($sql,1);
        $retData = [
            'total'=>$rs['num'],
            'data'=>$arr,
        ];

        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $page/10;
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/slotWeightCfg');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/slotWeightCfg', $data);
    }

    /**
     * Notes: 设置老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:23
     * @return json
     */
    public function actionSoltWeightcfg(){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);
        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'slotpro' =>$row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }

        $retData = $this->saveSoltWeightCfg($upload);
        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeBeginGuideJson();
            return $this->response(0, '操作成功');
        }
    }

    /**
     * Notes:保存老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:24
     * @param $data
     * @return array|int
     */
    public function saveSoltWeightCfg($data){
        $tb = otable::slotWeightCfg();
        $sql = "SELECT levelId from {$tb}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $temp = [];
        foreach ($rs as $row){
            array_push($temp,(int)$row['levelId']);
        }
        $data = json_decode(json_encode($data));
        foreach ($data as $row){
            $tempData = json_encode($row->slotpro,JSON_UNESCAPED_UNICODE);
            if(in_array($row->level,$temp)){
                $sql = "UPDATE {$tb} SET slotpro='{$tempData}' WHERE levelId={$row->level}";
            }else{
                $sql = "INSERT INTO {$tb} (levelId,slotpro) VALUES ({$row->level},'{$tempData}')";
            }
            $rs = oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->hDel(okeys::slotWeightCfg(),$row->level);
        }

        return $rs ? $rs : 0;
    }

    /**
     * Notes:老虎机权重修正配置
     * User: wsc
     * Time: 2021/2/27 13:31
     */
    public function slotWeightChangeCfg(){
        $data=[];
        $tb = otable::slotWeightChangeCfg();
        $sql = "SELECT * FROM {$tb}";
        $arr = oo::commonOprDb('slavedb')->getAll($sql,1);
        $tittleArr = ["betSpinsRule"=>"倍率修正需消耗总体力规则配置","spinsLost"=>"体力消耗修正配置","spinsLostDay"=>"每6小时体力消耗修正配置","slotLimitDay"=>"每6小时次数修正配置"];
        $trArr = [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",18=>"一个偷",19=>"两个偷",20=>"一个打",21=>"两个打",22=>'1个体力瓶',23=>'2个体力瓶'];
        foreach ($arr as $k=>$v){
            $data[$v['type']]['title'] = $tittleArr[$v['type']];
            $data[$v['type']]['list'] = json_decode($v['config'],true);
        }
//        $data['dataList'] = $list;
        $data['trArr'] = $trArr;
        $this->load->view('tiger/slotWeightChangeCfg', $data);
    }

    public function saveSlotWeightChangeCfg(){
        $postData = $this->input->post();
        $type=$postData['type'];
        $keys = $postData['k'];
        $values = $postData['v'];
        foreach ($keys as $k=>$v){
            $kv_data[$v] = $values[$k];
        }
        $conf_json = json_encode($kv_data);
        $tb = otable::slotWeightChangeCfg();
        $w = " type='".$type."'";
        $data['config'] =$conf_json;
        $sql = funs::db_updateSQL($tb,$data,$w);
        $res = oo::commonOprDb('games')->query($sql);
        if($res){
            $key = okeys::slotCoefficientCfg($postData['type']);
            oo::commonOprRedis('games')->delete($key);
            $conf = json_decode($data['config'],true);
            if($type=='betSpinsRule'){
                $cache = $conf;
            }else{
                foreach ($conf as $k=>$v){
                    $cache[$k] = json_encode($v);
                }
            }
            oo::commonOprRedis('games')->hMset($key,$cache);
        }else{
            $this->response(1, '操作失败');
        }
        return $this->response(0, '操作成功');
    }

    /*
     * 通过用户分组，获取收集卡点配置
     */
    public function getFreezePointConfigByUserGroup( $gids){
        if(!is_array($gids)) $gids = [$gids];
        $bConfig = $this->getFreezePointConfigByType('configB');
        $bGroups = empty($bConfig['groups'])  ? [] : is_array($bConfig['groups']) ? $bConfig['groups'] : json_decode($bConfig['groups'], 1);
        $uniGids = array_intersect($gids, $bGroups);
        if(!empty($uniGids)){    //获取B组配置
            return $bConfig;
        }

        //获取A组配置
        $aConfig = $this->getFreezePointConfigByType('configA');
        return $aConfig;
    }

    /*
     * 通过类型获取收集卡点配置
     * @type string configA|configB
     */
    public function  getFreezePointConfigByType($type = 'configA'){
        $key = okeys::slotFreezePointCfg( $type );
        $res = oo::commonOprRedis('games')->hgetall($key,'groups');
//        $res = 0;
        if(empty($res)){
            $tb = otable::slotFreezePointCfg();
            $sql = "SELECT * FROM {$tb} where `type`='{$type}'";
            $res = oo::commonOprDb('games')->getOne($sql, 1);
            unset($res['id'],$res['type']);
            oo::commonOprRedis('games')->hMset($key, $res);
            oo::commonOprRedis('games')->expire($key,oo::redisRandomExpire(30*24*60*60));
        }
        $res['config'] = empty($res['config']) ? [] : json_decode($res['config'], ture);
        $res['groups'] = empty($res['groups']) ? [] : json_decode($res['groups'], ture);
        ksort($res);
        return $res;
    }

    public function slotSpinsReturnRateCfgDebug(){
        $gid = intval($_GET['gid']);
        $gid = empty($gid) ? 101 : $gid;
        $config = self::getFreezePointConfigByUserGroup($gid);
        echo json_encode($config);
    }


    /**
     * Notes:老虎机体力返比控制
     * User: xwy
     * Time: 2021/8/28 11:06
     */
    public function slotSpinsReturnRateCfg(){
        $data=[];

        $status = intval(oo::commonOprRedis('games')->get(okeys::spinsReturnStatus()));

        $tb = otable::slotSpinsReturnRateCfg();
        $sql = "SELECT * FROM {$tb}";
        $arr = oo::commonOprDb('games')->getAll($sql,1);
        $tittleArr = [
            "configA"=>"修正值配置 - A组",
            "configB"=>"修正值配置 - B组",
            "A"=>"累计消耗体力/累计预设消耗体力",
            "B"=>"累计获得分数/累计预设分数",
        ];


        $trArr = [
            1=>"0",
            2=>"0.1",
            3=>"0.2",
            4=>"0.3",
            5=>"0.4",
            6=>"0.5",
            7=>"0.6",
            8=>"0.7",
            9=>"0.8",
            10=>"0.9",
            11=>"1.0",
        ];
        foreach ($arr as $k=>$v){
            $data[$v['type']]['title'] = $tittleArr[$v['type']];
//            echo  $v['config'];die;
            $data[$v['type']]['list'] = json_decode($v['config'],true);
            $data[$v['type']]['groups'] = json_decode($v['groups'],true);
//            var_dump( json_decode($v['config'],true));die;
        }
        $data['configType'] = 'spinsReturn';
        $data['saveUrl'] = 'config/saveSlotSpinsReturnRateCfg';
        $data['exportUrlA'] = '/Export/slotSpinsReturnRateCfg/configA';
        $data['exportUrlB'] = '/Export/slotSpinsReturnRateCfg/configB';
        $data['importUrl'] = 'Import/slotSpinsReturnRateCfg';
        $data['trArr'] = $trArr;
        $data['titleArr'] = $tittleArr;

        $data['ssGroups'] = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');//数数分组
        $data['status'] = $status;
        $this->load->view('config/slotSpinsReturnRateCfg', $data);
    }
    public function saveSlotSpinsReturnStatus(){
        $status = intval($this->input->post("status"));
        oo::commonOprRedis('games')->set(okeys::spinsReturnStatus(),$status);
        return $this->response(0, '操作成功');
    }
    public function saveSlotSpinsReturnRateCfg(){
        $postData = $this->input->post();
        $groups = $postData['groups'];
        $type= $postData['type'];
        $keys = $postData['k'];
        $values = $postData['v'];
        foreach ($keys as $k=>$v){
            if(empty($v))$v = 0;
            $kv_data[$v] = [];
            foreach ($values[$k] as $k1 =>$v1){
                $kv_data[$v][$k1] = empty($v1) ? 0 : $v1;
            }

//            $kv_data[$v] = $values[$k];
        }
        $conf_json = json_encode($kv_data);

        $tb = otable::slotSpinsReturnRateCfg();
        $sql = "SELECT * FROM {$tb} where type='" .$type . "'";
        $arr = oo::commonOprDb('games')->getOne($sql,1);
        if($arr){
            $w = " type='".$type."'";
            $newData['config'] =$conf_json;
            $newData['groups'] =json_encode($groups);
            $sql = funs::db_updateSQL($tb,$newData,$w);
        }else{
            $newData = [
                'type' => $type,
                'config' => $conf_json,
                'groups' => json_encode($groups),
            ];
            $sql = funs::db_insertSQL($tb,$newData);
        }
        $res = oo::commonOprDb('games')->query($sql);
        if($res){
            $key = okeys::slotSpinsReturnRateCfg($postData['type']);
            oo::commonOprRedis('games')->delete($key);
            $cache = [];
            foreach ($newData as $k=>$v){
                $cache[$k] = ($v);
            }
            oo::commonOprRedis('games')->hMset($key,$cache);
        }else{
            return $this->response(1, '操作失败', [$sql]);
        }
        return $this->response(0, '操作成功');
    }


    /**
     * Notes:老虎机体力返比控制
     * User: xwy
     * Time: 2021/8/30 17:06
     */
    public function slotFreezePointCfg(){
        $data=[];
        $tb = otable::slotFreezePointCfg();
        $sql = "SELECT * FROM {$tb}";
        $arr = oo::commonOprDb('games')->getAll($sql,1);
        $tittleArr = [
            "configA"=>"收集卡点配置 - A组",
            "configB"=>"收集卡点配置 - B组",
            "A"=>"（当前层总分-当前层获得分数）/ 当前层总分",
            "B"=>"剩余体力 / 当前收集层预设体力",
        ];

        $trArr = [
            1=>"0",
            2=>"0.1",
            3=>"0.2",
            4=>"0.3",
            5=>"0.4",
            6=>"0.5",
            7=>"0.6",
            8=>"0.7",
            9=>"0.8",
            10=>"0.9",
            11=>"1",
            12=>"1.1",
            13=>"1.2",
            14=>"1.3",
            15=>"1.4",
            16=>"1.5",
        ];
        foreach ($arr as $k=>$v){
            $data[$v['type']]['title'] = $tittleArr[$v['type']];
            $data[$v['type']]['list'] = json_decode($v['config'],true);
            $data[$v['type']]['groups'] = json_decode($v['groups'],true);
        }

        $data['minStage'] = intval(oo::commonOprRedis('games')->get(okeys::slotFreezePointMinStage()));
        $data['configType'] = 'freezePoint';
        $data['saveUrl'] = 'config/saveSlotFreezePointCfg';
        $data['exportUrlA'] = '/Export/slotFreezePointCfg/configA';
        $data['exportUrlB'] = '/Export/slotFreezePointCfg/configB';
        $data['importUrl'] = 'Import/slotFreezePointCfg';
        $data['trArr'] = $trArr;
        $data['titleArr'] = $tittleArr;
        $data['ssGroups'] = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');//数数分组

        $this->load->view('config/slotSpinsReturnRateCfg', $data);
    }

    public function saveSlotFreezePointMinStage(){
        $postData = $this->input->post();
        $stage = intval($postData['minStage']);
        $key = okeys::slotFreezePointMinStage();
        oo::commonOprRedis('games')->set($key,$stage);
        return $this->response(0, '操作成功');
    }

    public function saveSlotFreezePointCfg(){
        $postData = $this->input->post();
        $groups = $postData['groups'];
        $type= $postData['type'];
        $keys = $postData['k'];
        $values = $postData['v'];
        foreach ($keys as $k=>$v){
            if(empty($v))$v = 0;
            $kv_data[$v] = [];
            foreach ($values[$k] as $k1 =>$v1){
                $kv_data[$v][$k1] = empty($v1) ? 0 : $v1;
            }

        }
        $conf_json = json_encode($kv_data);

        $tb = otable::slotFreezePointCfg();
        $sql = "SELECT * FROM {$tb} where type='" .$type . "'";
        $arr = oo::commonOprDb('games')->getOne($sql,1);
        if($arr){
            $w = " type='".$type."'";
            $newData['config'] =$conf_json;
            $newData['groups'] =json_encode($groups);
            $sql = funs::db_updateSQL($tb,$newData,$w);
        }else{
            $newData = [
                'type' => $type,
                'config' => $conf_json,
                'groups' => json_encode($groups),
            ];
            $sql = funs::db_insertSQL($tb,$newData);
        }
        $res = oo::commonOprDb('games')->query($sql);
        if($res){
            $key = okeys::slotFreezePointCfg($postData['type']);
            oo::commonOprRedis('games')->delete($key);
            $cache = [];
            foreach ($newData as $k=>$v){
                $cache[$k] = ($v);
            }
            oo::commonOprRedis('games')->hMset($key,$cache);
        }else{
            return $this->response(1, '操作失败', [$sql]);
        }
        return $this->response(0, '操作成功');
    }

    /**
     * Notes:偷结果权重配置
     * User: wsc
     * Time: 2021/4/21 14:24
     */
    public function slotRet(){
        $data = oo::commonOprModel('config')->SlotWeightChangConfig();
        $data = array_column($data,"config","type");
        foreach ($data as $key=>&$value){
            $value = json_decode($value,true);
        }
        $this->load->view('config/slotweightchange', $data);
    }

    /**
     * Notes:偷结果权重编辑保存
     * User: wsc
     * Time: 2021/4/21 14:24
     * @param $type
     * @return json
     */
    public function actionSlotRet($type){
        $config = $this->input->post('config');
//        stealRetWeight, boxRetWeight, betRetWeight, betBoxRetWeight
        if($type == "stealRetWeight"){
            foreach ($config as $row){
                if($row['slv'] > $row['elv']){
                    return $this->response(1, '等级范围异常');
                }
            }
        }
        $data = [];
        $id = 1;
        foreach ($config as $row){
            $temp = $row;
            $temp['id'] = $id;
            $data[] = $temp;
            $id ++;
        }
        $ret = oo::commonOprModel('config')->actionSlotWeightChangConfig($type,json_encode($data,JSON_NUMERIC_CHECK));
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }


    public function stealRatio(){
        $table = otable::commonConfig();
        $key = okeys::stealRaticProCfg();
        $sql = "SELECT * FROM {$table} where type ='{$key}'";
        $one = oo::commonOprDb('slavedb')->getOne($sql,1);
//            $datajson = oo::commonOprRedis('games')->get($key);
        $data['list'] = $one['conf']?json_decode($one['conf'],true):[];
        $this->load->view('config/stealRatio', $data);
    }
    public function actionStealRatio(){
        $config = $this->input->post('conf');
        $json=json_encode(array_values($config));
        $table = otable::commonConfig();
        $key = okeys::stealRaticProCfg();
        $sql = "UPDATE {$table} SET conf='".$json."'  where type='{$key}'";
        $ret = oo::commonOprDb("games")->query($sql);
        $ret = oo::commonOprRedis('games')->set(okeys::stealRaticProCfg(),$json);
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }


    //保底机制
    public function userLuck()
    {
        //偷保底机制
//        $data['list'] = oo::commonOprModel('config')->getCommonConf(okeys::StealLuckCfg());
//        if (empty($data['list'])) {
//            $datajson = oo::commonOprRedis('games')->get(okeys::StealLuckCfg());
//            $data['list'] = $datajson ? json_decode($datajson, true) : [];
//        }
//        unset($data['list']['9999']);
        $data['list2'] = oo::commonOprModel('config')->getCommonConf(okeys::StealBottleConf());

        //体力瓶保底机制（新）
        $data['list3'] = oo::commonOprModel('config')->getCommonConf(okeys::SpinBottleConf());
 
        # 小丑卡保底
        $data['joker'] = oo::commonOprModel('config')->getCommonConf(okeys::jokerLuckCfg());

        $this->load->view('config/userLuck', $data);
    }

    //保存保底机制
    public function actionUserLuck($config = [], $type = 0)
    {
        $config = $config ?: $this->input->post('conf');
        $type = $type ?: $this->input->post('type');

        $ret = 0;
        switch ($type) {
            case 1://偷保底
//                $config["9999"] = [100000000, 100000001];
//                oo::commonOprModel('config')->saveCommonConf(okeys::StealLuckCfg(), $config, "偷保底配置");
//                $ret = oo::commonOprRedis('games')->set(okeys::StealLuckCfg(), json_encode($config, JSON_NUMERIC_CHECK));

                $ret = oo::commonOprModel('config')->saveCommonConf(okeys::StealBottleConf(), $config, "偷保底配置");
                oo::commonOprRedis('games')->delete(okeys::StealBottleConf());
                break;
            case 2://体力瓶保底（新）
                $ret = oo::commonOprModel('config')->saveCommonConf(okeys::SpinBottleConf(), $config, "体力瓶保底配置");
                oo::commonOprRedis('games')->set(okeys::SpinBottleConf(), json_encode($config, JSON_NUMERIC_CHECK));
                break;
            case 'joker'://小丑卡保底
                $ret = oo::commonOprModel('config')->saveCommonConf(okeys::jokerLuckCfg(), $config, "小丑卡保底配置");
                oo::commonOprRedis('games')->set(okeys::jokerLuckCfg(), json_encode($config, JSON_NUMERIC_CHECK));
                break;
        }

        if ($ret) {
            return $this->response(0, '操作成功', ["d" => $config]);
        } else {
            return $this->response(1, '操作失败');
        }
    }

    // 导入配置
    public function importStealLuckConf()
    {
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize' => 1024 * 50,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls', '.xlsx', '.json', '.png', '.jpg')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $dataArray = $this->getExcelSheetsArray();

        $basicConfArray = $dataArray[0] ?? [];
        unset($basicConfArray[0]);

        $userLuckConf = [];
        foreach ($basicConfArray as $index => $item) {
            list($stealTimes, $min, $max) = $item;
            $userLuckConf[$stealTimes] = [$min, $max];
        }

        return $this->actionUserLuck($userLuckConf, 1);
    }

    // 导入配置
    public function importSpinLuckConf()
    {
        $config = array(
            'savePath' => 'Excel/uploads',             //存储文件夹
            'maxSize' => 1024 * 50,                   //允许的文件最大尺寸，单位KB
            'allowFiles' => array('.xls', '.xlsx', '.json', '.png', '.jpg')  //允许的文件格式
        );
        $this->load->library('uploader', $config);
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        $dataArray = $this->getExcelSheetsArray();

        $basicConfArray = $dataArray[0] ?? [];
        $spinConfArray = $dataArray[1] ?? [];

        list($randName, $min, $max) = $basicConfArray[0];
        if ($randName != "随机浮点数") {
            return $this->response(1, '数据格式错误');
        }
        $randConf = [
            'min' => $min,
            'max' => $max
        ];

        unset($spinConfArray[0]);
        $spinsConf = [];
        foreach ($spinConfArray as $index => $item) {
            list($mul, $spend) = $item;
            $spinsConf[] = ['mul' => $mul, 'spend' => $spend];
        }
        $userLuckConf = [
            'rand' => $randConf,
            'mulSpend' => $spinsConf,
        ];

        return $this->actionUserLuck($userLuckConf, 2);
    }
    //========================================
    //========================================

    /**
     * 老虎机活动配置  --首页
     */
    public function slotActivityConfig($page = 0)
    {
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = ['关卡','有奖励 2个活动<br/>(概率)','有奖励 1个活动<br/>(概率)','无奖励 1个活动<br/>(概率)','无奖励 2个活动<br/>(概率)'];;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getSlotActivityConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/slotActivityConfig');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/slotActivityConfig', $data);
    }

    /**
     *老虎机活动配置
     */
    public function actionSlotActivityConfig(){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);
        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'data' =>$row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveSlotActivityConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $postData['page'];
        $posts['data'] = json_encode($upload,JSON_UNESCAPED_UNICODE);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);;

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    /**
     * 大转盘配置  --首页
     */
    public function turntConfig($page = 0)
    {
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->_turn_title;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getTurnConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/turntConfig');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/turntConfig', $data);
    }

    /**
     * 大转盘配置12格子配置
     */
    public function turntConfig2($page = 0)
    {
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->_turn_title2;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getTurnConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $posts['conf_ver'] = '2';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/turntConfig2');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/turntConfig2', $data);
    }

    /**
     * 大转盘配置
     */
    public function actionTurnConfig($version = ''){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);
        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'slotpro' =>$row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveTurnConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $postData['page'];
        $posts['data'] = json_encode($upload,JSON_UNESCAPED_UNICODE);
        $posts['conf_ver'] = $version;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $ret = json_decode(oo::commonOprModel('common')->CurlApi([
                'mod'      =>'Config',
                'act'      =>'makeTurnTableJson',
            ]),true);
            self::SaveJson($ret['data'],$ret['filename']);
            return $this->response(0, '操作成功');
        }
    }

    /**
     *建筑价格配置
     */
    public function buildConfig($page = 0){
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->_build_title;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getBuildConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $retData=  $this->httpPost($posts);

        $list = [];
        $reward = [];
        if ($retData['total'] != 0) {
            $list = $retData['data'];
            $reward = $retData['reward'];
        }

        $data['title'] = $title;
        $data['list'] = $list;
        $data['reward'] = $reward;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/buildConfig');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/buildConfig', $data);
    }
 
    /**
     *建筑价格配置
     */
    public function actionBuildConfig(){
        $postData = $this->input->post();

        $reward=[];
        foreach ($postData['data']['reward'] as $lv => &$item) {
            foreach ($item as &$item2) {
                foreach ($item2 as &$item3) {
                    $item3 = json_decode($item3, true);
                }
            }
            $reward[$lv] = $item;
        }

        $upload = [];
        $levels = [];
        foreach ($postData['data']['coin'] as $lv => $one) {
            if (in_array($lv, $levels)) {
                return $this->response(1, "levelId:{$lv} 重复");
            }
            $upload[] = [
                'level' => $lv,
                'coinConfig' => $one,
                'stage_reward' => $reward[$lv],
            ];
            $levels[] = $lv;
        }

        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveBuildConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $postData['page'];
        $posts['data'] = json_encode($upload,JSON_NUMERIC_CHECK);
        $retData = $this->httpPost($posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            oo::commonOprModel('Json')->levelCoinConfig();
            return $this->response(0, '操作成功');
        }
    }

    /**
     * 关卡配置
     */
    public function levelConfig($page = 0){
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->level_title;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getLevelConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = ConfigModel::formatLevelRewardConfig($list);
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/levelConfig');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['langs'] = oo::cfg('lang')['lang_level'];
        $data['tableColumnMapping'] = array_merge(["levelId"],array_keys($data['langs']),['pictureId','reward']);
        $this->load->view('config/levelConfig', $data);
    }

    public function actionLevelConfig(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveLevelConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $this->actionSyncMinigJson("Mining".time().".json");
            return $this->response(0, '操作成功');
        }
    }

    public function miningConfig($page = 0){
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->mining_title;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getMiningConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 100;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $temp = $retData['data'];
            foreach ($temp as $key=>$row){
                $temp[$key]['config'] = json_decode($row['config']);
            }
            $list = $temp;
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/miningConfig');
        $pageConfig['total_rows'] = $retData['total'];
        $pageConfig['per_page'] = 100;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/miningConfig', $data);
    }

    public function actionMiningConfig(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveMiningConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $this->actionSyncMinigJson("Mining".time().".json");
            return $this->response(0, '操作成功');
        }
    }

    public function taskConfig(){
        $title = $this->task_type;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getTaskConfig';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $this->load->view('config/taskConfig', $data);
    }

    public function actionTaskConfig(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveTaskConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeTaskCenterJson();
            return $this->response(0, '操作成功');
        }
    }

    public function achiConfig(){
        $title = $this->achi_type;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getAchiConfig';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $max = 0;
        if(!empty($list)){
            $list = [];
        }else{
            $temp = $retData['data'];
            foreach ($temp as $key=>$row){
                $temp[$key]['stage'] = explode(',',$row['stage']);
                $reward = json_decode($row['reward']);
                $temp[$key]['reward'] = $reward;
                if(count($reward)>$max)
                    $max=count($reward);
            }
            $list = $temp;
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['max'] = $max;
        $this->load->view('config/achiConfig', $data);
    }

    public function actionAchiConfig(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveAchiConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeTaskCenterJson();
            return $this->response(0, '操作成功');
        }
    }

    public function actionSyncMinigJson($filename){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeMiningJson';
        $posts['filename'] = $filename;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['code'] == 1){
            $data = $retData['data'];
            $this->SaveJson($data,$filename);
        }
    }

    public function baseConfig(){
        $title = $this->base_type;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getBaseConfig';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $this->load->view('config/baseConfig', $data);
    }

    public function actionBaseConfig(){
        $postData = $this->input->post()['data'];

        $data = json_decode($postData);
        $ret = ConfigModel::multiUpdateCon($data);
        if ($ret == -1) {
            return $this->response(1, '操作失败');
        }

        ConfigModel::updateConJson();
        return $this->response(0, '操作成功');
    }

    public function SaveJson($data,$filename, $t=0){
        $dir = $this->staticPath;
        if (!is_dir($dir))
        {
            $old = umask(0);
            //mkdir($dir, PRODUCTION_SERVER ? 0775 : 0777, true);
            mkdir($dir,0775 , true);
            umask($old);
        }
        $filepath = "{$dir}{$filename}";
        file_put_contents($filepath, json_encode($data,JSON_NUMERIC_CHECK));

        if(method_exists($this->common,'upToOss')){
            $dir = str_replace("./","",$dir);
            $file_path = str_replace("\\","/",FCPATH . $dir.$filename);

            $this->common->upToOss($dir.$filename,$file_path);
        }
    }

    public function symbolConfig($type = 0){
        $title = ($type == 0)?'金蛋':'感恩节';
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getSymbolConfig';
        $posts['type'] = $type;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title']= $title;
        $data['menu'] = $this->symbol_type;
        $data['list'] = $list;
        $data['type'] = $type;
        $this->load->view('config/symbolConfig', $data);
    }

    public function actionSymbolConfig(){
        $filename = 'SymbolConfig'.time().'.json';;
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveSymbolConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['data'] = $postData['data'];
        $posts['filename'] = $filename;
        $posts['type'] = $postData['type'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $this->SaveJson(json_decode($postData['data'],true),$filename);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    /**
     * 大转盘配置  --首页
     */
    public function turnspinsConfig($type = 1,$page = 0)
    {
        if($page == 0){
            $page = 10;
        }else{
            $page += 10;
        }
        $title = $this->_turn_spins_title;
        $title[0] = $title[0].(($type==1)?'(视频)':'(商城)');
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getTurnSpinsConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $page/10;
        $posts['page_size'] = 10;
        $posts['type'] = $type;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['type'] = $type;
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/turnspinsConfig/'.$type);
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = 10;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/turnspinsConfig', $data);
    }

    /**
     * 大转盘配置
     */
    public function actionTurnSpinsConfig(){
        $postData = $this->input->post();
        $type = $postData['type'];
        $data = json_decode($postData['data']);
        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'slotpro' =>$row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveTurnSpinsConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $postData['page'];
        $posts['data'] = json_encode($upload,JSON_UNESCAPED_UNICODE);
        $posts['type'] = $type;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);;

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function turnPlusConfig(){
        $data = [];
        $data['title'] = ['关卡','id0<br/>概率,类型,数量','id1<br/>概率,类型,数量','id2<br/>概率,类型,数量','id3<br/>概率,类型,数量','id4<br/>概率,类型,数量','id5<br/>概率,类型,数量','id6<br/>概率,类型,数量','id7<br/>概率,类型,数量'];;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getTurnConfig';
        $posts['type']= 'plus';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,true);
        $arr = [];
        foreach ($retData as $k=>$v){
            $arr[$v['levelId']] = $v['slotpro'];
        }
        $data['list'] = $arr;
        $this->load->view('config/turnPlusConfig', $data);
    }
    //签到皮肤
    public function signSkin(){
        $data['dirList'] = json_encode(array_column(oo::commonOprModel('config')->getActiveImgNameConfig("signIn",true)['content'],"type"));
        $data['selDir']  = oo::commonOprModel('config')->getSysCon('Game',"signInDir");
        $this->load->view('config/signSkin', $data);
    }
    //保存签到皮肤设置
    public function saveSignSkinCfg(){
        $postData = $this->input->post();
        $ret = oo::commonOprModel('config')->setSysCon('Game',"signInDir",$postData['selDir']);
        if(!$ret){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功',$postData);
        }
    }
    /**
     * 七日签到 & 七日签到 - 区间
     * Created by: Owen
     * Created on: 2019/12/2 16:32
     */
    public function signin($type = 0){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = $type == 0?'getSignInConfig':'getSigninSection';//新版签到 等级区间
        $url = $this->config->item('officialUrl');
        $data = $this->curl->req($url, $posts);
        $data = json_decode($data,true);
        $data['type'] = $type;
        $this->load->view($type == 0?'config/signinConfig2':'config/signinConfig3', $data);//新版签到 等级区间
    }

    public function actionSigninConfig($type = 0){
        $postData = $this->input->post();
        $data = [];
        foreach ($postData['coins'] as $key=>$row){
            $data[$key] = [
                'coins' => json_encode([
                    'coins' => $row,
                    'bet' => $postData['bet'][$key],
                ],JSON_NUMERIC_CHECK),
                'spins' => $postData['spins'][$key]
            ];
            $props = [];
            if(!empty($postData['props'][$key])){
                foreach ($postData['props'][$key]['propsId'] as $propsKey=>$propsId){
                    $props[] = [
                        'propsId' => $propsId,
                        'num'     => $postData['props'][$key]['num'][$propsKey],
                    ];
                }
            }
            $data[$key]['props'] = json_encode($props,JSON_NUMERIC_CHECK);
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setSignInConfig';
        $posts['section_id'] = $postData['section_id'];////新版签到 等级区间
        if(!empty($postData['section_id'])){
            $posts['start_level'] = $postData['start_level'];
            $posts['end_level'] = $postData['end_level'];
        }
        $posts['data'] = json_encode($data,JSON_NUMERIC_CHECK);
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeSignJson($type);
            return $this->response(0, '操作成功');
        }
    }

    public function actionSignInProgressConfig($type = 0){
        $postData = $this->input->post();
        $data = [];
        foreach ($postData['coins'] as $key=>$row){
            $data[$key] = [
                'coins' => json_encode([
                    'coins' => $row,
                    'bet' => $postData['bet'][$key],
                ],JSON_NUMERIC_CHECK),
                'spins' => $postData['spins'][$key]
            ];
            $props = [];
            if(!empty($postData['props'][$key])){
                foreach ($postData['props'][$key]['propsId'] as $propsKey=>$propsId){
                    $props[] = [
                        'propsId' => $propsId,
                        'num'     => $postData['props'][$key]['num'][$propsKey],
                    ];
                }
            }
            $data[$key]['props'] = json_encode($props,JSON_NUMERIC_CHECK);
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setSignInProgressConfig';
        $posts['section_id'] = $postData['section_id'];////新版签到 等级区间
        $posts['data'] = json_encode($data,JSON_NUMERIC_CHECK);
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeSignJson($type);
            return $this->response(0, '操作成功');
        }
    }

    public function makeSignJson($type = 0){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getSignInJson';
        $posts['new'] = $type;//新版签到 等级区间
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        $retData = json_decode($retData,true);

        foreach($retData['data']['config'] as $key => $val){
            $retData['data']['config'][$key]['progress'] = array_values($val['progress']);
        }

        self::SaveJson($retData['data'],$retData['filename']);
    }

    /**
     * 分享配置
     * Created by: Owen
     * Created on: 2019/12/2 16:32
     */
    public function share($version = ''){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getShare';
        $posts['version'] = $version;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,true);
        $list = $retData;
        $data['list'] = $list;
        if($version){
            foreach($data['list'] as $key => $row){
                $data['list'][$key]['reward'] = json_decode($row['reward'],true);
            }
            $data['menu'] = ['类型','最大分享次数','奖励','间隔时间'];
            $posts = $this->postData;
            $posts['mod'] = 'Config';
            $posts['act'] = 'getPropsConfig';
            $url = $this->config->item('officialUrl');
            $retData = json_decode($this->curl->req($url, $posts),true);
            $data['idData'] = $retData['props'];
        }else{
            $data['menu'] = ['类型','最大分享次数','自己奖励(1金币,2体力)','自己数量','对方奖励(1金币,2体力)','对方数量',];
        }
        $this->load->view('config/shareConfig'.$version, $data);
    }

    public function actionShareConfig($type = ''){
        $postData = $this->input->post();
        $data = $type?$postData['good']:json_decode($postData['data'],true);
        $filename = 'ShareConfig'.time().'.json';;
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveShareConfig';
        $posts['data'] = json_encode($data);
        $posts['filename'] = $filename;
        $posts['type'] = $type;
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $json = [];
        if($type){
            foreach ($data as $row){
                $json[$row['type']] = [
                    'maxTimes' => $row['maxTimes'],
                    'reward'  => $row['reward'][0],
                    'intervalTime' => $row['intervalTime'],
                    'show'        => intval($row['show']),
                ];
            }
        }else{
            foreach ($data as $row){
                $json[$row['type']] = [
                    'maxTimes'    => $row['maxTimes'],
                    'selfReward'  => $row['selfReward'],
                    'otherReward' => $row['otherReward'],
                ];
            }
        }

        $this->SaveJson($json,$filename);

        oo::logs()->adminlog("设置分享奖励配置");

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function luckydraw($flag = '',$newVersion = 0){
    	if(empty($flag)){
    		$flag = '';
    	}
    	
        $idData = [
            1=>['name'=>'金币', 'data'=>[201=>"coins01",202=>"coins02",203=>"coins03",204=>"coins04",205=>"coins05",206=>"coins06"]],
            2=>['name'=>'体力', 'data'=>[1=>"数值"]],
            3=>['name'=>'宝箱', 'data'=>[1=>"木质宝箱",2=>"白银宝箱",3=>"黄金宝箱",4=>"魔幻宝箱",19=>"小丑卡宝箱"]],
            4=>['name'=>'活动素材', 'data'=>[1=>"收集素材"]],
            5=>['name'=>'宠物相关', 'data'=>[1=>"宠物经验",2=>"宠物饲料"]],
            6=>['name'=>'祈福', 'data'=>[1=>"卡组祈福",2=>"卡片祈福"]],
            7=>['name'=>'VIP', 'data'=>[1=>"3日vip"]],
            9=>['name'=>'消耗品', 'data'=>[1=>"夺宝卷"]],
            10=>['name'=>'钻石', 'data'=>[1=>"数值"]],
            11=>['name'=>'卡片', 'data'=>[13=>"随机金卡",18=>"小丑卡"]],
        ];
	        
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getLuckyDrawConfig';
        $posts['newVersion'] = $newVersion;
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,true);
        $retData['idData'] = $idData;
        $retData['flag']   = $flag;
        
        $retData['newVersion']   = $newVersion;
        
        if($newVersion){
    		$idData = [
	            1=>['name'=>'金币', 'data'=>[201=>"coins01",202=>"coins02",203=>"coins03",204=>"coins04",205=>"coins05",206=>"coins06"]],
	            2=>['name'=>'体力', 'data'=>[15=>"体力"]],
	            3=>['name'=>'宝箱', 'data'=>[1=>"木质宝箱",2=>"白银宝箱",3=>"黄金宝箱",4=>"魔幻宝箱",19=>"小丑卡宝箱"]],
	            4=>['name'=>'活动素材', 'data'=>[1=>"收集素材"]],
	            5=>['name'=>'宠物相关', 'data'=>[8=>"宠物经验",9=>"宠物饲料"]],
	            //6=>['name'=>'祈福', 'data'=>[5=>"卡组祈福",6=>"卡片祈福"]],
	            //7=>['name'=>'VIP', 'data'=>[1=>"3日vip"]],
	            8=>['name'=>'大礼包', 'data'=>[1=>"大礼包"]],
	            9=>['name'=>'消耗品', 'data'=>[7=>"夺宝卷"]],
	            10=>['name'=>'钻石', 'data'=>[22=>"钻石"]],
	            11=>['name'=>'卡片', 'data'=>[13=>"随机金卡",18=>"小丑卡"]],
	        ];
	        $retData['idData'] = $idData;
	        $this->load->view('luckydraw/index2', $retData);
    	}else{
    		$this->load->view('luckydraw/index', $retData);
    	}
    }

    public function luckydrawConfig(){
        $input = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveLuckyDrawConfig';
        $posts['flag']= $input['flag'];
        $posts['newVersion']= $input['newVersion'];
        $url  = $this->config->item('officialUrl');
        $data  = [];

        oo::logs()->adminlog($this->router->fetch_method());

        if($input['actionType'] == 'pro'){
            $i = 0;
            foreach ($input['pro'] as $key=>$row){
                $data[] = [
                    'origLucky' => $key,
                    'newLucky'  => $input['lucky'][$i++],
                    'pro'       => json_encode($row,JSON_NUMERIC_CHECK),
                ];
            }
            $posts['data'] = json_encode($data);
            $posts['actionType'] = 'pro';
            $retData = $this->curl->req($url, $posts);
            if($retData == 0){
                return $this->response(1, '操作失败');
            }else{
                return $this->response(0, '操作成功');
            }
        }else if($input['actionType'] == 'progress'){
            $i = 0;
            foreach ($input['type'] as $key=>$row){
                $temp = [
                    'origProgress' => $key,
                    'newProgress'  => $input['progress'][$i++],
                ];
                $reward = [];
                foreach ($row as $x=>$y){
                	if($y == 1){
                		$reward[] = [
	                        'type'=>$y,
	                        'propsId'  =>14,
	                        'id'=>14,
	                        'gid' => $input['rewardid'][$key][$x],
	                        'num'  =>$input['num'][$key][$x],
	                        'img' =>$this->luckydrawImg($input['rewardid'][$key][$x]),
	                    ];
                	}else if($y == 3 && in_array($input['rewardid'][$key][$x],[19,20,21])){
                		//特殊宝箱
                		$reward[] = [
	                        'type'=>$y,
	                        'propsId'  =>$input['rewardid'][$key][$x],
	                        'id'  =>$input['rewardid'][$key][$x],
	                        'num'  =>$input['num'][$key][$x],
	                        'value'=>oo::commonOprModel('config')->getChestData($input['rewardid'][$key][$x]),
	                        'img' =>$this->luckydrawImg($input['rewardid'][$key][$x]),
	                    ];
                	}else{
                		$reward[] = [
	                        'type'=>$y,
	                        'propsId'  =>$input['rewardid'][$key][$x],
	                        'id'  =>$input['rewardid'][$key][$x],
	                        'num'  =>$input['num'][$key][$x],
	                        'img' =>$this->luckydrawImg($input['rewardid'][$key][$x]),
	                    ];
                	}
                }
                $temp['reward'] = json_encode($reward,JSON_NUMERIC_CHECK);
                $data[] = $temp;
            }
            $posts['data'] = json_encode($data);
            $posts['actionType'] = 'progress';
            $retData = $this->curl->req($url, $posts);
        }else if($input['actionType'] == 'reward'){
            foreach ($input['configId'] as $key=>$row){
                if($key==11){
                    foreach ($input['type'][$key] as $x=>$y){
                    	if($input['type'][$key][$x] == 1){
                    		$temp[] = [
	                            'type'=>$input['type'][$key][$x],
	                            'propsId'  =>14,
	                            'id'  =>14,
	                            'gid' =>$input['rewardid'][$key][$x],
	                            'num' =>$input['num'][$key][$x],
	                            'img' =>$this->luckydrawImg($input['rewardid'][$key][$x]),
	                        ];
                    	}else if($input['type'][$key][$x] == 3 && in_array($input['rewardid'][$key][$x],[19,20,21])){
	                		//特殊宝箱
	                		$temp[] = [
		                        'type'=>$input['type'][$key][$x],
		                        'propsId'  =>$input['rewardid'][$key][$x],
		                        'id'  =>$input['rewardid'][$key][$x],
		                        'num'  =>$input['num'][$key][$x],
		                        'value'=>oo::commonOprModel('config')->getChestData($input['rewardid'][$key][$x]),
		                        'img' =>$this->luckydrawImg($input['rewardid'][$key][$x]),
		                    ];
	                	}else{
                    		$temp[] = [
	                            'type'=>$input['type'][$key][$x],
	                            'propsId'  =>$input['rewardid'][$key][$x],
	                            'id'  =>$input['rewardid'][$key][$x],
	                            'num' =>$input['num'][$key][$x],
	                            'img' =>$this->luckydrawImg($input['rewardid'][$key][$x]),
	                        ];
                    	}
                    }
                    $data[] = [
                        'id'     => 11,
                        'reward' => json_encode([
                            'type'=>8,
                            'propsId'  =>-1,
                            'id'=>1,
                            'num' =>1,
                            'data'=>$temp
                        ],JSON_NUMERIC_CHECK),
                        'sort'    =>$input['sort'][$key],
                    ];
                }else{
                	if($input['type'][$key] == 1){
                		
                		$data[] = [
	                        'id'     => $row-1,
	                        'reward' => json_encode([
	                            'type'=>$input['type'][$key],
	                            'propsId'  =>14,
	                            'id'  =>14,
	                            'gid' =>$input['rewardid'][$key],
	                            'num' =>$input['num'][$key],
	                            'img' =>$this->luckydrawImg($input['rewardid'][$key]),
	                        ],JSON_NUMERIC_CHECK),
	                        'sort'    =>$input['sort'][$key],
	                    ];
                	}else if($input['type'][$key] == 3 && in_array($input['rewardid'][$key],[19,20,21])){
                		//特殊宝箱
                		$data[] = [
	                        'id'     => $row-1,
	                        'reward' => json_encode([
	                            'type'=>$input['type'][$key],
	                            'propsId'  =>$input['rewardid'][$key],
	                            'id'  =>$input['rewardid'][$key],
	                            'num' =>$input['num'][$key],
	                            'value'=>oo::commonOprModel('config')->getChestData($input['rewardid'][$key]),
	                            'img' =>$this->luckydrawImg($input['rewardid'][$key]),
	                        ],JSON_NUMERIC_CHECK),
	                        'sort'    =>$input['sort'][$key],
	                    ];
                	}else{
                		$data[] = [
	                        'id'     => $row-1,
	                        'reward' => json_encode([
	                            'type'=>$input['type'][$key],
	                            'propsId'  =>$input['rewardid'][$key],
	                            'id'  =>$input['rewardid'][$key],
	                            'num' =>$input['num'][$key],
	                            'img' =>$this->luckydrawImg($input['rewardid'][$key]),
	                        ],JSON_NUMERIC_CHECK),
	                        'sort'    =>$input['sort'][$key],
	                    ];
                	}
                    
                }
            }
            $posts['data'] = json_encode($data);
            $posts['actionType'] = 'reward';
            $retData = $this->curl->req($url, $posts);
        }
        $retData = json_decode($retData,true);
        self::SaveJson($retData['data'],$retData['name']);
        return $this->response(0, '操作成功');
    }
    
    public function luckydrawImg($id){
    	$temp = [
    		201 => 1,
    		202 => 2,
    		203 => 3,
    		204 => 3,
    		205 => 3,
    		206 => 3,
    		15	=> 4,
    		1	=> 5,
    		2	=> 6,
    		3	=> 7,
    		4	=> 8,
    		8	=> 9,
    		9	=> 10,
    		7	=> 11,
    		22	=> 12,
    		18  => 13,
    		13  => 14,
    		19  => 15,
    	];
    	return $temp[$id];
    }

    public function miningGameConfig($page = 0){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getMiningGameConfig';
        $miningGameConfig = $this->curl->req($this->config->item('officialUrl'), $posts);
        $data = json_decode($miningGameConfig,true);

        foreach ($data['miningGameConfig'] as $key=>$row){
            $id  = array_column($row['hookUpSpeed'],'id');
            $speed= array_column($row['hookUpSpeed'],'speed');
            $temp = [];
            foreach ($id as $x=>$y){
                $temp[$y] = $speed[$x];
            }
            $data['miningGameConfig'][$key]['hookUpSpeed'] = $temp;
        }
        $data['pageMax'] = ($page+1) * 5;
        $data['pageMin'] = $page * 5;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $data['idData'] = $retData['props'];
        $this->load->view('config/miningGame', $data);
    }

    public function actionMiningGameConfig(){
        $input = $this->input->post();
        $data = $input['config'];
        foreach ($data as $key=>$row){
            foreach ($row as $x=>$y){
                $temp = $y;
                if(is_array($temp)){
                    if($x == "mineralData"){
                        $mineralData = [];
                        foreach ($temp as $row){
                            $mineralData[] = $row;
                        }
                        $temp = $mineralData;
                    }
                    $data[$key][$x] = json_encode($temp,JSON_NUMERIC_CHECK);
                }
            }
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveMiningGameConfig';
        $posts['data'] = json_encode($data,JSON_NUMERIC_CHECK);
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        $retData = json_decode($retData,true);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeMiningGameJson();
            return $this->response(0, '操作成功');
        }
    }

    public function actionMiningGameRewardConfig(){
        $input = $this->input->post();
        $data['reward']  = $input['reward'];
        $data['refreshTimeDiamond'] = $input['refreshTimeDiamond'];

        $rewardBet = [];
        foreach ($input['rewardBet']['minLv'] as $key=>$row){
            $rewardBet[] = [
                'minLv'  => $row,
                'maxLv'  => $input['rewardBet']['maxLv'][$key],
                'bet'    => $input['rewardBet']['bet'][$key],
            ];
        }
        $data['rewardBet'] = $rewardBet;

        $rewardStage = [];
        foreach ($input['rewardStage'] as $key=>$row){
            $temp = ['levelId'=> $row['levelId']];
            $props= [];
            foreach ($row['propsId'] as $k=>$p){
                $props[] = [
                    'propsId' => $p,
                    'num' => $row['num'][$k],
                ];
            }
            $temp['props'] = $props;
            $rewardStage[] = $temp;
        }
        $data['rewardStage'] = $rewardStage;

        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveMiningGameReward';
        $posts['data'] = json_encode($data,JSON_NUMERIC_CHECK);
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeMiningGameJson();
            return $this->response(0, '操作成功');
        }
    }

    public function makeMiningGameJson(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeMiningGameJson';
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        $retData = json_decode($retData,true);
        self::SaveJson($retData['data'],$retData['filename']);
    }

    public function vipConfig(){
        $vipVersion = "155";
        $this->session->set_userdata('vipVersion',$vipVersion);
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getVipConfig';
        $posts['vipVersion'] = 155;
        $url  = $this->config->item('officialUrl');
        $vipConfig = $this->curl->req($url, $posts);
        $data['vipConfig'] = json_decode($vipConfig,true);
        $data['type'] = $vipVersion > 0 ? "日" : "周";
        $this->load->view('config/vipConfig', $data);
    }

    public function actionVipConfig(){
        $input = $this->input->post();
        $config = $input['vip'];
        foreach ($config as $key=>$row){
            foreach ($row as $x=>$y){
                if(is_array($y)){
                    $config[$key][$x] = json_encode($y,JSON_NUMERIC_CHECK);
                }
            }
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveVipConfig';
        $posts['data'] = json_encode($config);
        $posts['filename'] = "VipConfig".time().".json";
//        $posts['vipVersion'] = $this->session->userdata('vipVersion');
        $posts['vipVersion'] = 155;


        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            foreach ($config as $row){
                $temp = [];
                $temp['level'] = $row['lv'];
                $temp['point'] = $row['integration'];

                // 新增 ---------------------------
                if(!empty($row['dayVipPoint']) && $row['dayVipPoint'] != 0){
                    $temp['privilege'][] = ['id'  => 801, 'num' => $row['dayVipPoint']];
                    $temp['dailyReward'][] = ['propsId'  => 24, 'num' => $row['dayVipPoint']];
                }
                //1.8.5VIP特权版本取消每日体力奖励
                if(!empty($row['weekRewardSpins']) && $row['weekRewardSpins'] != 0){
                    //$temp['privilege'][]   = ['id'  => 901, 'num' => $row['weekRewardSpins']];
                    //$temp['dailyReward'][] = ['propsId'  => 15, 'num' => $row['weekRewardSpins']];
                }
                if(!empty($row['spinsRestore']) && $row['spinsRestore'] != 0){
                    $temp['privilege'][] = ['id'  => 501, 'num' => $row['spinsRestore']];
                }
                if(!empty($row['attackCoinsPro']) && $row['attackCoinsPro'] != 0){
                    $temp['privilege'][] = ['id'  => 1001, 'num' => $row['attackCoinsPro']];
                }
                if(!empty($row['stealCoinsPro']) && $row['stealCoinsPro'] != 0){
                    $temp['privilege'][] = ['id'  => 1101, 'num' => $row['stealCoinsPro']];
                }
                //1.8.5VIP特权取消炮台样式进化
                if(!empty($row['attackCss']) && $row['attackCss'] != 0){
                    //$temp['privilege'][] = ['id'  => 1200+$row['attackCss'], 'num' => 1];
                }
                if(!empty($row['shieldGroove']) && $row['shieldGroove'] != 0){
                    $temp['privilege'][] = ['id'  => 401, 'num' => $row['shieldGroove']];
                }
                //1.8.5VIP特权取消额外签到奖励
                if(!empty($row['signInBet']) && $row['signInBet'] != 0){
                    //$temp['privilege'][] = ['id'  => 101, 'num' => $row['signInBet']];
                }
                if(!empty($row['shopAppend']) && $row['shopAppend'] != 0){
                    $temp['privilege'][] = ['id'  => 701, 'num' => $row['shopAppend']];
                }
                //1.8.5VIP特权取消每日转盘增加次数
                if(!empty($row['turnTable'])){
                    $turnTable = json_decode($row['turnTable'],true);
                    if($turnTable['num'] != 0){
                        $turnTable['num'] = 0;
                        $temp['privilege'][] = json_decode($row['turnTable'],true);
                    }
                }
                if(!empty($row['miningGame']) && $row['miningGame'] != 0){
                    $temp['privilege'][] = ['id'  => 1301, 'num' => $row['miningGame']];
                }
                if(!empty($row['mock']) && $row['mock'] != 0){
                    $temp['privilege'][] = ['id'  => 1400+$row['mock'], 'num' => 1];
                }
                if(!empty($row['avatarBox']) && $row['avatarBox'] != 0){
                    $temp['privilege'][] = ['id'  => 300+$row['avatarBox'], 'num' => 1];
                }
                //1.8.5VIP特权取消一键建造
                if(!empty($row['oneClick']) && $row['oneClick'] != 0){
                    //$temp['privilege'][] = ['id'  => 1501, 'num' => $row['oneClick']];
                }


//                if(!empty($row['taskRewardBet']) && !in_array($row['taskRewardBet'],[0,1])){
//                    $temp['privilege'][] = ['id'  => 201, 'num' => $row['taskRewardBet']];
//                }
//                if(!empty($row['weekRewardShield']) && $row['weekRewardShield'] != 0){
//                    $temp['weekReward'][] = ['id'  => 201, 'num' => $row['weekRewardShield']];
//                    $temp['dailyReward'][] = ['id'  => 201, 'num' => $row['weekRewardShield']];
//                }
//                $chest = json_decode($row['weekRewardChest'],true);
//                if(!empty($chest) && $chest['propsId'] != 0 && $chest['num'] != 0){
//                    $temp['weekReward'][] = ['id'  => 300+$chest['propsId'],'num' => $chest['num']];
//                    $temp['dailyReward'][] = ['id'  => 300+$chest['propsId'],'num' => $chest['num']];
//                }
//                $bless = json_decode($row['weekRewardBless'],true);
//                if(!empty($bless) && $bless['propsId'] != 0 && $bless['num'] != 0){
//                    $temp['weekReward'][] = ['id'  => 401, 'num' => $bless['num']];
//                    $temp['dailyReward'][] = ['id'  => 401, 'num' => $bless['num']];
//                }
//                $luckyDraw = json_decode($row['weekRewardLuckydraw'],true);
//                if(!empty($luckyDraw) && $luckyDraw['propsId'] != 0 && $luckyDraw['num'] != 0){
//                    $temp['weekReward'][] = ['id'  => 501, 'num' => $luckyDraw['num']];
//                    $temp['dailyReward'][] = ['id'  => 501, 'num' => $luckyDraw['num']];
//                }
                $data[] = $temp;
            }
            self::SaveJson($data,$posts['filename']);
            return $this->response(0, '操作成功');
        }
    }

    public function crazyBet(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getCrazyBetConfig';
        $url  = $this->config->item('officialUrl');
        $crazyBetConfig = $this->curl->req($url, $posts);
        $crazyBetConfig = json_decode($crazyBetConfig,true);
        $data = [];
        foreach ($crazyBetConfig['config'] as $item) {
            if($item['actData'] == 0){
                $data[] = $item;
            }
        }
        $data = [
            'crazyBetConfig' => $data,
        ];
        $this->load->view('config/crazyBetConfig', $data);
    }

    public function actionCrazyBet(){
        $input = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setCrazyBetConfig';
        $posts['data']= json_encode($input['config']);
        $posts['filename']= "CrazyBetConfig".time().".json";
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $posts['act'] = 'getCrazyBetConfig';
            $crazyBetConfig = $this->curl->req($url, $posts);
            $crazyBetConfig = json_decode($crazyBetConfig,true);
            $data = [];
            foreach ($crazyBetConfig['config'] as $item) {
                $temp = [
                    "bet"    =>$item['bet'],
                    "levelId"=>$item['levelId'],
                    "spins"  =>$item['spins'],
                    "spinsLimit"  =>$item['spinsLimit'],
                ];
                if($item['actData'] == 0){
                    $data['normalConfig'][] = $temp;
                }else if($item['actData'] == 1){
                    $data['superBetConfig'][] = $temp;
                }
            }
            $data['actSpinsLimit'] = $crazyBetConfig['actSpinsLimit'];
            self::SaveJson($data,$posts['filename']);
            return $this->response(0, '操作成功');
        }
    }

    public function rewardCenter(){
        $tb  = otable::RewardCenterConfig();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('games')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $k=>$one){
            if(in_array($one['id'],[3,4,5,6,7,8,9,10,15,19,21,22,23,32,34,42,47])){
                unset($ret[$k]);
            }
        }
        $comCfg = oo::commonOprRedis('games')->hGetAll(okeys::IconShowCommonConf());
        $data= [
            'config' => $ret,
            'rightMaxShow'=>$comCfg['rightMaxShow']
        ];
        $this->load->view('config/rewardCenter', $data);
    }

    public function actionRewardCenter(){
        $input = $this->input->post();
        $tb  = otable::RewardCenterConfig();
        $data= $input['config'];
        $rightMaxShow = $input['rightMaxShow']?$input['rightMaxShow']:6;
        $cacheKey = okeys::RewardCenterShow();
        foreach ($data as $row){
            if(isset($row['isShow'])){
                $up = " isShow={$row['isShow']} ";
                oo::commonOprRedis('games')->hSet($cacheKey,$row['id'],$row['isShow']);
                oo::commonOprRedis('games')->hSet(okeys::actCenterShowType(1),$row['id'],$row['isShow']);
            }
            if(isset($row['isShowBtn'])){
                $up .= ",isShowBtn={$row['isShowBtn']} ";
                oo::commonOprRedis('games')->hSet(okeys::actCenterShowType(2),$row['id'],$row['isShowBtn']);
            }
            if(isset($row['isShowCountdown'])){
                $up .= ",isShowCountdown={$row['isShowCountdown']} ";
                oo::commonOprRedis('games')->hSet(okeys::actCenterShowType(3),$row['id'],$row['isShowCountdown']);
            }
            if(isset($row['iconWeight'])){
                $up .= ",iconWeight={$row['iconWeight']} ";
                oo::commonOprRedis('games')->hSet(okeys::actCenterShowType(4),$row['id'],$row['iconWeight']);
            }
            if(isset($row['position'])){
                $up .= ",position={$row['position']} ";
                oo::commonOprRedis('games')->hSet(okeys::actCenterShowType(5),$row['id'],$row['position']);
            }
            if(isset($row['propsWeight'])){
                $up .= ",propsWeight={$row['propsWeight']} ";
                oo::commonOprRedis('games')->hSet(okeys::actCenterShowType(5),$row['id'],$row['propsWeight']);
            }
            if($up){
                $sql = "UPDATE {$tb} SET {$up} WHERE id='{$row['id']}'";
                $ret[$row['id']] = oo::commonOprDb('games')->query($sql);
            }
        }

        $sql = "SELECT * FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('games')->getAll($sql,MYSQLI_ASSOC);
        $json = ["list"=>$ret,"rightMaxShow"=>$rightMaxShow];


        oo::commonOprRedis('games')->hSet(okeys::IconShowCommonConf(),'rightMaxShow',$rightMaxShow);

        $filename = "IconConfig".time().'.json';
        $tb = otable::StaticConfig();
        $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='IconConfig'";
        oo::commonOprDb('games')->query($sql);
        oo::commonOprRedis('games')->hSet(okeys::StaticConfig(),'IconConfig',$filename);

        self::SaveJson($json,$filename);

        oo::logs()->adminlog($this->router->fetch_method());
        return $this->response(0, '操作成功',$ret);
    }

    public function mainBg(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getMainBgConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);
        $this->load->view('config/mainBg', $data);
    }

    public function actionMainBg(){
        $input = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setMainBgConfig';
        $posts['data']= json_encode($input['config']);
        $posts['filename']= "MainBgConfig".time().".json";
        $url  = $this->config->item('officialUrl');

        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $json = $input['config'];
            sort($json);
            self::SaveJson($json,$posts['filename']);
            return $this->response(0, '操作成功');
        }
    }

    public function maxLevelReward(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getMaxLevelRewardConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);
        $this->load->view('config/maxLevelReward', $data);
    }

    public function actionMaxLevelReward(){
        $input = $this->input->post();
        $props = [];
        foreach ($input['props']['propsId'] as $key=>$row){
            $props[] = [
                'propsId' => $row,
                'num'     => $input['props']['num'][$key],
            ];
        }
        $data  = [
            'coins' => [
                'coins' => $input['coins'],
                'bet'   => $input['bet']
            ],
            'spins' => $input['spins'],
            'props' => $props,
        ];
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setMaxLevelRewardConfig';
        $posts['data']= json_encode($data,JSON_NUMERIC_CHECK);
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }

    }

    public function makeTaskCenterJson(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeTaskCenterJson';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData =json_decode($retData,true);
        return self::SaveJson($retData['data'],$retData['filename']);
    }

    public function loginBulletBox(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'loginBulletBox';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);
        $this->load->view('config/loginBulletBox', ['list'=>$data]);
    }

    public function actionLoginBulletBox(){
        $input = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setLoginBulletBox';
        $posts['data']= json_encode($input['config']);
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            self::makeLoginBulletBoxJson();
            return $this->response(0, '操作成功');
        }
    }

    public function addLoginBulletBox()
    {
        $params = $this->input->post();

        $tb = otable::LoginBulletBox();
        $sql = funs::db_insertSQL($tb, $params);

        $res = oo::commonOprDb('games')->query($sql);
        if (!$res) {
            return $this->response(1, '操作失败');
        } else {
            oo::commonOprRedis('games')->delete(okeys::LoginBulletBox());

            self::makeLoginBulletBoxJson();
            return $this->response(0, '操作成功');
        }
    }

    public function makeLoginBulletBoxJson(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeLoginBulletBoxJson';
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,true);
        self::SaveJson($retData['data'],$retData['filename']);
    }

    public function recall(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'recallConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);
        $this->load->view('config/recall', ['list'=>$data]);
    }

    public function actionRecall(){
        $input = $this->input->post();
        $data  = [];
        foreach($input["day"] as $key=>$row){
            $data[] = [
                'day'    => $row,
                'reward' => [
                    'coins' => [
                        'coins' => $input["coins"][$key],
                        'bet'   => $input["bet"][$key],
                    ],
                    'spins' => $input["spins"][$key]
                ],
            ];
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'setRecallConfig';
        $posts['data']= json_encode($data);
        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function makeBeginGuideJson(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeBeginGuideJson';
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        $retData = json_decode($retData,true);
        self::SaveJson($retData['data'],$retData['filename']);
    }

    /**
     * 打金币配置
     */
    public function attackCoinConfig($page = 0)
    {
        $pageSize = 1500;
        if($page == 0){
            $page = $pageSize;
        }else{
            $page += $pageSize;
        }
        $title = ['关卡','有盾','无盾'];
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getAttackCoinConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page_size'] = $pageSize;
        $posts['page'] = $page/$pageSize;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $posts['page'];
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#config/attackCoinConfig');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $pageSize;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $this->load->view('config/attackCoinConfig', $data);
    }

    /**
     * 修改打金币配置
     */
    public function actionAttackCoinConfig(){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);

        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'shield' =>$row->data[0]->shield,
                'no_shield' =>$row->data[1]->no_shield,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'saveAttackCoinConfig';
        $posts['lid'] = '1';
        $posts['sid'] = '1';
        $posts['page'] = $postData['page'];
        $posts['data'] = json_encode($upload,JSON_UNESCAPED_UNICODE);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);;

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function starExchange(){
        $tb  = otable::StarExchange();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['spinsNum']   = json_decode($row['spinsNum'],true);
            $ret[$key]['petExp']     = json_decode($row['petExp'],true);
            $ret[$key]['chestPrice'] = json_decode($row['chestPrice'],true);
        }
        $this->load->view('config/starExchange', ['list'=>$ret]);
    }

    public function actionStarExchange(){
        $input = $this->input->post('good');
        $tb    = otable::StarExchange();
        foreach ($input as $propsId=>$row){
            $input[$propsId]['chestPrice'] = json_encode($row['chestPrice'],JSON_NUMERIC_CHECK);
            unset($input[$propsId]['propsId']);
            $set = "";
            foreach ($input[$propsId] as $key=>$value){
                $set .= "`{$key}`='{$value}',";
            }
            $set = trim($set,',');
            $sql = "UPDATE {$tb} SET {$set} WHERE propsId={$propsId}";
            $ret = oo::commonOprDb('games')->query($sql);
        }
        oo::logs()->adminlog($this->router->fetch_method());
        if($ret == 0){
            return $this->response(1, '操作失败');
        }else{
            oo::commonOprRedis('games')->delete(okeys::StarExchangeConfig());
            return $this->response(0, '操作成功');
        }
    }

    public function activityCoins(){
        $tb = otable::ActivityCoins();
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $this->load->view('config/activityCoins', ['list'=>$ret, 'keys' => ACTIVITY_COIN_HEADERS]);
    }

    public function actionActivityCoins()
    {
        $tb = otable::ActivityCoins();
        $data = json_decode($this->input->post('data'), true);
        foreach ($data as $row) {
            $sql = funs::db_updateSQL($tb, $row, "levelId={$row['levelId']}");
            oo::commonOprDb('games')->query($sql);
        }

        oo::logs()->adminlog($this->router->fetch_method());

        // 更新缓存
        oo::commonOprModel('config')->upActivtityCoinCache();


        return $this->response(0, '操作成功');
    }

    public function levelBaseCoins()
    {
        $tb = otable::LvCoinsConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}");

        $typeMap = [0 => 'default'];

        $data = [];
        foreach ($ret as $row) {
            $type = $typeMap[$row['type']] ?? '';
            if(empty($type)){
                continue;
            }
            $data[$row['lv']][$type] = $row['value'];
        }

        $this->load->view('config/levelBaseCoins', ['list' => $data]);
    }

    public function updateLevelBaseCoins()
    {
        $typeMap = ['default' => 0];

        $tb = otable::LvCoinsConfig();
        $data = json_decode($this->input->post('data'), true);

        foreach ($data as $row) {
            $level = $row['lv'];

            foreach ($typeMap as $tn => $type) {
                $value = $row[$tn];
                $sql = "UPDATE {$tb} SET `value` = $value  WHERE lv={$level} AND type={$type}";
                oo::commonOprDb('games')->query($sql);
            }
        }
        oo::logs()->adminlog($this->router->fetch_method());

        // 更新缓存
        oo::commonOprModel('config')->updateLvBaseCoinsCache();

        return $this->response(0, '操作成功');
    }

    public function polymerization(){
        $tb = otable::Polymerization(2);
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $this->load->view('advertisement/polymerization', ['list'=>$ret]);
    }

    public function polymerizationEdit($id){
        $tb = otable::Polymerization(2);
        $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id}",MYSQLI_ASSOC);
        $ret['reward']    = json_decode($ret['reward'],true);
        $ret['group_pro'] = json_decode($ret['group_pro'],true);
        $userGroup = oo::commonOprModel('config')->getUserGroupConfig2();
        $configSSGroupShow = oo::commonOprRedis('statistics')->hGetAll(okeys::configSSGroupShow());
        $hideSSgroups = array_keys($configSSGroupShow);
        $userGroupTypes = [
            1 => '广告分组',
            5 =>'数数分组',
        ];
        $userGroups = [];
        foreach ($userGroup as $key=>$row){
            if(in_array($row['id'], $hideSSgroups))continue;
            if($userGroupTypes[$row['cid']]){
                $userGroups[$row['cid']][] = $row;
            }
        }
        foreach ($ret['group_pro'] as $k => $v){
            if(empty($v['type']))$ret['group_pro'][$k]['type'] = 1;
        }
        $this->load->view('advertisement/polymerizationEdit', ['info'=>$ret,'userGroups'=>$userGroups,'userGroupTypes'=>$userGroupTypes]);
    }

    public function actionPolymerization(){
        $postData = $this->input->post();
        $tb = otable::Polymerization(2);
        $reward = [];
        $sql = "UPDATE {$tb} SET ";
        $sql.= "cd='{$postData['cd']}',trueId='{$postData['trueId']}',trueId_ios='{$postData['trueId_ios']}',max='{$postData['max']}',status='{$postData['status']}',sceneId='{$postData['sceneId']}',sceneId_ios='{$postData['sceneId_ios']}',";
        if(isset($postData['spins'])){
            $reward = ['specialReward'=>0,'reward'=>['spins'=>$postData['spins']]];
        }else if(isset($postData['shield'])){
            $reward = ['specialReward'=>0,'reward'=>['shield'=>$postData['shield']]];
        }else if(isset($postData['coins'])){
            $reward = ['specialReward'=>0,'reward'=>['coins'=>['coins'=>$postData['coins'],'bet'=>$postData['bet']]]];
        }else if(isset($postData['chestId'])){
            $reward = ['specialReward'=>0,'reward'=>['chestId'=>$postData['chestId']]];
        }else if(isset($postData['config'])){
            $reward = ['specialReward'=>1,'config'=>$postData['config']];
        }else if(isset($postData['time'])){
            $tb = otable::Polymerization(2);
            $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$postData['id']}",MYSQLI_ASSOC);
            $ret['reward']    = json_decode($ret['reward'],true);
            $ret['reward']['time'] = $postData['time'];
            $reward = $ret['reward'];
        }else if(isset($postData['bet'])){
            $tb = otable::Polymerization(2);
            $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$postData['id']}",MYSQLI_ASSOC);
            $ret['reward']    = json_decode($ret['reward'],true);
            $ret['reward']['bet'] = $postData['bet'];
            $reward = $ret['reward'];
        }
        if(!empty($reward)){
            $reward = addslashes(json_encode($reward));
            $sql.= "reward='{$reward}',";
        }

        if(!empty($postData['group_pro'])){
            $group_pro = [];
            $idArr = [];
            $config = oo::commonOprModel('config')->getUserGroupConfig2();
            $config = array_column($config,NULL,"id");
            foreach ($postData['group_pro']['id'] as $k=>$r){
                if(in_array($r,$idArr)){
                    continue;
                }
                $idArr[] = $r;
                $group_pro[] = [
                    'id'      => $r,
                    'v'       => $postData['group_pro']['v'][$k],
                    'type'    => $postData['group_pro']['type'][$k],
                    'levelId' => $postData['group_pro']['levelId'][$k],
                    'num'     => $postData['group_pro']['num'][$k],
                    'sort'    => $config[$r]['sort'],
                ];
            }
            array_multisort(array_column($group_pro,'sort'),SORT_ASC,$group_pro);
            $group_pro = addslashes(json_encode($group_pro,JSON_NUMERIC_CHECK));
            $sql.= "group_pro='{$group_pro}',";
        }

        $sql = trim($sql,',');
        $sql.= " WHERE id={$postData['id']} LIMIT 1";
        oo::commonOprDb('games')->query($sql) && oo::commonOprRedis('games')->delete(okeys::Polymerization(3));

        oo::logs()->adminlog($this->router->fetch_method());

        return $this->response(0, '操作成功');
    }

    /*
	* 支付加倍配置
	*/
    public function turnPaybetConfig(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getTurnPaybetConfig';
        $url  = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        $data = json_decode($config,true);
        $this->load->view('config/turnPaybetConfig', ['list'=>$data]);
    }

    /*
	* 支付加倍配置
	*/
    public function setTurnPaybetConfig(){
        $input = $this->input->post();
        $posts = $this->postData;
        $data = [];
        foreach($input['price'] as $id => $row){
            $data['price'][$id] = $row;
            $data['list'][$id] = $input['list'][$id];
        }
        $posts['type'] = $input['type'];
        $posts['mod'] = 'Config';
        $posts['act'] = 'setTurnPaybetConfig';
        $posts['data']= json_encode($data,JSON_UNESCAPED_UNICODE);

        $url  = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function updateUserGroup(){
        oo::commonOprModel('member')->updateUserGroup2();
    }
    public function userGroup(){
        $ret = oo::commonOprModel('config')->getUserGroupConfig();
        $this->load->view('config/userGroup', ['list'=>$ret]);
    }

    public function editUserGroup($id){
        $ret = oo::commonOprModel('config')->getUserGroupConfig($id);
        $condition = oo::commonOprModel('config')->getUserGroupConditionConfig($id);
        $action = ['point','levelId','active','onlineTime','regTime','friendNum','sendCardNum','friendRank','countryRank','worldRank'];
        foreach ($condition as $key=>$row){
            if(in_array($key,$action) && $row != 0){
                $condition[$key] = explode(',',$row);
            }
        }
        $condition['countrySet'] = json_decode($condition['countrySet'],true);
        $condition['adjustGroup'] = json_decode($condition['adjustGroup'],true);
        $country = ['RO'=>'罗马尼亚', 'US'=>'美国', 'DE'=>'德国', 'GB'=>'英国', 'ES'=>'西班牙', 'FR'=>'法国', 'IN'=>'印度', 'VN'=>'越南', 'OTHER'=>'其他'];
        $this->load->view('config/editUserGroup', ['id'=>$id,'info'=>$ret,'condition'=>$condition,'country'=>$country]);
    }

    public function actionUserGroup(){
        $input = $this->input->post();
        $id    = $input['id'];
        $name    = $input['name'];
        $adPro   = $input['adPro'];
        $adTotal = $input['adTotal'];
        $tb = otable::UserGroupConfig();
        $retData = oo::commonOprDb('games')->query("UPDATE {$tb} SET name='{$name}',adPro='{$adPro}',adTotal='{$adTotal}' WHERE id={$id}");
        oo::commonOprRedis('games')->delete(okeys::UserGroupConfig());

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function actionUserGroupCondition(){
        $input = $this->input->post();
        $id    = $input['id'];
        $platform = $input['platform'];
        $userType = $input['userType'];
        $vip      = $input['vip'];
        $point    = $input['point'];
        if($point == 1){
            $point = implode(',',$input['points']);
        }
        $levelId  = $input['levelId'];
        if($levelId == 1){
            $levelId = implode(',',$input['levelIds']);
        }
        $firstPay = $input['firstPay'];
        $active   = $input['active'];
        if($active == 1){
            $active = implode(',',$input['actives']);
        }
        $onlineTime  = $input['onlineTime'];
        if($onlineTime == 1){
            $onlineTime = implode(',',$input['onlineTimes']);
        }
        $regTime     = $input['regTime'];
        if($regTime == 1){
            $regTime = implode(',',$input['regTimes']);
        }
        $friendNum   = $input['friendNum'];
        if($friendNum == 1){
            $friendNum = implode(',',$input['friendNums']);
        }
        $friendRank  = $input['friendRank'];
        if($friendRank == 1){
            $friendRank = implode(',',$input['friendRanks']);
        }
        $countryRank = $input['countryRank'];
        if($countryRank == 1){
            $countryRank = implode(',',$input['countryRanks']);
        }
        $worldRank   = $input['worldRank'];
        if($worldRank == 1){
            $worldRank = implode(',',$input['worldRanks']);
        }
        $countrySet   = $input['countrySet'];
        if($countrySet == 1){
            $countrySet = json_encode($input['countrySetArr']);
        }
        $adjustGroup   = $input['adjustGroup'];
        if($adjustGroup == 1){
            $adjustGroup = json_encode($input['adjustGroupArr']);
        }
        $set = "platform='{$platform}',userType='{$userType}',vip='{$vip}',point='{$point}',levelId='{$levelId}',firstPay='{$firstPay}',active='{$active}',onlineTime='{$onlineTime}',";
        $set.= "regTime='{$regTime}',friendNum='{$friendNum}',friendRank='{$friendRank}',countryRank='{$countryRank}',worldRank='{$worldRank}',countrySet='{$countrySet}',adjustGroup='{$adjustGroup}'";
        $tb  = otable::UserGroupConditionConfig();
        $retData = oo::commonOprDb('games')->query("UPDATE {$tb} SET {$set} WHERE id={$id}");
        oo::commonOprRedis('games')->delete(okeys::UserGroupConditionConfig());

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function treasurepro($version = ''){
        $tb  = otable::TreasureProConfig($version);
        $sql = "SELECT * FROM {$tb}";
        $ret = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['pro'] = json_decode($row['pro'],true);
            $ret[$key]['superBet'] = json_decode($row['superBet'],true);
        }
        $data['list'] = $ret;
        $data['title'] = $this->treasurepro_title;
        if($version){
            array_shift($data['title']);
            array_unshift($data['title'], '任务层');
            $this->load->view('config/treasurepro2', $data);
        } else {
            $this->load->view('config/treasurepro', $data);
        }
    }

    public function actionTreasurePro($version = ''){
        $input = $this->input->post('data');
        $input = json_decode($input,true);
        $tb  = otable::TreasureProConfig($version);
        $column = $version ? 'taskId' : 'levelId';
        foreach ($input as $row){
            $pro      = json_encode($row['pro'],JSON_NUMERIC_CHECK);
            $superBet = json_encode($row['superBet'],JSON_NUMERIC_CHECK);
            $id = $row[$column];
            $retData = oo::commonOprDb('games')->query("UPDATE {$tb} SET pro='{$pro}',superBet='{$superBet}' WHERE {$column}={$id}");
        }
        oo::commonOprRedis('games')->delete(okeys::TreasureProConfig($version));

        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function shareLink(){
        $tb  = otable::ShareLinkConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} order by id DESC ",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['data'] = json_decode($row['data'],true);
            if(in_array($row['action'],[1,4,5])){
                //奖励 & 开启活动
                $ret[$key]['success'] = oo::commonOprRedis('games')->hLen(okeys::ShareLinkReward($row['id']));
            }else if($row['action'] == 2){
                //兑换码
                $tb  = otable::exchangeCode();
                $code = $ret[$key]['data']['content'];
                $exchangeCode = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE code={$code} LIMIT 1",MYSQLI_ASSOC);
                $ret[$key]['success'] = $exchangeCode['rwdNum'];
            }else{
                //开启页面
                $ret[$key]['success'] = 0;
            }
        }
        $this->load->view('config/sharelink', ['list'=>$ret, 'time' => time()]);
    }

    public function editShareLink($id = 0){
        $ret = [];
        if($id){
            $tb  = otable::ShareLinkConfig();
            $ret = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
            $ret['data'] = json_decode($ret['data'],true);
        }

//        $posts = $this->postData;
//        $posts['mod'] = 'Config';
//        $posts['act'] = 'getPropsConfig';
//        $retData = $this->httpPost($posts);
        $this->load->view('config/editShareLink', ['info'=>$ret]);
    }

    public function actionEditShareLink(){
        $input  = $this->input->post();
        $data   = $input['data'];
        $data['props']   = json_decode($input['data']['props'],true);
        $name   = $input['name'];
        $num    = $input['num'];
        $action = $input['action'];
        $expireTime = strtotime($input['expireTime']);
        $userLimit  = $input['userLimit'];
        if($expireTime < time()){
            return $this->response(1, '时间已过期');
        }
        if(empty($num) || empty($name) || empty($action) || empty($expireTime)){
            return $this->response(1, '请填写数据');
        }
        $tempData = json_encode($data,JSON_NUMERIC_CHECK);
        $tb     = otable::ShareLinkConfig();
        if(!empty($input['id'])){
            $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET expireTime='{$expireTime}',userLimit='{$userLimit}',data='{$tempData}' WHERE id={$input['id']}");
            if($ret == 0){
                return $this->response(1, '操作失败');
            }
            oo::commonOprRedis('games')->delete(okeys::ShareLinkConfig($input['id']));
            return $this->response(0, '操作成功');
        }
//        if($action == 1||$action == 5){
//            $props = $data['props'];
//            $temp  = [];
//            foreach ($props['propsId'] as $key=>$row){
//                $temp[] = [
//                    'propsId' => $row,
//                    'num'     => $props['num'][$key]
//                ];
//            }
//            $temp[] = ['propsId'=>14,'gid'=>oo::commonOprModel('config')->coinsToGid($data['coins']['coins']),'bet'=>$data['coins']['bet']];
//            $temp[] = ['propsId'=>15,'num'=>$data['spins']];
//            $data['props'] = $temp;
//            unset($data['spins']);
//            unset($data['coins']);
//        }
        $created= time();
        oo::commonOprDb('games')->query("INSERT INTO {$tb} (name,action,num,data,created,expireTime,userLimit)VALUE('{$name}','{$action}','{$num}','{$tempData}','{$created}','{$expireTime}','{$userLimit}')");
        $lastId = oo::commonOprDb('games')->insertID();

        if($action == 1||$action == 5){//1 分享奖励 5 邮件验证奖励
            $jumpId = 101;
        }else if($action == 2){
            $jumpId = 22;
        }else if($action == 3){
            $jumpId = $data['jumpId'];
        }else if($action == 4){
            $jumpId = $data['activityId'] + 101;
        }
        $base64 = base64_encode(json_encode([
            'id'      => $lastId,
            'jumpId'  => $jumpId,
            'action'  => $action,
            'data'    => $data,
            'expire'  => $expireTime,
        ],JSON_NUMERIC_CHECK));
        $sign = $this->getShareLinkSign($lastId);
        $oos_debug = $this->config->item('oos_debug');
        if($oos_debug){
            $longUrl = "https://share.crazycoin.link/link.php?id={$lastId}&sign={$sign}";
        }else{
            $longUrl = "https://share.crazycoin.link/link.php?id={$lastId}&sign={$sign}";
        }
        //短链拼接
        $hashids = Hashids::instance(6,THIS_PROJECT_NAME);
        if($oos_debug){//避免测试与正式混用code
            $encode_id = $hashids->encode(10000000+$lastId);
        }else{
            $encode_id = $hashids->encode($lastId);
        }
        $did = "C".$encode_id;
//        $shortUrl = STORT_URL."/{$did}";
        $shortUrl = STORT_URL."/?code={$did}";
        $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET longUrl='{$longUrl}',shortUrl='{$shortUrl}',did='{$did}' WHERE id={$lastId}");
        if($ret == 0){
            return $this->response(1, '操作失败');
        }
        $linkData = oo::commonOprDb('games')->getAll("SELECT did,longUrl FROM {$tb} WHERE did!=''");
        $arr=[];
        foreach ($linkData as $item){
            $arr[$item['did']] = $item['longUrl'];
        }
//        $setUrl = STORT_URL."/?type=set&from=".THIS_PROJECT_NAME."&data=".base64_encode(json_encode($arr));
        $dataStr = base64_encode("id={$lastId}&sign={$sign}");
        $setUrl = STORT_URL."/?type=set&from=".THIS_PROJECT_NAME."&code={$did}&data=".$dataStr;
        funs::sendCurl($setUrl);
        return $this->response(0, '操作成功',[$arr,$setUrl]);
    }
    private function getShareLinkSign($lastId){
        $shareKey = md5('3yz@VASObh');
        $str = "id={$lastId}";
        return md5("{$str}&cfk={$shareKey}");

    }
    public function delShareLink(){
        $input  = $this->input->post();
        $id     = $input['id'];
        $tb  = otable::ShareLinkConfig();
        $ret = oo::commonOprDb('games')->query("DELETE FROM {$tb} WHERE id={$id} LIMIT 1");
        if($ret == 0){
            return $this->response(1, '操作失败');
        }
        oo::commonOprRedis('games')->delete([
            okeys::ShareLinkConfig($id),
            okeys::ShareLinkReward($id),
        ]);
        return $this->response(0, '操作成功');
    }

    //活动图片资源目录配置
    public function activeImgNameConfig(){
        $maxId = 0;
        oo::commonOprRedis('games')->delete(okeys::ActiveImgNameConfig());
        $tmp = oo::commonOprModel('config')->getActiveImgNameConfig(0,false);
        $ret = [];
        foreach($tmp as $val){
            if(empty($val['show'])){
                continue;
            }
            $ret[] = $val;
            if($val['id'] > $maxId){
                $maxId = $val['id'];
            }
        }
        $data['data']  = $ret;
        $data['maxId'] = $maxId + 1;
        $data['href']  = "/filemanager.php?fm_usr=activity&fm_pwd=activity&userName=".get_cookie('chinesename')."&activityPath=";
        $data['debug'] = $this->config->item('oos_debug') ? 1 : 0;
        $this->load->view('config/activeImgNameConfig', $data);
    }

    //同步目录
    public function syncTitleConf(){
        set_time_limit(0);
        $input  = $this->input->post();

        $table = otable::ActiveImgNameConfig();
        $name = $input['parent'];
        $titleConf = oo::commonOprDb('slavedb')->getOne("select * from {$table} where `name`='{$name}'");

        $postParams["sid"]=1;
        $postParams["lid"]=1;
        $postParams["service"]=1;
        $postParams["act"]= 'syncTitleConf';
        $postParams["mod"]= 'Test';
        $postParams['parent'] = $input['parent'];
        $postParams['titleConf'] = $titleConf['title_conf'];
        $sendToPro = true;
        if($sendToPro){     #是否上传到正式环境
            $data['curlResult'] = $this->curl->req($this->config->item('officialProUrl'), $postParams); #调用正式环境api
        }else{
            $data['curlResult'] = $this->curl->req($this->config->item('officialDevUrl'), $postParams); #调用开发机api
        }

        return $this->response(0, '操作成功', $data);

    }
    public function syncDir(){
        set_time_limit(0);
        $input  = $this->input->post();
        $path = __ROOT__ . '/public/game/image/activity_2' . DIRECTORY_SEPARATOR . $input['type'];
        if(!is_dir($path)){
            return $this->response(0, '目录:'.$path.'不存在', [$input, $path]);
        }

        $relativePath = 'activity_2' . DIRECTORY_SEPARATOR . $input['type'];


        $postParams["sid"]=1;
        $postParams["lid"]=1;
        $postParams["service"]=1;
        $postParams["act"]= 'syncDir';
        $postParams["mod"]= 'Test';
        $postParams['parent'] = $input['parent'];
        $postParams['type'] = $input['type'];
        $postParams['name'] = $input['name'];
        $sendToPro = true;
        if($sendToPro){     #是否上传到正式环境
            $data['curlResult'] = $this->curl->req($this->config->item('officialProUrl'), $postParams); #调用正式环境api
            $sshScriptPath = __ROOT__ . DIRECTORY_SEPARATOR . 'autosshPro.sh';#备份脚本/创建文件夹
            $scpScriptPath = __ROOT__ . DIRECTORY_SEPARATOR . 'autoscpPro.sh';#文件同步脚本
        }else{
            $data['curlResult'] = $this->curl->req($this->config->item('officialDevUrl'), $postParams); #调用开发机api
            $sshScriptPath = __ROOT__ . DIRECTORY_SEPARATOR . 'autossh.sh';#备份脚本/创建文件夹
            $scpScriptPath = __ROOT__ . DIRECTORY_SEPARATOR . 'autoscp.sh';#文件同步脚本
        }



//        $sshCmd = $sshScriptPath . ' ' . $relativePath;
//        $scpCmd = $scpScriptPath . ' ' . $relativePath;
//        exec($sshCmd, $sshScriptResult ,$sshScriptStateCode);
//        exec($scpCmd, $scpScriptResult ,$scpScriptStateCode);
//        $data = [
//            'params' => $relativePath,
//            'ssh' => [
//                'path' =>$sshScriptPath,
//                'cmd' =>$sshCmd,
//                'result' =>$sshScriptResult,
//                'code' =>$sshScriptStateCode,
//            ],
//            'scp' => [
//                'path' =>$scpScriptPath,
//                'cmd' =>$scpCmd,
//                'result' =>$scpScriptResult,
//                'code' =>$scpScriptStateCode,
//            ],
//        ];
//        $data['curlResult'] = $this->curl->req($this->config->item('officialUrl'), $postParams);
        return $this->response(0, '操作成功', $data);

    }

    private function syncPermissionCheck($path, $file){
        if(empty($file))return false;
        if(in_array($file, ['Android', 'iOS']))return false;
        if(empty($path))return false;
        if(strpos($path, 'crazycoin/') !== 0)return false;
        if(strpos($path,'crazycoin/cfg') === false)return true;
        return false;
    }
    public function syncBundleDir(){
        $rsyncScript = '/mnt/sven/script/shell/rsync-prod.sh';
        set_time_limit(0);
        $oos_debug = $this->config->item('oos_debug');
        if(!$oos_debug)
            return $this->response(0, '操作成功！');

        $input  = $this->input->post();
        if(empty($input['path']))
            return $this->response(0, '非法操作！', [$input]);
        $path = ltrim($input['path'], '/' );
        $relativePath = __ROOT__ . '/public/game/' . $path;
        if(!is_dir($relativePath)
            && !file_exists($relativePath)
        )
            return $this->response(__LINE__ , '同步目标:'.$relativePath.'不存在', [$input, $relativePath]);

        $pathinfo = explode('/', trim($input['path'], '/' ));
        $file = end($pathinfo);
        if(!$this->syncPermissionCheck($path, $file))
            return $this->response(__LINE__ , '当前目标:'.$path.'不允许同步', [$input,  $path]);

        $path = ltrim($path, 'crazycoin');
        $path = ltrim($path, '/');
        $cmd = "{$rsyncScript}   {$path}";
        exec($cmd, $rsyncResult ,$rsyncStateCode);

        $data = [
            'params' => $path,
            'scp' => [
                'path' =>$rsyncScript,
                'cmd' =>$cmd,
                'result' =>$rsyncResult,
                'code' =>$rsyncStateCode,
            ],
        ];
        $successCode = [
            0,23
        ];
        return $this->response($rsyncStateCode, in_array($rsyncStateCode, $successCode) ? '操作成功' : '操作失败', $data);
    }

    public function refreshJsonConfig(){
        set_time_limit(0);
        $oos_debug = $this->config->item('oos_debug');
//        if(!$oos_debug) return $this->response(0, '操作成功！');
        $time = time();
        $input  = $this->input->post();
        if(empty($input['path'])||empty($input['type'])||!in_array($input['type'], ['Android', 'iOS']))
            return $this->response(0, '非法操作！', [$input]);
        $type = $input['type'];
        $path = trim($input['path'], DIRECTORY_SEPARATOR );
        $hkey = "CC_{$type}ActivityConfig";
        $jsonConfigFileName = "CC_{$type}ActivityConfig{$time}.json";
        $relativePath = __ROOT__ . '/public/game/' . DIRECTORY_SEPARATOR . $path;

        if(!is_dir($relativePath))
            return $this->response(__LINE__ , '目录:'.$relativePath.'不存在', [$input, $relativePath]);

        $actDirs = [];
        $typeDir = opendir($relativePath);
        $actConfigJsonData = [];
        while($actDir = readdir($typeDir)){
            if(in_array($actDir, ['.','..']))continue;
            $actDirPath = $relativePath . DIRECTORY_SEPARATOR . $actDir;
            $actDirHandler = opendir($actDirPath);
            $curTime = 0;
            $actConfigJsonData[$actDir] = '';
            while($actConfigFile = readdir($actDirHandler)){
                if(in_array($actConfigFile, ['.','..']))continue;
                if(strpos($actConfigFile, 'config_') !== 0)continue;
                $configFilePath = $actDirPath . DIRECTORY_SEPARATOR . $actConfigFile;
                $ftime = filemtime($configFilePath);
                if($ftime > $curTime){
                    $actConfigFile = rtrim($actConfigFile, '.json');
                    $curTime = $ftime;
                    $actConfigJsonData[$actDir] = $actConfigFile;
                }
            }

            $actDirs[] = $actDir;
        }

        $jsonConfigFilePath = __ROOT__ . '/public/game/config/' .$jsonConfigFileName ;
        file_put_contents($jsonConfigFilePath, json_encode($actConfigJsonData));
        $configTbl = otable::StaticConfig();
        $dbRes = oo::commonOprDb('games')->query("update {$configTbl} set `path`='{$jsonConfigFileName}' where `config`='{$hkey}'");
        $redisRes = oo::commonOprRedis('games')->hSet(okeys::StaticConfig(), $hkey, $jsonConfigFileName);
        return $this->response(0, '操作成功', [$dbRes, $redisRes]);

    }

    //上传图片
    public function uploadImgs($pathName = ''){
        $data['pathName'] = $pathName;

        $dir = PUBLIC_PATH . "/game/image/activity_2/".$pathName ."/" ;  //要获取的目录
        $out = [];
        $i = 1;
        if(is_dir($dir)){
            $opendir = opendir($dir);
            while ($f = readdir($opendir) ){
                if($f != '.' && $f != '..'){
                    $out[] = [
                        'filename'=>$f,
                        'path'=> '/public/game/image/activity_2/' . $pathName . "/" . $f,
                    ];
                    $i += 1;
                }
            }
            closedir($opendir);
        }

        $data['file'] = $out;
        $data['pathName'] = $pathName;

        $this->load->view('config/uploadImgs',$data);
    }

    public function refreshActivityCDN($pathName = ''){
        $dir = "image/activity_2/" . $pathName . "/";

        $ret = $this->common->CdnRefreshDir($dir);
        if($ret === true){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '刷新失败域名：'.implode(',', $ret));
        }

    }
    public function refreshCDN(){
        $dir = $this->input->post();
        if(empty($dir['path']))return $this->response(1, '非法操作');
        $path = ltrim($dir['path'], '/');
        $ret = $this->common->CdnRefreshDir($path);
        if($ret === true){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '刷新失败域名：'.implode(',', $ret));
        }

    }
    public function refreshActivityCDNAll(){
        $ret = $this->common->CdnRefreshAll();
        if($ret === true){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '刷新失败域名：'.implode(',', $ret));
        }
    }


    public function preloadCDNByFile(){
        $input  = $this->input->post();
        if(empty($input['file']))$this->response(__LINE__, '非法操作！');
        $ret = oo::commonOprModel('common')->CdnPushUrl($input['file']);
        $this->response(0, '刷新成功'."-cdn结果：{$ret}");
    }

    //活动图片资源目录配置 修改
    public function actionActiveImgNameConfig(){
        $input  = $this->input->post();
        $tb = otable::ActiveImgNameConfig();

        foreach ($input['name'] as $id => $name){
            $sql = "SELECT count(*) as count FROM {$tb} WHERE id = {$id}";
            $ret = oo::commonOprDb('slavedb')->getOne($sql,1);
            if(empty($ret['count'])){
                $now = time();
                $sql = " INSERT INTO {$tb}(id, name, content, add_time) VALUES('{$id}','{$name}', '', $now) ";
                $rs = oo::commonOprDb('games')->query($sql);
            }else{
                $sql = "UPDATE {$tb} SET name = '{$name}' WHERE id = {$id}";
                $rs = oo::commonOprDb('games')->query($sql);
            }
        }

        foreach($input['content'] as $id => $content){
            $temp = [];
            foreach($content['name'] as $key => $name){
                $temp[$key+1]['id'] = $key+1;
                $temp[$key+1]['name'] = $name;
                $temp[$key+1]['type'] = $content['type'][$key];
                $dir = PUBLIC_PATH . "/game/image/activity_2/" . $content['type'][$key];
                if (!is_dir($dir)) {
                    $old = umask(0);
                    mkdir($dir,  0775 , true);
                    umask($old);
                }
            }
            $temp = json_encode($temp,JSON_UNESCAPED_UNICODE);
            $sql = "UPDATE {$tb} SET content = '{$temp}' WHERE id = {$id}";
            $ret = oo::commonOprDb('games')->query($sql);
        }

        oo::logs()->adminlog($this->router->fetch_method()."--修改活动资源图片：".json_encode($input));

        if($ret){
            oo::commonOprRedis('games')->delete(okeys::ActiveImgNameConfig());
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }
    public function inviteStageRewardConf($db=false){
        $conf =[];
        $key =okeys::InviteStageReward();
        if($db){
            oo::commonOprRedis('games')->delete($key);
        }else{
            $confJson = oo::commonOprRedis('games')->hGetAll($key);
            $conf = funs::getArrFromJsonArr($confJson);
        }
        if(empty($conf)||$db){
            $tb = otable::commonConfig();
            $sql = "SELECT * FROM {$tb} WHERE type='inviteStageReward'";
            $res = oo::commonOprDb('slavedb')->getOne($sql,1);
            if($res['conf']){
                $conf = json_decode($res['conf'],true);
                foreach ($conf as $k=>$v){
                    $arr[$k+1] = json_encode($v);
                }
                oo::commonOprRedis('games')->hMset($key,$arr);
            }else{
                $conf =[];
            }
        }
        array_multisort(array_column($conf,'stage'),SORT_ASC,$conf);
        return $conf;
    }
    //邀请奖励配置 等级区间
    public function getInviteRewardConfig(){
        $data[1] = oo::commonOprModel('config')->getInviteRewardConfig(0,1);
        $data[2] = oo::commonOprModel('config')->getInviteRewardConfig(0,2);
        $tmp = $this->inviteStageRewardConf();
        $arr = [];
        foreach($tmp as $k => $v){
            $arr[$v['stage']] = $v;
        }
        $info['stageReward'] = json_encode($arr);
        $postData =$this->postData;
        $postData['mod'] = 'Config';
        $postData['act'] = 'getAllProps';
        $ret = $this->getDateFromServer($postData);

        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $posts['frombg'] = 1;
        $posts['type'] = 18;
        $posts['lid'] = 1;
        $posts['sid'] = 1;
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $idData = $retData['props'];

        unset($ret[5],$ret[6],$ret[7],$ret[16],$ret[17]);
        unset($ret[10],$ret[11],$ret[12],$ret[18]);
        $info['propsList'] = json_encode($ret);
        $chestSkin  = array_column(oo::commonOprModel('config')->chestSkin(),'name','id');
        $this->load->view('config/getInviteRewardConfig', ['data'=>$data,'info'=>$info, 'idData' => $idData, 'chestSkin' => $chestSkin]);
    }
    public function saveIniteStageReward(){
        $input  = $this->input->post();
        $arrs = $input['reward'];

        $index = 1;
        foreach($arrs as $k=>$v){
            $tmp = $v['prize'];
            if(empty($tmp['propsId'])){
                continue;
            }
            $arrs[$k]['stage'] = $index;
            $index++;
            $prize = [];
            foreach($tmp['propsId'] as $kk=>$vv){
                $t = [
                    'propsId' => $vv,
                    'num' => isset($tmp['num'], $tmp['num'][$kk]) ? $tmp['num'][$kk] : 1,
                ];
                if(isset($tmp['skin']) && !empty($tmp['skin'][$kk])){
                    $t['skin'] = $tmp['skin'][$kk];
                }
                $prize[] = $t;
            }
            $arrs[$k]['prize'] = $prize;
        }

        array_multisort(array_column($arrs,'stage'),SORT_ASC,$arrs);
        $conf = json_encode($arrs);
        $tb = otable::commonConfig();
        $rconf = $this->inviteStageRewardConf(true);
        if($rconf){
            $sql = "UPDATE {$tb} SET conf='".$conf."'  where type='inviteStageReward' ";
        }else{
            $sql = "INSERT INTO {$tb}(name, type, conf) VALUES('邀请阶段奖励','inviteStageReward', '{$conf}')";
        }
        $ret = oo::commonOprDb('games')->query($sql);
        if($ret){
            $this->inviteStageRewardConf(true);
            return $this->response(0, '操作成功',$input['reward']);
        }else{
            return $this->response(1, '操作失败');
        }
    }
    public function getDateFromServer($postData){
        $data =  $this->curl->req($this->_url, $postData);
        return json_decode($data,true);
    }
    //邀请奖励配置 修改
    public function actionInviteRewardConfig(){
        $input  = $this->input->post();
        $sid    = $input['sid'];
        $tb = otable::InviteRewardConfig();
        foreach($input['list'] as $section_id => $row){
            $sql = "UPDATE {$tb} SET level = {$row['level']},spins_guest = {$row['spins_guest']},bind_fb = {$row['bind_fb']},spins_fb = {$row['spins_fb']} WHERE section_id = {$section_id} AND sid = {$sid}";
            $ret = oo::commonOprDb('games')->query($sql);
        }
        if($ret){
            oo::commonOprRedis('games')->delete(okeys::InviteRewardConfig($sid));
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function upLimit(){
        $tb  = otable::UpLimitConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['data'] = json_decode($row['data'],true);
        }
        $this->load->view('config/upLimitConfig', ['list'=>$ret]);
    }

    public function actionUpLimit(){
        $input  = $this->input->post('config');
        $tb     = otable::UpLimitConfig();
        $jsonFile = [];
        foreach($input as $type => $row){
            $json = [];
            foreach ($row['levelId'] as $k=>$lv){
                $json[] = [
                    'levelId' => $lv,
                    'upLimit' => $row['upLimit'][$k],
                ];
            }
            $jsonFile[$type] = $json;
            $json2 = addslashes(json_encode($json,JSON_NUMERIC_CHECK));
            $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET data ='{$json2}' WHERE type='{$type}'");
            if($ret){
                $cacheKey = okeys::UpLimitConfig();
                oo::commonOprRedis('games')->hSet($cacheKey,$type,json_encode($json,32));
            }
        }
        if($ret){
            $configName = "UpLimitConfig";
            $filename   = "UpLimitConfig".time().".json";
            self::SaveJson($jsonFile,$filename);
            oo::commonOprModel('Json')->setStaticConfig($configName,$filename);
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    //分享列表配置
    public function sharePointListConfig($img = "",$country = 'DEFAULT'){
        $tb = otable::sharePointListConfig();
        if(empty($img)){
            $data['list'] = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY id DESC",MYSQLI_ASSOC);
            $data['langList'] = oo::cfg("lang")["lang_upper"];
            $data['langData'] = oo::commonOprModel("language")->getJson('SHARE','');
            foreach($data['list'] as $key => $row){
                foreach($data['langList'] as $lang => $val){
                    $data['list'][$key]['content'][$lang] = $data['langData']['SHARE'][$lang][$row['lang_key']];
                }
            }
            $this->load->view('config/sharePointListConfig', $data);
        }else{
            $data['list'] = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY id",MYSQLI_ASSOC);
            $data['langList'] = ['DEFAULT'=>'默认','DE'=>'德国','FR'=>'法国','US'=>'美国','GB'=>'英国','ES'=>'西班牙','TH'=>'泰国','BR'=>'巴西'];
            $data['href']     = "/filemanager.php?fm_usr=share&fm_pwd=share&userName=".get_cookie('chinesename')."&shareCountry={$country}";
            $data['country']  = $country;
            $langData = [];
            foreach($data['list'] as $key => $row){
                $abTest = json_decode($row['abTest'],true) ?? [];
                $langData[$row['lang_key']] = intval($abTest[$country]);
            }
            $data['langData'] = $langData;
            $this->load->view('config/sharePointListConfigImg', $data);
        }
    }

    public function sharePointListConfigSetAbTest(){
        $country = $this->input->post('country');
        $data = $this->input->post('data');
        $tb   = otable::sharePointListConfig();
        $ret  = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY id DESC",MYSQLI_ASSOC);
        $ret  = array_column($ret,NULL,"lang_key");
        foreach ($data as $key=>$row){
            $atTest = json_decode($ret[$key]['abTest'],true);
            $atTest[$country] = $row;
            $atTest = json_encode($atTest);
            $bool = oo::commonOprDb('games')->query("UPDATE {$tb} SET `abTest` ='{$atTest}' WHERE lang_key='{$key}'");
        }
        if($bool){
            oo::commonOprRedis('games')->delete(okeys::SharePointListConfig());
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    //添加分享配置
    public function addSharePointListConfig(){
        $type = $this->input->post('type');
        $lang_key = $this->input->post('lang_key');
        $content = array_filter($this->input->post('content'));
        $url = $this->input->post('url');
        $img = $this->input->post('img');
        $status = $this->input->post('status');
        $interval_time = $this->input->post('interval_time');
        $props = $this->input->post('props');
        $id = $this->input->post('id');
        if(empty($content)){
            return $this->response(1, '操作失败');
        }
        $contentTemp = json_encode($content,JSON_UNESCAPED_UNICODE);
        $tb = otable::sharePointListConfig();
        if($id){
            $sql = "UPDATE {$tb} SET lang_key ='{$lang_key}',img = '{$img}' WHERE id = {$id}";
        }else{
            $sql = "INSERT INTO {$tb} (type,lang_key,img,url,`status`,interval_time) VALUES('{$type}','{$lang_key}','{$img}','',0,0)";
        }
        $ret = oo::commonOprDb('games')->query($sql);
        if($ret){
            $langList = oo::cfg("lang")["lang_upper"];
            $retList =[];
            foreach($langList as $lang => $row){
                $langData = oo::commonOprModel("language")->getJson('SHARE',$lang);
                $langData['SHARE'][$lang_key]['title'] = $content[$lang]['title'];
                $langData['SHARE'][$lang_key]['desc'] = $content[$lang]['content'];
                $langData['SHARE'][$lang_key]['img'] = $img;
                $rs = oo::commonOprModel("language")->saveJson('SHARE',$lang,$langData['SHARE']);
                $retList[$lang] = $rs;
            }
            return $this->response(0, '操作成功',$retList);
        }else{
            return $this->response(1, '操作失败');
        }
    }

    //删除分享配置
    public function delSharePointListConfig(){
        $id = $this->input->post('id');
        if(empty($id)){
            return $this->response(1, '参数错误');
        }
        $tb = otable::sharePointListConfig();
        $result = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id = {$id} limit 1",MYSQLI_ASSOC);

        $sql = "DELETE FROM {$tb} WHERE id = {$id}";
        $ret = oo::commonOprDb('games')->query($sql);
        if($ret){
            $lang_key = $result['lang_key'];
            $langList = ['LDE'=>'德国','LEN'=>'英语','LES'=>'西班牙','LFR'=>'法语','LID'=>'印度尼西亚','LNO'=>'挪威','LPT'=>'葡萄牙','LTH'=>'泰国','LTW'=>'中国台湾','LVI'=>'越南','LZH'=>'中国'];
            foreach($langList as $lang => $row){
                $langData = oo::commonOprModel("language")->getJson('SHARE',$lang);
                unset($langData['SHARE'][$lang_key]);
                $rs = oo::commonOprModel("language")->saveJson('SHARE',$lang,$langData['SHARE']);
            }
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function friendGiftCoins(){
        $tb  = otable::FriendGiftCoinsConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $this->load->view('config/friendGiftConfig', ['list'=>$ret]);
    }

    /**
     * 好友数量进度奖励配置
     */
    public function friendProgressConfig() {
        $tb  = otable::friendProgressConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} Order BY num ASC", MYSQLI_ASSOC);
        foreach($ret as $k => $v){
            $ret[$k]['reward'] = json_decode($v['reward'], true);
        }
        //$idData = [
        //    1  => ['type'=>3, 'id'  =>1,'name' =>'木质宝箱', 'msg' =>'木质宝箱','max'=>5],
        //    2  => ['type'=>3, 'id'  =>2,'name' =>'白银宝箱', 'msg' =>'白银宝箱','max'=>5],
        //    3  => ['type'=>3, 'id'  =>3,'name' =>'黄金宝箱', 'msg' =>'黄金宝箱','max'=>5],
        //    4  => ['type'=>3, 'id'  =>4,'name' =>'魔幻宝箱', 'msg' =>'魔幻宝箱','max'=>5],
        //];

        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $posts['frombg'] = 1;
        $posts['type'] = 18;
        $posts['lid'] = 1;
        $posts['sid'] = 1;
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $idData = $retData['props'];


        //召回配置字段太少只存redis
        $tmp = oo::commonOprRedis('games')->get(okeys::callbackConfig());
        if(!empty($tmp)){
            $callback = (array)json_decode($tmp, true);
        }
        //没有数据，先给个默认值
        if(empty($callback)){
            $callback = ['level' => 2, 'reward' => ['props' => [['propsId' => 15, 'num' => 30], ['propsId' => 2, 'num' => 1]]]];
        }

        $this->load->view('config/friendProgressConfig', ['list'=>$ret, 'idData' => $idData, 'callback' => $callback]);
    }

    /**
     * 保存好友数量进度奖励配置
     */
    public function saveFriendProgress() {
        $config = $this->input->post('reward');
        if(empty($config)){
            return $this->response(1, '操作失败,提交数据为空');
        }
        $tb  = otable::friendProgressConfig();
        $sql = "replace into {$tb} (id, num, reward) VALUES ";
        $data = [];
        foreach($config as $val){
            $reward = [];
            foreach($val['reward'] as $k => $v){
                if($k == 'coins' && !empty($v['bet'])){
                    $reward['coins'] = ['coins' => $v['coins'], 'bet' => $v['bet']];
                }
                if($k != 'props'){
                    $reward[$k] = $v;
                    continue;
                }
                if(empty($reward['props'])){
                    $reward['props'] = [];
                }
                foreach($v['propsId'] as $key => $pid){
                    if(empty($v['num'][$key])){
                        continue;
                    }
                    $reward['props'][] = ['propsId' => $pid, 'num' => $v['num'][$key]];
                }
            }
            if(empty($reward['coins']['bet'])){
                unset($reward['coins']);
            }
            $val['reward'] = $reward;
            $data[] = $val;
            $reward = json_encode($reward);
            $sql .= "({$val['id']}, {$val['num']}, '{$reward}'),";
        }
        $sql = rtrim($sql, ',');
        $ret = oo::commonOprDb('games')->query($sql);
        if($ret){
            oo::commonOprRedis('games')->set(okeys::friendProgressRewardConfig(), json_encode($data));
        }

        $tmp = $this->input->post('callback');
        if(!empty($tmp)){
            $callback = ['level' => $tmp['level']];
            $reward = [];
            foreach($tmp['reward'] as $k => $v){
                if($k == 'coins' && !empty($v['bet'])){
                    $reward['coins'] = ['coins' => $v['coins'], 'bet' => $v['bet']];
                }
                if($k != 'props'){
                    $reward[$k] = $v;
                    continue;
                }
                if(empty($reward['props'])){
                    $reward['props'] = [];
                }
                foreach($v['propsId'] as $key => $pid){
                    if(empty($v['num'][$key])){
                        continue;
                    }
                    $reward['props'][] = ['propsId' => $pid, 'num' => $v['num'][$key]];
                }
            }
            if(empty($reward['coins']['bet'])){
                unset($reward['coins']);
            }
            $callback['reward'] = $reward;
            oo::commonOprRedis('games')->set(okeys::callbackConfig(), json_encode($callback));
        }

        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function actionFriendGiftCoins(){
        $config = $this->input->post('config');
        $tb  = otable::FriendGiftCoinsConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $levelIdArr = array_column($ret,'levelId');
        $newLevelId = $config['levelId'];
        foreach ($config['levelId'] as $key=>$row){
            $coins = $config['coins'][$key];
            if(!in_array($row,$levelIdArr)){
                $sql = "INSERT INTO {$tb} (levelId,coins) VALUES('{$row}','{$coins}')";
            }else{
                $sql = "UPDATE {$tb} SET coins = '{$coins}' WHERE levelId = {$row}";
            }
            $ret = oo::commonOprDb('games')->query($sql);
        }
        foreach ($levelIdArr as $row){
            if(!in_array($row,$newLevelId)){
                $ret = oo::commonOprDb('games')->query("DELETE FROM {$tb} WHERE levelId={$row}");
            }
        }
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function chest(){
        $tb  = otable::ChestConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['reward'] = json_decode($row['reward'],true);
            $ret[$key]['reward'] = array_column($ret[$key]['reward'],NULL,'propsId');
        }
        $data['list'] = $ret;
        $this->load->view('config/propsConfig', $data);
    }

    public function actionChest(){
        $config = array_values($this->input->post('good'));
        $tb  = otable::ChestConfig();
        foreach ($config as $row){
            $reward   = [];
            $coins    = [];
            $spins    = [];
            $exp      = [];
            $reward[] = ['propsId'=>17,'num'=>$row['card']];
            $reward[] = ['propsId'=>18,'num'=>$row['joker']];
            foreach ($row['coins']['num'] as $k=>$r){
                $coins[] = ['num'=>$r,'v'=>$row['coins']['v'][$k]];
            }
            $reward[] = ['propsId'=>14,'pro'=>$coins];
            foreach ($row['spins']['num'] as $k=>$r){
                $spins[] = ['num'=>$r,'v'=>$row['spins']['v'][$k]];
            }
            $reward[] = ['propsId'=>15,'pro'=>$spins];
            foreach ($row['exp']['num'] as $k=>$r){
                $exp[] = ['num'=>$r,'v'=>$row['exp']['v'][$k]];
            }
            $reward[] = ['propsId'=>8,'pro'=>$exp];
            $reward = addslashes(json_encode($reward,JSON_NUMERIC_CHECK));
            $sql = "UPDATE {$tb} SET `name`='{$row['name']}',`reward`='{$reward}' WHERE propsId ='{$row['propsId']}'";
            $ret = oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->delete(okeys::ChestConfig($row['propsId']));
        }
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function userGroupList($cid = 1){
        oo::commonOprRedis('games')->delete(okeys::UserGroupConfig(2));
        $config = oo::commonOprModel('config')->getUserGroupConfig2();
        array_multisort(array_column($config,'sort'),SORT_ASC,$config);

        $configSSGroupUpdates = [];
        if($cid == 5){
            $configSSGroupShow = oo::commonOprRedis('statistics')->hGetAll(okeys::configSSGroupShow());
            if(empty($configSSGroupShow)){
                $configSSGroupShow = [];
            }
            $configSSGroupUpdates = oo::commonOprRedis('statistics')->hGetAll(okeys::configSSGroupUpdate());
            if(empty($configSSGroupUpdates)){
                $configSSGroupUpdates = [];
            }
        }else{
            $configSSGroupShow = [];
        }
        foreach ($config as $key=>$row){
            if($cid != $row['cid'] || ( $row['sort'] < 0 )){
                unset($config[$key]);
                continue;
            }

            if($cid == 5){
                if(strpos($config[$key]['name'],'默认分组') === false){
                   $config[$key]['groupId'] = $config[$key]['id'];
                }
                if(in_array($row['id'],$configSSGroupShow)){
                    $config[$key]['showStatus'] = 0;
                }else{
                    $config[$key]['showStatus'] = 1;
                }
                $config[$key]['updateStatus'] = 0;
                if(in_array($row['id'],$configSSGroupUpdates)){
                    $config[$key]['updateStatus'] = 1;
                }
            }
            $config[$key]['count'] = $row['cid']!=5?max(intval(oo::commonOprRedis('games')->hGet(okeys::UserGroupTotal(),$row['id'])),0):$row['count'];
        }
        $nameArr = [1=>"广告组", 2=>"RFM模型", 3=>"大R社群", 4=>"签到组", 5=>"数数分组"];
        $name    = $nameArr[$cid];
        $this->load->view('config/userGrouplist', ['list'=>$config,"cid"=>$cid,"name"=>$name,"nameArr"=>$nameArr]);
    }

    //显示隐藏
    public function userGroupShow($id = 0,$status = 1){
        if($id == -1){
            $group = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');//数数分组
            $setArr = [];
            foreach($group as $key => $row){
                $setArr[$key] = $key;
            }
            $ret = oo::commonOprRedis('statistics')->hMset(okeys::configSSGroupShow(),$setArr);
        }else{
            if($status){
                //显示 从缓存删除
                $ret = oo::commonOprRedis('statistics')->hDel(okeys::configSSGroupShow(),$id);
            }else{
                //隐藏 加入缓存
                $ret = oo::commonOprRedis('statistics')->hSet(okeys::configSSGroupShow(),$id,$id);
            }
        }
        if($ret){
            return $this->response(0, '操作成功',['status' => $status]);
        }else{
            return $this->response(1, $id.'操作失败'.$ret);
        }
    }
    public function userGroupUpdate($id = 0,$status = 1){
        $redisKey = okeys::configSSGroupUpdate();
        if($id == -1){
            $group = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');//数数分组
            $setArr = [];
            foreach($group as $key => $row){
                $setArr[$key] = $key;
            }
            $ret = oo::commonOprRedis('statistics')->hMset($redisKey, $setArr);
        }else{
            if($status < 1){
                //显示 从缓存删除
                $ret = oo::commonOprRedis('statistics')->hDel($redisKey, $id);
            }else{
                //隐藏 加入缓存
                $ret = oo::commonOprRedis('statistics')->hSet($redisKey, $id, $id);
            }
        }
        if($ret){
            return $this->response(0, '操作成功',['status' => $status]);
        }else{
            return $this->response(1, $id.' 操作失败'.$ret);
        }
    }

    /**
     * Notes:获取数数分组列表
     * User: wsc
     * Time: 2021/5/29 17:22
     * @return json
     */
    public function getSSGroupData(){
       $data = oo::commonOprModel('SSdata')->getGroupList();
       if(!empty($data)){
           $existGroups = [];
           foreach ($data as $k=>$v){
               $existGroups[] = $v['id'];
               $datas[$k] =[
                   'cid'=>5,
                   'groupId'=>$v['id'],
                   'name'=>$v['clusterName'],
                   'remark'=>$v['displayName'],
                   'update'=>1,
                   'count'=>$v['usersNum']
               ];
           }
           $validNames = $this->changeUserGroupList($datas);


           # 当前系统所有数数分组
           $tb = otable::UserGroupConfig(2);
           $localGroups = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} where cid=5 and sort >= 0",MYSQLI_ASSOC);
           # 后台存在，数数不存在的分组
           $delGroups = [];
           foreach ($localGroups as $group){
               if(!empty($group['groupId']) && !in_array($group['groupId'], $existGroups)){
                   $delGroups[] = $group['id'];
               }
           }

           oo::logs()->debug3(['后台数数分组数据'=>$localGroups,'数数最新分组数据'=>$datas,'需要删除的分组数据'=>$delGroups],"refreshShushuGroups.log");
           if(!empty($delGroups)){
               $delIdsStr = implode(',', $delGroups);

               # 将数数那边删除的分数在这边废弃
               oo::commonOprDb('games')->query("update  {$tb} set sort=-1 where cid=5 and id in ({$delIdsStr})",MYSQLI_ASSOC);
               $updateKey = okeys::configSSGroupUpdate();
               $hideKey = okeys::configSSGroupShow();
               foreach ($delGroups as $id){
                   oo::commonOprRedis('statistics')->hSet($hideKey,$id,$id);   # 显示状态为隐藏
                   oo::commonOprRedis('statistics')->hDel($updateKey, $id);    # 更新状态为不更新
               }
           }

           return $this->response(0, '操作成功', $validNames);
       }else{
           return $this->response(1, '操作失败');
       }

    }

    /**
     * Notes:更新用户分组列表
     * User: wsc
     * Time: 2021/5/29 17:22
     * @param $datas
     * @return array|bool
     */
    public function changeUserGroupList($datas){
        $tb = otable::UserGroupConfig(2);
        $validNames = [];
        foreach ($datas as $k=>$v){
            if(!$this->checkGroupName($v['name']))continue;
            $ret = oo::commonOprDb('games')->getOne("SELECT * FROM {$tb} WHERE (groupId={$v["groupId"]} AND cid={$v["cid"]})  limit 1",MYSQLI_ASSOC);
            if(!empty($ret)){
                $w = "cid={$v["cid"]} AND groupId={$v["groupId"]} AND `name`='{$v['name']}'";
                $sql = funs::db_updateSQL($tb,$v,$w);
            }else{
                $sql = funs::db_insertSQL($tb,$v);
            }
            $ret = $sql?oo::commonOprDb('games')->query($sql):false;
            $validNames[] = $v['name'];
        }
        oo::commonOprRedis('games')->delete(okeys::UserGroupConfig(2));
        $config = oo::commonOprModel('config')->getUserGroupConfig2();
        return $validNames;
    }
    public function checkGroupName($groupName){
        if(empty($groupName))return false;
        if(strpos($groupName, 'cohort_') === 0)return false;
        preg_match("/^u\d+\_/",$groupName, $matchs);
        if(!empty($matchs))return false;
        return true;
    }

    public function userGroup2($cid,$id = 0){
        $condition = [0=>'平台', 1=>'设备', 2=>'VIP', 3=>'首冲', 4=>'VIP积分', 5=>'等级', 6=>'活跃天数(天)', 7=>'累计游戏时长(分)', 8=>'注册时长(天)', 9=>'好友数量', 10=>'好友排行', 11=>'国家排行', 12=>'世界排行', 13=>'国家分组', 14=>'Adjust来源分组', 15=>'RFM', 16=>'渠道', 17=>'VIP等级', 18=>'充值金额', 19=>'注册区间金额', 20=>'时间区间金额', 21=>'最近登录天数'];
        $between   = [4=>'point', 5=>'levelId', 6=>'active', 7=>'onlineTime', 8=>'regTime', 9=>'friendNum', 10=>'friendRank', 11=>'countryRank', 12=>'worldRank', 18=>'payNum'];
        $country   = oo::commonOprModel('config')->country;
        $adjustGroup = ['UAC2.0'=>'UAC2.0用户', 'UAC2.5'=>'UAC2.5用户', 'AEO'=>'AEO用户', 'VO'=>'VO用户', 'Recall'=>'Recall用户', 'Not'=>'未归类用户'];
        $vipConfig   = json_decode(oo::commonOprModel('common')->CurlApi([
            'mod'=>'Config',
            'act'=>'getVipConfig',
            'vipVersion'=>'155',
        ]),true);
        $vipConfig = array_column($vipConfig,'lv');
        if($id){
            $config = oo::commonOprModel('config')->getUserGroupConfig2($id);
        }else{
            $config = [];
        }
        $this->load->view('config/userGroup2', [
            'cid'=>$cid,
            'id'=>$id,
            'info'=>$config,
            'condition'=>$condition,
            'between'=>$between,
            'country'=>$country,
            'adjustGroup'=>$adjustGroup,
            'vipLv'=>$vipConfig
        ]);
    }
    public function actionUserGroup2(){
        $input  = $this->input->post();
        $id     = $input['id'];
        $cid    = $input['cid'];
        $groupId= $input['groupId'];
        $name   = $input['name'];
        $remark = $input['remark'];
        $update = $input['update'];
        $adTotal= $input['adTotal'];
        $config = $input['config'];
        $sort = $input['sort'];
        $s = ['point', 'levelId', 'active', 'onlineTime', 'regTime', 'friendNum', 'friendRank', 'countryRank', 'worldRank', 'payNum'];
        foreach ($config as $key=>$row){
            foreach ($row as $k=>$v){
                if($v != 0 && in_array($k,$s)){
                    $config[$key][$k] = implode($row[$k.'s'],",");
                    unset($config[$key][$k.'s']);
                    break;
                }else if($v == 0 && in_array($k,$s)){
                    unset($config[$key][$k.'s']);
                }
            }
        }
        foreach ($config as $key=>$row){

            if($row['condition'] == 15){
                $config[$key]['rfm'] = [
                    'r'=>$row['r'],
                    'f'=>$row['f'],
                    'm'=>$row['m'],
                ];
                unset($config[$key]['r']);
                unset($config[$key]['f']);
                unset($config[$key]['m']);
            }
            if($row['condition'] == 19){
                $config[$key]['regPay'] = [
                    'time'=>$row['regPayTime'],
                    'num' =>$row['regPayNum'],
                ];
                unset($config[$key]['regPayTime']);
                unset($config[$key]['regPayNum']);
            }
            if($row['condition'] == 20){
                $config[$key]['timePay'] = [
                    'time'=>[
                        strtotime($row['tPayTime'][0]),
                        strtotime($row['tPayTime'][1]),
                    ],
                    'num'=>$row['tPayNum'],
                ];
                unset($config[$key]['tPayTime']);
                unset($config[$key]['tPayNum']);
            }
            if($row['condition'] == 21){
                $config[$key]['loginNum'] = [
                    $row['rLoginNum'][0],
                    $row['rLoginNum'][1],
                ];
                unset($config[$key]['rLoginNum']);
            }
        }
        $arr = ['countrySet', 'adjustGroup', 'vipLv'];
        foreach ($config as $key=>$row){
            foreach ($row as $k=>$v){
                if($v != 0 && in_array($k,$arr)){
                    $config[$key][$k] = $row[$k.'Arr'];
                    unset($config[$key][$k.'Arr']);
                    break;
                }else if($v == 0 && in_array($k,$arr)){
                    $config[$key][$k] = [];
                    unset($config[$key][$k.'Arr']);
                }
            }
        }
        $config = array_values($config);
        $condition = addslashes(json_encode($config));
        $tb = otable::UserGroupConfig(2);
        $ret = oo::commonOprDb('gamse')->getOne("SELECT * FROM {$tb} WHERE (groupId='{$groupId}' OR name='{$name}') AND cid='{$cid}' limit 1",MYSQLI_ASSOC);
        if(empty($id) && !empty($ret)){
            return $this->response(1, '分群ID或名称已存在');
        }
        if(!empty($id)){
            $sql = "UPDATE {$tb} SET `cid`='{$cid}',`name`='{$name}',`groupId`='{$groupId}',`remark`='{$remark}',`update`='{$update}',`adTotal`='{$adTotal}',`condition`='{$condition}',`sort`='{$sort}' WHERE id ='{$id}'";
        }else{
            $sql = "INSERT INTO {$tb} (`cid`,`groupId`,`name`,`remark`,`update`,`adTotal`,`condition`,`sort`) VALUES ('{$cid}','{$groupId}','{$name}', '{$remark}', '{$update}','{$adTotal}','{$condition}','{$sort}')";
        }
        $ret = oo::commonOprDb('games')->query($sql);
        $ret && oo::commonOprRedis('games')->delete(okeys::UserGroupConfig(2));
        if(!empty($id) && $ret['sort'] != $sort){
            $tb = otable::Polymerization(2);
            $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            foreach ($ret as $row){
                $groupPro = json_decode($row['group_pro'],true);
                foreach ($groupPro as $k=>$p){
                    if($p['id'] == $id){
                        $groupPro[$k]['sort'] = $sort;
                        break;
                    }
                }
                array_multisort(array_column($groupPro,'sort'),SORT_ASC,$groupPro);
                $groupPro = addslashes(json_encode($groupPro));
                $sql = "UPDATE {$tb} SET group_pro='{$groupPro}' WHERE id='{$row['id']}' LIMIT 1";
                oo::commonOprDb('games')->query($sql) && oo::commonOprRedis('games')->delete(okeys::Polymerization(3));
            }
            oo::commonOprRedis('games')->delete(okeys::Polymerization(3));
        }

        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function delUserGroup(){
        $id = $this->input->post('id');
        $tb = otable::UserGroupConfig(2);
        $ret = oo::commonOprDb('games')->query("DELETE FROM {$tb} WHERE id={$id} LIMIT 1");
        if($ret){
            oo::commonOprRedis('games')->delete(okeys::UserGroupConfig(2));
            oo::commonOprRedis('games')->sAdd(okeys::DelUserGroupAction(),$id);
            $tb = otable::Polymerization(2);
            $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            foreach ($ret as $row){
                $group_pro = json_decode($row['group_pro'],true);
                $action = false;
                foreach ($group_pro as $k=>$g){
                    if($g['id'] == $id){
                        unset($group_pro[$k]);
                        $action = true;
                    }
                }
                if($action){
                    sort($group_pro);
                    $group_pro = stripslashes(json_encode($group_pro));
                    $sql = "UPDATE {$tb} SET group_pro='{$group_pro}' WHERE id='{$row['id']}' LIMIT 1";
                    oo::commonOprDb('games')->query($sql) && oo::commonOprRedis('games')->delete(okeys::Polymerization(3));
                }
            }
            oo::commonOprRedis('games')->delete(okeys::UserGroupActionByUid($id));
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function updateUserGroupByUser(){
        $id = $this->input->post('id');
        $tb  = otable::UserDynamicsData();
        $sql = "SELECT uid FROM {$tb} WHERE groupId2 LIKE '%{$id}%'";
        $ret = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
        foreach ($ret as $row){
            oo::commonOprRedis('games')->sAdd(okeys::UserGroupActionByUid($id),$row['uid']);
        }
        oo::commonOprRedis('games')->sAdd(okeys::UserGroupActionGroupId(),$id);
        return $this->response(0, '操作成功');
    }

    public function coinDozer(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $data = json_decode(oo::commonOprModel('config')->getSysCon('CoinDozer',"config"),true);
        $this->load->view('config/coinDozer', ['info'=>$data,'props'=>$retData['props']]);
    }

    public function actionCoinDozer($type){
        $input = $this->input->post();
        $data = json_decode(oo::commonOprModel('config')->getSysCon('CoinDozer',"config"),true);
        if($type != "gameCfg"){
            $input[$type] = array_values($input[$type]);
        }
        $data[$type] = $input[$type];
        oo::commonOprModel('config')->setSysCon('CoinDozer','config',json_encode($data,JSON_NUMERIC_CHECK));
        return $this->response(0, '操作成功');
    }

    public function refreshLuckyDrawConf(){
        oo::commonOprRedis('games')->delete([okeys::LuckyProConfig(),okeys::LuckyConfig(),okeys::LuckyProgressConfig()]);
        return $this->response(0, '操作成功');
    }

    public function aihelp(){
        $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();
            $start  = $input['start'];
            $length = $input['length'];
            $tb   = otable::AIHelp();
            $ret  = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY `created_at` DESC LIMIT {$start}, {$length}", MYSQLI_ASSOC);
            $ret2 = oo::commonOprDb('slavedb')->getOne("SELECT count(*) as total FROM {$tb}", 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']);
                }
                $data['data'] = $ret;
                $data['recordsTotal']    = $ret2['total'];
                $data['recordsFiltered'] = $ret2['total'];
            }else {
                $data = $this->withNodata();
            }
            die(json_encode($data));
        }
        $this->load->view('config/aihelp',$data);
    }

    public function actionAIHelp(){
        $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, '奖励空');
        }
        $name       = $input['name'];
        $created_at = time();
        $remark = $input['remark'];
        $reward = json_encode($reward,JSON_NUMERIC_CHECK);
        $tb  = otable::AIHelp();
        oo::commonOprDb('games')->query("INSERT INTO {$tb}(`name`,reward,created_at,remark) VALUES('{$name}','{$reward}','{$created_at}','{$remark}')");
        return $this->response(0, '操作成功');
    }

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

    /**
     * 触发活动配置
     * @param $act
     * Created by: Owen
     * Created on: 2020/12/18 12:20
     */
    public function activityLimit(){
        $data['crazyBet'] = json_decode(oo::commonOprModel('config')->getSysCon("activity","crazyBet"),true) ?? [];
        $this->load->view('config/activityLimit',$data);
    }

    public function actionActivityLimit(){
        $input = $this->input->post();
        $crazyBet = $input['crazyBet'];
        oo::commonOprModel('config')->setSysCon("activity","crazyBet",json_encode($crazyBet,JSON_NUMERIC_CHECK));
        return $this->response(0, '操作成功');
    }

    /**
     * ios兑换码开关设置
     */
    public function iosOpenOline() {
        $data=[
            'openOline'    => oo::commonOprRedis('games')->get(okeys::openOline()),
            'openOlineVer' => oo::commonOprRedis('games')->get(okeys::openOlineVersion()),
            'isOpenMaple'  => oo::commonOprRedis('games')->get(okeys::isOpenMaple()),
        ];

        $closeSetting = oo::commonOprRedis('games')->hGetAll(okeys::iosCloseSetting());
        foreach ($closeSetting as $type => $setting){
            $closeSetting[$type] = json_decode($setting, true);
        }
        $data['closeSetting'] = $closeSetting;
        $data['types'] = [
            'closeClub' => 'IOS版本公会开关配置'
        ];
        $this->load->view('config/iosOpenOline',$data);
    }

    /**
     * 设置ios兑换开关
     */
    public function actionIosOpenOline() {
        $input = $this->input->post();
        if(isset($input['openOlineVer'])){
            oo::commonOprRedis('games')->set(okeys::openOlineVersion(), $input['openOlineVer']);
        }
        if(isset($input['openOline'])){
            oo::commonOprRedis('games')->set(okeys::openOline(), (int)$input['openOline']);
        }

        if(isset($input['isOpenMaple'])){
            oo::commonOprRedis('games')->set(okeys::isOpenMaple(), (int)$input['isOpenMaple']);
        }
        return $this->response(0, '操作成功');
    }

    /**
     * 设置ios 过审开关
     */
    public function saveIosCloseSetting() {
        $input = $this->input->post();
        if(empty($input['type']) || empty($input[$input['type']]))$this->response(__LINE__, '非法操作', $input);
        $key = okeys::iosCloseSetting();
        $setting = is_scalar($input[$input['type']]) ? $input[$input['type']] : json_encode($input[$input['type']], 32);
        oo::commonOprRedis('games')->hset($key, $input['type'], $setting);
        return $this->response(0, '操作成功', $input);
    }

    public function userGroupSignIn($id = 0){
        $data['id'] = $id;
        if($id){
            $config = oo::commonOprModel('config')->getUserGroupConfig2($id)['signIn'];
            if(empty($config)){
                $config = json_decode(oo::commonOprModel('config')->getSysCon("signIn","default"),true);
            }
        }else{
            $config = json_decode(oo::commonOprModel('config')->getSysCon("signIn","default"),true) ?? [];
        }
        $data['daily'][1] = $config;
        $data['props']    = oo::commonOprModel('config')->getPropsConfig();
        $this->load->view('config/userGroupSignIn', $data);
    }

    public function actionUserGroupSignIn(){
        $postData = $this->input->post();
        $id   = $postData['id'];
        $data = [];
        foreach ($postData['coins'] as $key=>$row){
            $data[$key] = ['id' => $key, 'coins' => ['coins' => $row, 'bet' => $postData['bet'][$key],], 'spins' => $postData['spins'][$key]];
            $props = [];
            if(!empty($postData['props'][$key])){
                foreach ($postData['props'][$key]['propsId'] as $propsKey=>$propsId){
                    $props[] = ['propsId' => $propsId, 'num'     => $postData['props'][$key]['num'][$propsKey],];
                }
            }
            $data[$key]['props'] = $props;
        }
        if($id){
            $tb = otable::UserGroupConfig(2);
            $signIn = addslashes(json_encode($data,JSON_NUMERIC_CHECK));
            oo::commonOprDb('games')->query("UPDATE {$tb} SET `signIn`='{$signIn}' WHERE id ='{$id}'") && oo::commonOprRedis('games')->delete(okeys::UserGroupConfig(2));
        }else{
            oo::commonOprModel('config')->setSysCon('signIn','default',json_encode($data,JSON_NUMERIC_CHECK));
        }
        return $this->response(0, '操作成功');
    }

    public function delUserGroupSignIn(){
        $id = $this->input->post('id');
        $tb = otable::UserGroupConfig(2);
        oo::commonOprDb('games')->query("UPDATE {$tb} SET `signIn`='' WHERE id ='{$id}'") && oo::commonOprRedis('games')->delete(okeys::UserGroupConfig(2));
        return $this->response(0, '操作成功');
    }

    const CARD_NUM_COEFFICIENT = "CARD_NUM_COEFFICIENT";

    public function cardCoefficient(){
        $tb = otable::CardCoefficient();
        $activate = oo::commonOprDb('slavedb')->getAll("SELECT num,coefficient FROM {$tb} Where type = 2");
        foreach ($activate as &$row) {
            $row['coefficient'] = explode(",", $row['coefficient']);
        }

        $num = oo::commonOprModel('config')->getCommonConf(self::CARD_NUM_COEFFICIENT);
        $this->load->view('config/cardCoefficient', ['num' => $num, 'activate' => $activate]);
    }

    public function actionCardCoefficient()
    {
        $postData = $this->input->post();

        $tb = otable::CardCoefficient();
        foreach ($postData['activate'] as $key => $row) {
            $temp = implode(',', $row);
            oo::commonOprDb('games')->query("UPDATE {$tb} SET `coefficient`='{$temp}' WHERE num ='{$key}' AND type='2'");
        }
        oo::commonOprRedis('games')->delete(okeys::CardCoefficient());

        oo::commonOprModel('config')->saveCommonConf(self::CARD_NUM_COEFFICIENT, $postData['num'], "卡片数量修正系数");
        oo::commonOprRedis('games')->set(self::CARD_NUM_COEFFICIENT, json_encode($postData['num'], JSON_NUMERIC_CHECK));
        return $this->response(0, '操作成功');
    }

    public function chestSkin(){
        $tb  = otable::ChestSkinConfig(2);
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY id",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['reward'] = json_decode($row['reward'],true);
            $ret[$key]['reward'] = array_column($ret[$key]['reward'],NULL,'propsId');
        }
        $data['list'] = $ret;
        $this->load->view('config/chestSkin', $data);
    }
    public function actionChestSkin(){
        $config = array_values($this->input->post('good'));
        $tb = otable::ChestSkinConfig(2);
        foreach ($config as $row){
            $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$row['id']}",MYSQLI_ASSOC);
            $reward = json_decode($ret['reward'],true);
            $reward = array_column($reward,null,"propsId");
            $coins    = [];
            $reward[17]['num'] = $row['card'];
            $reward[18]['num'] = $row['joker'];
            $reward[9] = ["propsId"=>9,"num"=>$row['food']];
            foreach ($row['coins']['num'] as $k=>$r){
                $coins[] = ['num'=>$r,'v'=>$row['coins']['v'][$k]];
            }
//            $reward[14]['pro'] = $coins;
            $reward = array_values($reward);
            $reward = addslashes(json_encode($reward,JSON_NUMERIC_CHECK));
            $sql = "UPDATE {$tb} SET `name`='{$row['name']}',`reward`='{$reward}',`skinResourceId`='{$row['skinResourceId']}' WHERE id ='{$row['id']}'";
            $ret = oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->delete(okeys::ChestSkinConfig($row['id']));
            oo::commonOprRedis('games')->delete(okeys::NewChestSkinConfig($row['id']));
        }
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }
    public function actionAddChestSkin(){
        $name = $this->input->post('name');
        $tb   = otable::ChestSkinConfig(2);
        $ret  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id=1",MYSQLI_ASSOC);
        $skinResourceId = $this->input->post('skinResourceId');
        $reward  = addslashes($ret['reward']);
        $starPro = addslashes($ret['starPro']);
        $ret  = oo::commonOprDb('games')->query("INSERT INTO {$tb} SET name='{$name}',reward='{$reward}',starPro='{$starPro}',skinResourceId='{$skinResourceId}'");
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function chestWeight($from,$type,$id){
        $data["from"] = $from;
        $data["type"] = $type;
        $data["id"]   = $id;
        if($from == 1){
            $tb = otable::StarExchange(2);
            $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE propsId={$id}",MYSQLI_ASSOC);
            $value = json_decode($ret[$type],true);
        }else{
            if($from == 2){
                $tb = otable::ChestSkinConfig(2);
                $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id}",MYSQLI_ASSOC);
            }else if($from == 3){
                $tb = otable::ChestConfig(2);
                $ret= oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE propsId={$id}",MYSQLI_ASSOC);
            }
            $reward = json_decode($ret['reward'],true);
            $reward = array_column($reward,null,"propsId");
                $value = $reward[$type]['pro'];
//            if($type == "spinsNum"){
//                $value = $reward[15]['pro'];
//            }else if($type == "petExp"){
//                $value = $reward[8]['pro'];
//            }else{
//                $value = $reward[$type]['pro'];
//            }
        }
        $title[] = "等級";
        $i = 1;
        foreach (array_column($value[0]["weight"],"v") as $v){
            $title[] = "权重({$v})";
            $i++;
        }
        $data["title"] = $title;
        $data["list"] = $value;
        $this->load->view('config/chestWeight',$data);
    }

    public function lang(){
        $tb = otable::languageConfig(2);
        $data["list"] = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY lang",MYSQLI_ASSOC);
        $tmp = [];
        foreach ($data["list"] as $key=>$row){
            $tmp[$row['key']][$row['lang']] = $row['content'];
            if($row['lang'] != "LZH"){
                unset($data["list"][$key]);
            }
        }
        $lang = [];
        foreach ($this->_langList as $key=>$row){
            $key = $key == 'vn'?'vi':$key;
            $lang["L".strtoupper($key)] = $row;
        }
        $data['lang'] = $lang;
        $data['temp'] = $tmp;
        $this->load->view('config/lang',$data);
    }

    public function addLang(){
        $key = $this->input->post('key');
        if(empty($key)){
            return $this->response(-1, '语言键不能为空');
        }
        $config = $this->input->post('conf');
        $tb     = otable::languageConfig(2);
        foreach ($config as $lang=>$content){
            $tempContent = addslashes($content);
            oo::commonOprDb('games')->query("REPLACE INTO {$tb} SET lang='{$lang}',`key`='{$key}',content='{$tempContent}'");
        }
        oo::commonOprModel("language")->setLangJson();
        return $this->response(0, '操作成功');
    }

    public function lang2($lang){
        $tb = otable::languageConfig(2);
        $list = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE `lang`='{$lang}'",MYSQLI_ASSOC);
        $data = [];
        foreach ($list as $row){
            $keyArr = explode('.',$row['key']);
            $this->langRecursion($data,$keyArr,0,$row['content']);
        }
        $data = array_merge(["test"=>1],$data);
        echo json_encode($data);
    }

    public function langRecursion(&$data,$keyArr,$deep,$content){
        if(count($keyArr)>=1){
            if(count($keyArr) - 1 == $deep){
                $data[$keyArr[$deep]] = $content;
            }else{
                $this->langRecursion($data[$keyArr[$deep]],$keyArr,$deep+1,$content);
            }
        }
    }

    public function cardTypePro($id){
        $tb    = otable::ChestSkinConfig(2);
        $ret   = oo::commonOprDb('slavedb')->getOne("SELECT `starPro` FROM {$tb} WHERE id={$id}",MYSQLI_ASSOC);
        $data  = json_decode($ret['starPro'],true) ?? [];
        $data['pro'] = array_column($data['pro'],null,"star");
        $data['id']  = $id;
        $data['cardTypes'] = [
            0 => '常规卡',
            1 => '限时卡',
            2 => '全部',
        ];
        $this->load->view('config/chestSkinPro',$data);
    }

    public function actionCardTypePro($id){
        $config = $this->input->post('config');
        if(array_sum($config['star']) == 0){
            $data = "[]";
        }else{
            $pro = [];
            foreach ($config['star'] as $key=>$row){
                $pro[] = [
                    'star' => $key,
                    'v'    => $row,
                ];
            }
            $data['pro'] = $pro;
            $data['maxGoldCard'] = $config['maxGoldCard'];
            $data['maxBlackGoldCard'] = $config['maxBlackGoldCard'];
            $data['blackGoldCardKValue'] = $config['blackGoldCardKValue'];
            $data['cardType'] = $config['cardType'];

            $data = json_encode($data,JSON_NUMERIC_CHECK);
        }
        $tb  = otable::ChestSkinConfig(2);
        $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET `starPro`='{$data}' WHERE id ='{$id}'");
        $ret && oo::commonOprRedis('games')->set(okeys::ChestSkinStarProConfig($id), $data);
        if($ret){
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function shareConfig($type = "",$country = 'DEFAULT'){
        $tb  = otable::shareConfig();
        $tb2 = otable::shareBaseConfig();
        $data['langList'] = oo::cfg('lang')['lang_upper'];
        if(empty($type)){
            $data['idData']   = oo::commonOprModel('config')->getPropsConfig();
            $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}", 1);
            $ret2 = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb2}", 1);
            $defaultLangContent = [
                'title' => '',
                'desc' => '',
            ];
            foreach ($ret as &$row){
                $row['reward'] = json_decode($row['reward'],true);
                $content = json_decode($row['content'], true);
                foreach ($data['langList'] as $langKey => $langCn){
                    $content[$langKey] = $content[$langKey] ?? $defaultLangContent;//$content['LEN'];
                }
                $row['content'] = json_encode($content);
            }
            $data['list'] = array_column($ret,null,'key');
            $data['base'] = $ret2;
            $this->load->view('config/shareConfig3', $data);
        }
        else{
            $oos_debug = $this->config->item('oos_debug');
            if($oos_debug){
                $server = ($_SERVER['HTTPS']?"https://":"http://").$_SERVER['HTTP_HOST'];
            } else {
                $server = 'https://share.crazycoin.link/';
            }
            $data['server'] = $server;
            $data['list'] = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $data['href']     = "/filemanager.php?fm_usr=share&fm_pwd=share&userName=".get_cookie('chinesename')."&shareCountry={$country}";
            $data['country']  = $country;
            $active = $langData = $track = [];
            foreach($data['list'] as $key => $row){
                $abTest = json_decode($row['abTest'],true) ?? [];
                $actImg = json_decode($row['actImg'],true) ?? [];
                $curTrack = json_decode($row['track'],true) ?? [];
                $track[$row['key']] = $curTrack[ltrim($country,'L')] ?? $curTrack[$country] ;
                $langData[$row['key']] = intval($abTest[$country]);
                $active[$row['key']] = $actImg[$country]?? 0;
            }
            $data['langData'] = $langData;
            $data['track']    = $track;
            $data['actImg']   = $active;
            $this->load->view('config/shareImgConfig', $data);
        }
    }

    public function actShareConfig($type = ""){
        $tb  = otable::shareConfig();
        $baseTb  = otable::shareBaseConfig();
        $langList = array_keys(oo::cfg('lang')['lang_upper2']);
        $langList[] = 'DEFAULT';
        $defaultData = [
            'key' => 3,
            'name' => 3,
            'maxTimes' => 1,
            'reward' => addslashes('[{"propsId":"15","num":"2"}]'),
            'intervalTime' => 3600,
            'show' => 1,
            'content' => 3,
            'abTest' => addslashes('{"US":"0","FR":"0","ES":"0","DE":"1","GB":"0","DEFAULT":"0","TH":"0"}'),
            'shareType' => 0,
            'track' => addslashes('{"DEFAULT":{"d":"1z942q1","a":"1z942q1","b":"1z942q1"},"DE":{"d":"8g99z77","a":"cie3b7w","b":"wfmhp2g"},"FR":{"d":"60shva0","a":"6sebuqj","b":"27tlmz2"},"US":{"d":"gxblf9m","a":"9gzqkcl","b":"u5ihz6f"},"GB":{"d":"dc9n0pz","a":"r4xow6l","b":"t2h9zu9"},"ES":{"d":"l5whjy0","a":"f8qzgmq","b":"5oc8av6"},"TH":{"d":"6b83wcj","a":"f8rn47g","b":"vtzdqt7"},"BR":{"d":"f0nlwkm","a":"qys3vl9","b":"3jh5jnb"}}'),
            'actImg' => addslashes('{"DEFAULT":0,"GB":0,"TH":0}'),
        ];
        $columns = '`' . implode('`,`', array_keys($defaultData)) . '`';
        if(empty($type)){
            $post = $this->input->post('conf');
            $base = $this->input->post('base');
            $json = [];
            if($post && is_array($post)){
                if(!$this->checkShareKeyRepeat($post)){
                    return $this->response(1, '分享点类型不能重复');
                }
                foreach ($post as $key=>$value) {
                    $content = addslashes($value['content']);
                    $shareType = $value["shareType"];
                    $sql = "select * from  {$tb} where `key` ='{$value['key']}'";
                    $row = oo::commonOprDb('games')->getOne($sql, 1);
                    if($row){
                        $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET `content`='{$content}',`shareType`='{$shareType}' WHERE `key` ='{$value['key']}'");
                    } else{
                        $value['content'] = $content;
                        $insertData = array_merge($defaultData, $value);
                        $insertValuesStr = '';
                        foreach ($insertData as $iv){
                            $insertValuesStr .= "'{$iv}',";
                        }
                        $insertValuesStr = trim($insertValuesStr, ',');
                        $insertSql = "insert into {$tb} ({$columns}) VALUES ({$insertValuesStr}) ";
                        $ret = oo::commonOprDb('games')->query($insertSql);
                    }
                    //$maxTimes = $value["maxTimes"];
                    //$reward = addslashes(json_encode($value['reward']));
                    //$intervalTime = $value["intervalTime"];
                    //$show = $value['show'];
                    //$ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET `reward`='{$reward}',`intervalTime`='{$intervalTime}',`show`='{$show}',`content`='{$content}',`shareType`='{$shareType}',`maxTimes`='{$maxTimes}' WHERE `key` ='{$key}'");
                }
            }
            if($base && is_array($base)){
                $maxTimes = isset($base['maxTimes']) ? (int)$base['maxTimes'] : 1;
                $reward = isset($base['reward']) ? (int)$base['reward'] : 1;
                $show = isset($base['show']) ? (int)$base['show'] : 0;
                $intervalTime = isset($base['intervalTime']) ? (int)$base['intervalTime'] : 1;

                $ret = oo::commonOprDb('games')->query("UPDATE {$baseTb} SET `reward`='{$reward}',`intervalTime`='{$intervalTime}',`show`='{$show}',`maxTimes`='{$maxTimes}'");
            }
        }else{
            $country = $this->input->post('country');
            $data = $this->input->post('data');
            $d = $this->input->post('d');
            $a = $this->input->post('a');
            $b = $this->input->post('b');
            $actImg = $this->input->post('actImg');
            $res  = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $res  = array_column($res,NULL,"key");
            foreach ($data as $key=>$row){
                $abTest = json_decode($res[$key]['abTest'],true);
                $track  = json_decode($res[$key]['track'],true);
                $abTest[$country] = $row;
                $origActImg = empty($res[$key]['actImg']) ? [] : (array)json_decode($res[$key]['actImg'], true);
                if($row){
                    unset($origActImg[$country]);
                } else {
                    $origActImg[$country] = (empty($actImg[$key])||!in_array($actImg[$key], [0,1,2]))?0:$actImg[$key];
                }
                $abTest = json_encode($abTest);
                $origActImg = json_encode($origActImg);
                $track[$country] = [
                    "d"=>$d[$key],
                    "a"=>$a[$key],
                    "b"=>$b[$key],
                ];
                $track = json_encode($track);
                $ret = oo::commonOprDb('games')->query("UPDATE {$tb} SET `abTest` ='{$abTest}',`track` ='{$track}',`actImg`='{$origActImg}' WHERE `key`='{$key}'");
            }
        }
        if($ret){
            $ret  = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $ret  = array_column($ret,NULL,"key");
            $ret2  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$baseTb}",MYSQLI_ASSOC);
            $tbConf2 = otable::shareConfig2();
            $retInvite  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tbConf2} WHERE `type`='invite'",MYSQLI_ASSOC);

            //$inviteConf = oo::commonOprDb('slavedb')->getOne("SELECT * FROM ");

            foreach ($ret as $key=>$row){
                $reward = json_decode($row['reward'],true);
                $track  = json_decode($row['track'],true);
                $abTest = json_decode($row['abTest'],true);
                $actImg = $row['actImg'] ? (array)json_decode($row['actImg'],true) : [];
                foreach ($track as $lk => $lv){
                    if(!in_array($lk, $langList)){
                        $track[$lk] = $track["DEFAULT"];
                    }
                    foreach ($lv as $gk => $gv){
                        if(empty($gv)){
                            $track[$lk][$gk] = '';
                        }
                    }
                }
                $json[$key] = [
                    //'maxTimes'     => $row['maxTimes'],
                    //'reward'       => $reward,
                    //'intervalTime' => $row['intervalTime'],
                    //'show'         => $row['show'],
                    'shareType'    => $row['shareType'],
                    'abTest'       => $abTest,
                    'track'        => $track,
                    'actImg'       => $actImg,
                    'intervalTime' => $row['intervalTime'],
                ];
                if($row['key'] == 'INVITE_FRIEND'){
                    $json[$key]['reward'] = (array)json_decode($retInvite['reward'], true);
                    $json[$key]['intervalTime'] = $retInvite['intervalTime'];
                    $json[$key]['maxTimes'] = $retInvite['maxTimes'];
                    $json[$key]['show'] = $retInvite['show'];
                }
            }
            $json['maxTimes'] = (int)$ret2['maxTimes'];
            $json['reward'] = [["propsId"=>15,"num" => (int)$ret2['reward']]];
            $json['show'] = (int)$ret2['show'];
            $json['intervalTime'] = (int)$ret2['intervalTime'];

            //删除公共配置
            oo::commonOprRedis('games')->delete(okeys::shareBaseConfig());
            //删除
            oo::commonOprRedis('games')->delete(okeys::shareConfig(3));

            $filename = "ShareConfig".time().".json";
            oo::commonOprModel("json")->SaveJson($json,$filename) && oo::commonOprModel("json")->setStaticConfig("Share",$filename);
            oo::commonOprModel("language")->setLangJson();
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }
    public function delShareConfig($key = ""){
        $tb  = otable::shareConfig();
        $baseTb  = otable::shareBaseConfig();
        if(empty($key)){
            $this->response(1, '参数异常');
        }

        $ret = oo::commonOprDb('games')->query("delete from {$tb} where `key`='{$key}'");


        if($ret){
            $ret  = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            $ret  = array_column($ret,NULL,"key");
            $ret2  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$baseTb}",MYSQLI_ASSOC);
            $tbConf2 = otable::shareConfig2();
            $retInvite  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tbConf2} WHERE `type`='invite'",MYSQLI_ASSOC);

            //$inviteConf = oo::commonOprDb('slavedb')->getOne("SELECT * FROM ");

            foreach ($ret as $key=>$row){
                $reward = json_decode($row['reward'],true);
                $track  = json_decode($row['track'],true);
                $abTest = json_decode($row['abTest'],true);
                $actImg = $row['actImg'] ? (array)json_decode($row['actImg'],true) : [];
                $json[$key] = [
                    //'maxTimes'     => $row['maxTimes'],
                    //'reward'       => $reward,
                    //'intervalTime' => $row['intervalTime'],
                    //'show'         => $row['show'],
                    'shareType'    => $row['shareType'],
                    'abTest'       => $abTest,
                    'track'        => $track,
                    'actImg'       => $actImg,
                ];
                if($row['key'] == 'INVITE_FRIEND'){
                    $json[$key]['reward'] = (array)json_decode($retInvite['reward'], true);
                    $json[$key]['intervalTime'] = $retInvite['intervalTime'];
                    $json[$key]['maxTimes'] = $retInvite['maxTimes'];
                    $json[$key]['show'] = $retInvite['show'];
                }
            }
            $json['maxTimes'] = (int)$ret2['maxTimes'];
            $json['reward'] = [["propsId"=>15,"num" => (int)$ret2['reward']]];
            $json['show'] = (int)$ret2['show'];
            $json['intervalTime'] = (int)$ret2['intervalTime'];

            //删除公共配置
            oo::commonOprRedis('games')->delete(okeys::shareBaseConfig());
            //删除
            oo::commonOprRedis('games')->delete(okeys::shareConfig(3));

            $filename = "ShareConfig".time().".json";
            oo::commonOprModel("json")->SaveJson($json,$filename) && oo::commonOprModel("json")->setStaticConfig("Share",$filename);
            oo::commonOprModel("language")->setLangJson();
            return $this->response(0, '操作成功');
        }else{
            return $this->response(1, '操作失败');
        }
    }
    private function checkShareKeyRepeat($shareList){
        $shareKeys = [];
        foreach ($shareList as $item){
            if(in_array($item['key'], $shareKeys))return false;
            $shareKeys[] = $item['key'];
        }
        return true;
    }

    // -----------------------------------------------------------------------------------------------------------------
    /**
     * 金卡交换粉丝页地址不同语言配置
     */
    public function fansUrl() {
        $tb = otable::fansUrl();
        $sql = "SELECT * FROM {$tb} ORDER BY ID ASC";
        $list = oo::commonOprDb('games')->getAll($sql, 1);
        $data = ['list' => $list];
        $this->load->view('config/fansUrl', $data);
    }

    /**
     * 金卡交换粉丝页更新
     */
    public function actFansUrl() {
        $post = $this->input->post('conf');
        if(!$post || !is_array($post)){
            return $this->response(1, '操作失败');
        }
        $tb = otable::fansUrl();
        foreach($post['id'] as $id){
            if(empty($post['url']) || empty($post['url'][$id])){
                continue;
            }
            $sql = "UPDATE {$tb} SET url='{$post['url'][$id]}' WHERE id={$id}";
            $ret = oo::commonOprDb('games')->query($sql);
        }
        if(!$ret){
            return $this->response(1, '操作失败');
        }
        oo::commonOprRedis('games')->delete(okeys::fansUrl());

        $sql = "SELECT * FROM {$tb} ORDER BY ID ASC";
        $list = oo::commonOprDb('games')->getAll($sql, 1);
        if(empty($list)){
            return $this->response(0, '操作成功');
        }
        $json = [];
        foreach($list as $val){
            $json[$val['lang']] = $val['url'];
        }
        $filename = "FansUrl".time().".json";
        oo::commonOprModel("json")->SaveJson($json,$filename) && oo::commonOprModel("json")->setStaticConfig("FansUrl",$filename);
        return $this->response(0, '操作成功');
    }
//    public $goodSku  = [
//        ["sku"=>'com.gworld.cc.gift07',   "price"=>'1.99'],
//        ["sku"=>'com.gworld.cc.gift08',   "price"=>'2.99'],
//        ["sku"=>'com.gworld.cc.gift3.99', "price"=>'3.99'],
//        ["sku"=>'com.gworld.cc.gift04',   "price"=>'4.99'],
//        ["sku"=>'com.gworld.cc.gift7.99', "price"=>'7.99'],
//        ["sku"=>'com.gworld.cc.gift01',   "price"=>'9.99'],
//        ["sku"=>'com.gworld.cc.gift05',   "price"=>'14.99'],
//        ["sku"=>'com.gworld.cc.gift02',   "price"=>'19.99'],
//        ["sku"=>'com.gworld.cc.gift29.99',"price"=>'29.99'],
//        ["sku"=>'com.gworld.cc.gift09',   "price"=>'49.99'],
//        ["sku"=>'com.gworld.cc.gift03',   "price"=>'99.99'],
//    ];
    //水果机配置
    public function fruitConfig(){
        $goodSku =oo::cfg('sku');
        $slotResult =[1=>"金币",2=>"体力",3=>"特殊奖励",4=>"下次双倍",5=>"三次奖励机会"];
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $posts['frombg'] = 1;
        $posts['type'] = 18;
        $posts['lid'] = 1;
        $posts['sid'] = 1;
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $idData = $retData['props'];
        //===基础配置===
        $tb=otable::fruitBaseConfig();
        $sql = "SELECT * FROM {$tb}";
        $configs = oo::commonOprDb('games')->getAll($sql, 1);
        foreach ($configs as $cfg){
            $list[$cfg["type"]] = json_decode($cfg["config"],true);
        }

        //等级配置
        $tb2=otable::fruitLvConfig();
        $sql2= "SELECT * FROM {$tb2}";
        $configs2 = oo::commonOprDb('games')->getAll($sql2, 1);

        //商品配置
        $tb3 = otable::goodsCrazy();
        $sql3= "SELECT * FROM {$tb3} where gtype=32";
        $configs3 = oo::commonOprDb('games')->getAll($sql3, 1);

        $list2=[];
        foreach ($configs2 as $k=>$cfg){
            $list2[$k]['lv'] = $cfg['lv'];
            $list2[$k]['maxExp'] = $cfg['maxExp'];
            $list2[$k]["upCeCfg"] = json_decode($cfg["upCeCfg"],true);
            $list2[$k]["lvRewardCfg"] = json_decode($cfg["lvRewardCfg"],true);
        }
        $data =[
            "list"=>$list,
            "idData"=>$idData,
            "chestSkin"=>array_column(oo::commonOprModel('config')->chestSkin(),'name','id'),
            "slotResult"=>$slotResult,
            "lvList"=>$list2,
            "goodsList"=>$configs3,
            "skuList"=>$goodSku,
        ];

        $this->load->view('config/fruitGame', $data);
    }
    //保存基础配置
    public function SaveFruitCfg($type){
        $post = $this->input->post();
        $tb=otable::fruitBaseConfig();
        if ($type){
            $data = json_encode($post[$type]);
            if($type=='goodsList'){
                foreach($post[$type] as $k=>$v){
                    $glist[]= [
                        "gid"=>intval($v["gid"]),
                        "spinNum"=>intval($v["goriginReward"]),
                        "sku"=>$v["gsku"],
                        "prizeNum"=>floatval($v["gprice"]),
                        "discount"=>floatval($v['gdiscount']),
                        "maxLimit"=>floatval($v['gMax']),
                    ];
                }
                $data = json_encode($glist);
            }
            $updata =["config"=>$data];
            $w ="type='".$type."'";
            $sql = funs::db_updateSQL($tb,$updata,$w);
//            return $this->response(0, '操作成功',[$sql]);
            $res  =oo::commonOprDb('games')->query($sql,1);
            if($res){
                switch ($type){
                    case "gamePro":
                        $key=okeys::FruitGameProCfg();
                        oo::commonOprRedis('games')->set($key,$data);
                        break;
                    case "gameLimit":
                        $key=okeys::FruitGameLimitCfg();
                        oo::commonOprRedis('games')->hMset($key,$post[$type]);
                        break;
                    case "goodsList":
                        $key=okeys::FruitGameGoodsListCfg();
                        oo::commonOprRedis('games')->set($key,$data);
                        break;
                }
            }
        }
        if($type=="goodsList"){
            $tb2 = otable::goodsCrazy();
            foreach ($post[$type] as $k=>$v){
                $updata2 = $v;
                $w2 ="gid=".$v['gid'];
                unset($updata2["gid"]);
                $sql2 = funs::db_updateSQL($tb2,$updata2,$w2);
                $res1[]  =oo::commonOprDb('games')->query($sql2,1);
            }
            if (!$res1[0]||!$res1[1]){
                $res = false;
            }
        }
        if($res){
            $ret=$this->response(0, '操作成功',$post);
        }else{
            $ret =$this->response(1, '操作失败',$post);
        }
        return $ret;
    }
    //保存等级配置
    public function SaveFruitLvCfg(){
        $post = $this->input->post();
        $data = json_decode($post["data"],true);
        foreach ($data["reward"] as $k=>$v){
            unset($data["reward"][$k]["id"]);
        }
        $updata = [
            "lv"=>$data['lv'],
            "maxExp"=>$data["maxExp"],
            "upCeCfg"=>json_encode($data["data"]),
            "lvRewardCfg"=>json_encode($data["reward"]),
        ];
        $w= "lv={$data['lv']}";
        $sql = funs::db_updateSQL(otable::fruitLvConfig(),$updata,$w);
        $res = oo::commonOprDb('games')->query($sql,1);
        if ($res){
            $key=okeys::FruitGameLvCfg($data['lv']);
            oo::commonOprRedis('games')->hMset($key,$updata);
            return $this->response(0, '操作成功',$updata);
        }else{
            return $this->response(1, '操作失败',$data);
        }

    }
//======新水果机============
    public function fruitNewConfig(){
        $goodSku =oo::cfg('sku');
        $slotResult =[3=>"奖励",4=>"下次双倍"];
        $idData = oo::cfg('props');
        //===基础配置===
        $tb=otable::fruitBaseConfig();
        $sql = "SELECT * FROM {$tb}";
        $configs = oo::commonOprDb('games')->getAll($sql, 1);
        foreach ($configs as $cfg){
            $list[$cfg["type"]] = json_decode($cfg["config"],true);
        }

        //等级配置
        $tb2=otable::fruitLvConfig();
        $sql2= "SELECT * FROM {$tb2}";
        $configs2 = oo::commonOprDb('games')->getAll($sql2, 1);

        //商品配置
//        $tb3 = otable::goodsCrazy();
//        $sql3= "SELECT * FROM {$tb3} where gpid=113";
//        $configs3 = oo::commonOprDb('games')->getAll($sql3, 1);
        $configs3 = $list['goodsListNew'];
        $list2=[];
        foreach ($configs2 as $k=>$cfg){
            $list2[$k]['lv'] = $cfg['lv'];
            $list2[$k]['maxExp'] = $cfg['maxExp'];
            $list2[$k]["upCeCfg"] = json_decode($cfg["upCeCfg"],true);
            $list2[$k]["lvRewardCfg"] = json_decode($cfg["lvRewardCfg"],true);
        }
        $data =[
            "list"=>$list,
            "idData"=>$idData,
            "chestSkin"=>array_column(oo::commonOprModel('config')->chestSkin(),'name','id'),
            "slotResult"=>$slotResult,
            "lvList"=>$list2,
            "goodsList"=>$configs3,
            "skuList"=>$goodSku,
        ];

        $this->load->view('config/fruitGameNew', $data);
    }
    //保存基础配置
    public function SaveFruitNewCfg($type){
        $post = $this->input->post();
        $tb=otable::fruitBaseConfig();
        if ($type){
            $data = json_encode($post[$type]);
//            return $this->response(1, '操作失败',$post);
            if($type=='goodsListNew'){
                foreach($post[$type] as $k=>$v){
                    $glist[]= [
                        "gid"=>intval($v["gid"]),
                        "gtype"=>113,
                        "sku"=>$v["sku"],
                        "price"=>floatval($v["price"]),
                        "bet"=>intval($v['bet']),
                    ];
                }
                $data = json_encode($glist,32);
            }else if($type=='gameProNew'||$type=='gameProNewPay'){
                foreach($post[$type] as $k=>$v){
                    $propsIds = array_column($v["ext"],"propsId");
                    if($v["id"]!=1&&in_array(19,$propsIds)){
                        $ret =$this->response(1, '操作失败,只有id:6可以配置小丑宝箱',$v);
                        return $ret;
                    }
                    if($v["id"]!=1&&count($propsIds)==1&&!in_array(14,$propsIds)){
                        $ret =$this->response(1, '操作失败,其他结果项id:'.$v["id"].'只能配置金币',$v);
                        return $ret;
                    }
                }
            }

            $updata =["config"=>$data];
            $w ="type='".$type."'";
            $sql = funs::db_updateSQL($tb,$updata,$w);
//            return $this->response(0, '操作成功',[$sql]);
            $res  =oo::commonOprDb('games')->query($sql,1);
            if($res){
                switch ($type){
                    case "gameProNew":
                        $key=okeys::FruitGameProCfg("_NEW");
                        oo::commonOprRedis('games')->set($key,$data);
                        break;
                    case "gameProNewPay":
                        $key=okeys::FruitGameProCfg("_NEW:PAY");
                        oo::commonOprRedis('games')->set($key,$data);
                        break;
                    case "goodsListNew":
                        $key=okeys::FruitGameGoodsListCfg("_NEW");
                        oo::commonOprRedis('games')->set($key,$data);
                        break;
                }
            }
        }
//        if($type=="goodsList"){
//            $tb2 = otable::goodsCrazy();
//            foreach ($post[$type] as $k=>$v){
//                $updata2 = $v;
//                $w2 ="gid=".$v['gid'];
//                unset($updata2["gid"]);
//                $sql2 = funs::db_updateSQL($tb2,$updata2,$w2);
//                $res1[]  =oo::commonOprDb('games')->query($sql2,1);
//            }
//            if (!$res1[0]||!$res1[1]){
//                $res = false;
//            }
//        }
        if($res){
            $ret=$this->response(0, '操作成功',$post);
        }else{
            $ret =$this->response(1, '操作失败',$post);
        }
        return $ret;
    }
//==========================

    public function stealCoinConfig(){
        $tbl = otable::commonConfig();
        $type = 'stealMaxMoney';
        $config = oo::commonOprDb('slavedb')->getOne("select * from {$tbl} where type='{$type}'",1);
        $config = json_decode($config['conf'], true);
        $data = [
            'list' => $config
        ];
        $this->load->view('config/stealCoinConfig', $data);
    }
    public function stealCoinConfigSave(){
        $post = $this->input->post('data');
        if(empty($post))$this->response(1, '参数异常');
        $post = @json_decode($post, true);
        if(empty($post))$this->response(1, '参数异常');
        $post = array_column($post, null, 'levelId');
        foreach ($post as $lv => $item){
            if(empty($lv) || empty($item['levelId']) || empty($item['maxCoin']))unset($post[$lv]);
        }
        $data = json_encode($post);
        $tbl = otable::commonConfig();
        $type = 'stealMaxMoney';
        $title = '偷金币配置';
        $config = oo::commonOprDb('slavedb')->getOne("select * from {$tbl} where type='{$type}'",1);

        if($config){
            $sql = "UPDATE {$tbl} SET conf='".$data."' where type='{$type}'";
        }else{
            $sql = "INSERT INTO {$tbl}(name, type, conf) VALUES('{$title}','{$type}', '{$data}')";
        }
        $res = oo::commonOprDb('games')->query($sql);
        if ($res){
            $updata = array_column($post, 'maxCoin', 'levelId');
            $key = okeys::stealCoinConf();
            oo::commonOprRedis('games')->delete($key);
            oo::commonOprRedis('games')->hMset($key,$updata);
            return $this->response(0, '操作成功',[$updata]);
        }else{
            return $this->response(1, '操作失败');
        }
    }

    public function getPropsConfig()
    {
        $params = $this->input->get();
        $propsType = $params['type'] ?? 'activity';

        $propsConfig = oo::commonOprModel('config')->getPropsConfigFromLocal($propsType);
        $this->response(1, 'success', $propsConfig);
    }

    public function slotWhiteList(){
        $key = okeys::slotWhiteList();
        $uids = oo::commonOprRedis('games')->sMembers($key);
        $this->load->view('config/slotWhiteList', ['uids' => $uids]);
    }
    public function setSlotWhiteList(){
        $key = okeys::slotWhiteList();
        $newUids = $this->input->post('uids');
        $newUids = strtr($newUids, ['，' => ',']);
        $newUids = explode(',', $newUids);

        oo::commonOprRedis('games')->delete($key);
        foreach ($newUids as $uid){
            $addRes[] = oo::commonOprRedis('games')->sAdd($key, $uid);
        }
        $this->response(1, '操作成功', [ $addRes]);
    }

    //体力瓶配置
    public function spinsPotGift()
    {
        $tb = otable::spinsPotGift();
        $tb2 = otable::spinsPotWeight();
        //基础配置
        $data['list']['baseCfg'] = oo::commonOprModel('config')->getCommonConf('spinsPotCfg');
        //礼包
        $sql = "SELECT * FROM {$tb} group by startlv,endlv";
        $giftPackList = oo::commonOprDb('slavedb')->getAll($sql, 1);
        foreach ($giftPackList as $k => $item) {
            $giftPackList[$k]['firstcfg'] = json_decode($item['firstcfg'], true);
            $giftPackList[$k]['againcfg'] = json_decode($item['againcfg'], true);
            $giftPackList[$k]['longtimecfg'] = json_decode($item['longtimecfg'], true);
        }
        //权重
        $spinsWeight = [];
        $sql = "SELECT * FROM {$tb2}";
        $list2 = oo::commonOprDb('slavedb')->getAll($sql, 1);
        foreach ($list2 as $item) {
            $spinsWeight[] = json_decode($item['config'], true);
        }
        $data["priceArr"] = oo::cfg('sku');
        $data["resourceDirs"] = oo::commonOprModel('config')->getActiveImgNameConfig()["spinsPot"];
        $data['list']['giftPack'] = $giftPackList;
        $data['list']['spinsWeight'] = $spinsWeight;
        $data['title'] = ["等级", "权重", "类型(1一个瓶,2两个瓶)", "分值"];

        $this->load->view('tiger/spinsPotGift', $data);
    }
    //基础配置
    public function saveSpinsPotBaseCfg(){
        $conf= $this->input->post('conf');

        $key = okeys::spinsPotBaseCfg();
        $res = oo::commonOprModel('config')->saveCommonConf('spinsPotCfg',$conf,"体力瓶基础配置");
        if($res){
            oo::commonOprRedis('games')->hMset($key,$conf);
        }
        $this->response(1, '操作成功', [$conf]);
    }

    //礼包配置
    public function saveSpinsPotGift()
    {
        $confList = $this->input->post('conf');

        $tb = otable::spinsPotGift();
        oo::commonOprDb("games")->query("DELETE FROM {$tb}");

        $cacheMap = [];
        foreach ($confList as $item) {
            for ($i = $item['startlv']; $i <= $item['endlv']; $i++) {
                $one = [
                    'levelId' => $i,
                    'startlv' => $item['startlv'],
                    'endlv' => $item['endlv'],
                    'initval' => $item['initval'],
                    'firstcfg' => json_encode($item['firstcfg'], JSON_NUMERIC_CHECK),
                    'againcfg' => json_encode($item['againcfg'], JSON_NUMERIC_CHECK),
                    'longtimecfg' => json_encode($item['longtimecfg'], JSON_NUMERIC_CHECK),
                ];
                $item['levelId'] = $i;
                $sql = funs::db_insertSQL($tb, $one);
                $res = oo::commonOprDb("games")->query($sql, 1);
                if (!$res) {
                    $this->response(-1, '操作失败');
                }
                $cacheMap[$i] = json_encode($item, JSON_NUMERIC_CHECK);
            }
        }
        oo::commonOprRedis('games')->delete(okeys::spinsPotGift());
        oo::commonOprRedis('games')->hMset(okeys::spinsPotGift(), $cacheMap);

        $this->response(1, '操作成功', $confList);
    }

    //打配置
    public function attackCfg(){
        //基础配置
        $data['baseCfg'] = oo::commonOprModel('config')->getCommonConf('TIGER_ATTACK_CONFIG');
        $this->load->view('tiger/attackCfg',$data);
    }
    public function saveAttackCfg(){
        $conf= $this->input->post('conf');

        $key = okeys::attackConfig();
        $res = oo::commonOprModel('config')->saveCommonConf('TIGER_ATTACK_CONFIG',$conf,"打基础配置");
        if($res){
            oo::commonOprRedis('games')->set($key,json_encode($conf,32));
        }
        $this->response(1, '操作成功', [$conf]);
    }

    // 活动解锁提醒
    public function actUnlockConf()
    {
        //基础配置
        $data['conf'] = oo::commonOprModel('config')->getCommonConf('ACT_UNLOCK_CONF');
        $data['option'] = UNLOCK_ACT_LIST;

        $this->load->view('config/actUnlockConf', $data);
    }

    public function saveActUnlockConf()
    {
        $conf = $this->input->post('conf');

        $keyArr = [];
        foreach ($conf as $item) {
            if (in_array($item['key'], $keyArr)) {
                $name = UNLOCK_ACT_LIST[$item['key']];
                $this->response(1, "不能设置重复的活动名: {$name}");
            }

            $keyArr[] = $item['key'];
        }

        oo::commonOprModel('config')->saveCommonConf('ACT_UNLOCK_CONF', $conf, "活动解锁提醒配置");

        $filename = 'ActUnlockConf' . time() . '.json';
        oo::commonOprModel("json")->SaveJson($conf, $filename);
        oo::commonOprModel("json")->setStaticConfig("ActUnlockConf", $filename);

        $this->response(0, '操作成功');
    }

    # 新手引导最后一步配置
    public function guideLastStep(){
        $guideMap = [
            0 => '关闭',
            1 => '卡牌翻翻乐',
        ];
        $table = otable::commonConfig();
        $typeKey = okeys::guideLastStep();
        $config = oo::commonOprRedis('games')->get($typeKey);
        if(empty($config)){
            $config = oo::commonOprDb('slavedb')->getOne("select * from {$table} where type='{$typeKey}' limit 1");
            $config = $config['conf'] ?? '';
        }
        $config = @json_decode($config, true) ?? [];
        $columns = [
            'conf' => $this->inputField('conf','是否开启', 'selector', intval($config['conf']), $guideMap),
        ];
        $data = [
            'config' => $config,
            'columns' => $columns,
        ];
        $this->load->view('config/guideLastStep', $data);
    }
    public function saveGuideLastStep(){
        $table = otable::commonConfig();
        $typeKey = okeys::guideLastStep();
        $configName = '新手引导最后一步配置';


        $input = $this->input->post();
        $config = json_encode($input);
        if(empty($input['id'])){
            $res = oo::commonOprDb('games')->query("insert into {$table} (`type`, `name`, `conf`)  values ('{$typeKey}', '{$configName}', '{$config}')");
            $input['id'] = oo::commonOprDb('games')->insertID();
            $config = json_encode($input);
        }
        $res = oo::commonOprDb('games')->query("update {$table} set  `conf`='{$config}' where id={$input['id']} ");
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->set($typeKey, $config);
        $this->response(1, '保存成功');
    }


    public function getPropsCommonConfig($type)
    {
        $propsConfig = ConfigModel::getPropsCommonConfig($type);
        $this->response(0, 'success', $propsConfig);
    }

    /**
     * 主题标题配置
     */
    public function themeTitleConf()
    {
        $table = otable::ActiveImgNameConfig();
        $type = $this->input->post()['type'];
        $subType = $this->input->post()['subType'];
        $titleConf = oo::commonOprDb('slavedb')->getOne("select * from {$table} where `name`='{$type}'");
        $titleConf = json_decode($titleConf['title_conf'], true) ?? [];
        if(empty($titleConf[$subType])){
            $titleConf = oo::commonOprModel('config')->getCon("actThemeConf", "titleConfig") ?? '[]';
            $titleConf = json_decode($titleConf, true);
            $titleConf[$subType] = $titleConf[$subType] ?? [];
        }
        $titleConf[$subType]['type'] = $type;
        $titleConf[$subType]['key'] = $subType;



        return $this->response(0, '操作成功', $titleConf[$subType]);
    }

    // 主题标题配置更新
    public function themeTitleConfUpdate()
    {
        $data = $this->input->post();

        $table = otable::ActiveImgNameConfig();
        $type = $data['type'];
        $subType = $data['key'];
        unset($data['type']);
        unset($data['key']);

        $typeConf = oo::commonOprDb('slavedb')->getAll("select * from {$table} ");
        $newJsonData = [];
        foreach ($typeConf as $item){
            $titleConf = json_decode($item['title_conf'], true) ?? [];
            if($item['name'] == $type){
                $titleConf[$subType] = $data;
                $newData = json_encode($titleConf, JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
                oo::commonOprDb('games')->getAll("update {$table} set `title_conf`='{$newData}' where `name`='{$type}' ");
            }
            $newJsonData = array_merge($newJsonData, (array)$titleConf);
        }

        $titleConf = oo::commonOprModel('config')->getCon("actThemeConf", "titleConfig") ?? '[]';
        $titleConf = json_decode($titleConf, true);

        $newJsonData = array_merge((array)$titleConf, $newJsonData);

        $filename = 'ActThemeTitleConfig' . time() . '.json';

        oo::commonOprModel("json")->SaveJson($newJsonData, $filename);
        oo::commonOprModel("json")->setStaticConfig("ActThemeTitleConfig", $filename);

        return $this->response(0, '操作成功');
    }


    // 活动礼包折扣Icon
    public function actIconRes()
    {
        $skins= oo::commonOprModel('config')->getActiveImgNameConfig("discount_icon", true)['content'];
        $data['resList'] = array_column($skins, 'name', 'type');
        $data['res'] = oo::commonOprModel('config')->getCon("Game", "discountIconTheme") ?? '';

        $this->load->view('config/actIconRes', $data);
    }

    // 更新活动礼包折扣Icon
    public function updateActIconRes()
    {
        $config = $this->input->post();
        $ret = oo::commonOprModel('config')->updateCon("Game", "discountIconTheme", $config['res'], '活动礼包折扣图标主题');

        // 更新json
        ConfigModel::updateConJson();

        if (!$ret) {
            return $this->response(1, '操作失败');
        } else {
            return $this->response(0, '操作成功');
        }
    }

    // 获取数数分组列表
    public function getShushuList(){
        $groups = oo::commonOprModel('config')->getUserGroupConfigByCid(5);
        return $this->response(0, '操作成功', $groups);
    }
}
