<?php
class ConfigModel extends CI_Model
{
    const MultiNumTypeReward = ['随机金卡', '金币'];
    public $versions = ['1.7.5.0','1.7.6.0','1.7.7.0','1.7.8.0','1.7.9.0','1.8.0.0','1.8.1.0','1.8.2.0','1.8.3.0', '1.8.4.0', '1.8.5', '1.8.6', '1.9'];

    public $device = [
        1=>'android',
        2=>'ios',
        3=>'vivo'
    ];

    public $country   = [
        'RO'=>'罗马尼亚',
        'US'=>'美国',
        'DE'=>'德国',
        'GB'=>'英国',
        'ES'=>'西班牙',
        'FR'=>'法国',
        'IN'=>'印度',
        'VN'=>'越南',
        'TH'=>'泰國',
        'NO'=>'挪威',
        'AT'=>'奥地利',
        'IT'=>'意大利',
        'DK'=>'丹麦',
        'SE'=>'瑞典',
        'IE'=>'爱尔兰',
        'AU'=>'澳大利亚',
        'BR'=>'巴西',
        'PT'=>'葡萄牙',
        'BE'=>'比利时',
        'IS'=>'冰岛',
        'CH'=>'瑞士',
        'OTHER'=>'其他'
    ];
    //配置道具原型结构
    public $PrizeStructY = [
        "id",
        "num",
        "type",
        "skin",
        "rtype",
        "is_ts",
        "ts"
    ];
    //配置道具表现结构
    public $PrizeShow =[
        "propsId",
        "num",
        "skin"
    ];
    public function __construct(){
        parent::__construct();
        $this->load->model('oo');
        $this->load->library('curl');
        $versions = $this->getVersions();
        if(!empty($versions)){
            $this->versions = $versions;
        }
    }

    /**
     * 获取当前在用的国家语言编码
     * @return array
     */
    public function getCurLangs() {
        return oo::cfg('lang')['lang_upper2'];
    }

    /**
     * coins 转换 gid
     * @param $coins
     * @return int|mixed
     * Created by: Owen
     * Created on: 2020/5/26 17:44
     */
    public function coinsToGid($coins){
        return 200 + str_replace("coins0","",$coins);
    }

    public function getCon($item, $title)
    {
        if (empty($item) || empty($title)) {
            return false;
        }

        $hashName = okeys::basicConfigKey();
        $key = "$item-$title";
        $ret = oo::commonOprRedis('games')->hGet($hashName, $key);
        if ($ret === false) {
            $table = otable::basicConfig();
            $sql = "SELECT content FROM {$table} WHERE item = '{$item}' AND title = '{$title}'";
            $res = oo::commonOprDb('slavedb')->getOne($sql, 1);
            oo::commonOprRedis('games')->hSet($hashName, $key, $res['content']);
            return $res['content'];
        }
        return $ret;
    }

    public function updateCon(string $item, string $title, string $content, string $memo)
    {
        $table = otable::basicConfig();
        $sql = "SELECT id,content FROM {$table} WHERE item = '{$item}' AND title = '{$title}'";
        $res = oo::commonOprDb('slavedb')->getOne($sql, 1);

        if (empty($res)) {
            $sql = "INSERT INTO {$table} (id,item,title,content,memo) VALUES (NULL,'{$item}','{$title}','{$content}','{$memo}')";
        } else {
            $sql = "UPDATE {$table} SET memo='{$memo}',item='{$item}',title='{$title}',content='{$content}' WHERE id={$res['id']}";
        }

        //写数据库
        $rs = oo::commonOprDb('games')->query($sql);

        //数据预热
        oo::commonOprRedis('games')->hSet(okeys::basicConfigKey(), "$item-$title", $content);
        oo::commonOprRedis('games')->hSet($table, "$item-$title", $content);

        return $rs ?: 0;
    }

    public function getVersions() {
        $tb = otable::versionSet();
        $sql = "SELECT * from {$tb} LIMIT 1";
        $rs = oo::commonOprDb('games')->getOne($sql,1);
        return empty($rs['content']) ? [] : explode(',', $rs['content']);
    }

    public static function formatLevelRewardConfig(array $levelConfig): array
    {
        foreach ($levelConfig as &$oneLevelConf) {
            if (empty($oneLevelConf['reward'])) {
                $oneLevelConf['reward'] = json_encode([
                    [
                        "propsId" => 14,
                        "num" => $oneLevelConf['reward_coin'] ?? 0,
                        "rtype" => 1,
                        "skin" => 0
                    ],
                    [
                        "propsId" => 15,
                        "num" => $oneLevelConf['reward_spin'] ?? 0,
                        "rtype" => 1,
                        "skin" => 0
                    ]
                ], JSON_NUMERIC_CHECK);
            }

            unset($oneLevelConf['reward_coin'], $oneLevelConf['reward_spin']);
        }

        return $levelConfig;
    }

    public static function getPropsCommonConfig($type = ''): array
    {
        $propsConfig = oo::commonOprModel('config')->getPropsConfigFromLocal($type);

        return self::formatPropConfig($propsConfig);
    }

    //格式化道具配置，统一数据结构
    public static function formatPropConfig(array $propsConf): array
    {
        $config = [];
        $actTypeArr = [];
        $priorityArr = [];
        foreach ($propsConf as $oneProp) {
            $one = [
                "id" => intval($oneProp['id']),
                "name" => $oneProp['name'],
                "type" => ($oneProp['type'] ?? 'nor') == 'act' ? 'act' : 'nor',
                "skinList" => isset($oneProp['skinList']) ? json_decode(json_encode($oneProp['skinList'], JSON_NUMERIC_CHECK), true) : []
            ];

            if ($one['type'] == 'act') {
                $actTypeArr[] = $one['id'];
            }

            if (in_array($one['id'], [14, 15, 16])) {
                $priorityArr[] = $one;
            } else {
                $config[] = $one;
            }
        }

        $config = array_merge($priorityArr, $config);

        return ['propsList' => $config, 'actIdList' => $actTypeArr, 'numIsOneList' => REWARD_NUM_ONE, 'rewardNumLimit' => REWARD_NUM_LIMIT];
    }

    public static function levelBasicConfImport(array $dataArray): array
    {
        $basicConf = $dataArray[0];
        $rewardConf = $dataArray[1];

        $retData = [];

        // 基础配置
        $columnsMapping = array_merge(array_keys(oo::cfg('lang')['lang_level']), [ 'pictureId']);
        foreach ($basicConf as $idx => $row) {
            if ($idx == 0) {
                continue;
            }
            $data = [];
            foreach ($columnsMapping as $k => $item){
                $data[$item] = $row[$k+1];
            }
            $retData[] = [
                'levelId' => $row[0],
                'data' => $data,
            ];
        }

        $commonConf = self::getPropsCommonConfig();

        $rewardsConf = [];
        for ($line = 1; $line < count($rewardConf); $line++) {
            $item = $rewardConf[$line];

            $rewardsTemp = ['level' => $item[0], 'prize' => []];
            $rewardList = [];

            //分割奖励
            array_shift($item);
            for ($index = 0; $index < count($item); $index++) {
                $div = intval($index / 3);
                $mod = $index % 3;

                $value = $item[$index];
                if ($mod == 0) {
                    if (empty($value)) {
                        break;
                    }
                    $rewardList[$div]['rewardName'] = $value;

                } elseif ($mod == 1) {
                    $rewardList[$div]['isFixNum'] = $value;
                } else {
                    $rewardList[$div]['rewardNum'] = $value;
                }
            }

            //格式化奖励
            foreach ($rewardList as $oneReward) {
                list($propsId, $skin) = self::parseRewardTypeAndSkinId($oneReward['rewardName'], $commonConf['propsList']);
                #非金币奖励，全部固定值奖励
                if (!in_array($oneReward['rewardName'], self::MultiNumTypeReward)) {
                    $oneReward['isFixNum'] = '是';
                }

                #固定值奖励 1 按等级取值 2
                $rtype = ($oneReward['isFixNum'] == '是') ? 1 : 2;

                #奖励数值
                $num = $oneReward['rewardNum'];

                $rewardsTemp['prize'][] = [
                    "propsId" => $propsId,
                    "num" => $num,
                    "rtype" => $rtype,
                    "skin" => $skin
                ];
            }

            $rewardsConf[] = $rewardsTemp;
        }

        foreach ($retData as &$oneBaseConf) {
            $matchTimes = 0;
            foreach ($rewardsConf as $index => $oneRewardConf) {
                //匹配上了
                if ($oneBaseConf['levelId'] == $oneRewardConf['level']) {
                    $matchTimes++;

                    //检查奖励的合法性
                    $ret = self::verifyReward($oneRewardConf['prize'], $commonConf, $oneRewardConf['level']);
                    if ($ret[0] != 0) {
                        return $ret;
                    }

                    $oneBaseConf['data']['reward'] = json_encode($oneRewardConf['prize'], JSON_NUMERIC_CHECK);
                }
            }
            //没匹配到奖励
            if (empty($matchTimes)) {
                return [-1, "唯一ID：{$oneBaseConf['levelId']},未匹配到奖励"];
            }
        }

        return $retData;
    }

    public static function getPropsNameById(array $reward): string
    {
        $propsName = '';
        if (empty($reward['propsId'])) {
            return $propsName;
        }

        $propsConfig = oo::commonOprModel('config')->getPropsConfigFromLocal();
        foreach ($propsConfig as $oneProps) {
            if ($oneProps['id'] == $reward['propsId']) {
                if (empty($reward['skin'])) {
                    return $oneProps['name'];
                }

                if (empty($oneProps['skinList'])) {
                    return $propsName;
                }

                foreach ($oneProps['skinList'] as $oneSkin) {
                    if ($oneSkin['id'] == $reward['skin']) {
                        return $oneSkin['name'];
                    }
                }
            }
        }

        return $propsName;
    }

    /**
     * 验证奖励是否合法
     */
    private static function verifyReward($prizeArr, $commonConf, $level): array
    {
        $actIdList = $commonConf['actIdList'];
        $numIsOneList = $commonConf['numIsOneList'];
        foreach ($prizeArr as $onePrize) {


            if (empty($onePrize['propsId'])) {
                return [-1, "唯一ID：{$level},所配置的奖励不存在"];
            }

            if (in_array($onePrize['propsId'], $numIsOneList) && intval($onePrize['num']) != 1) {
                return [-1, "唯一ID：{$level},宝箱,金卡等奖励值只支持一个"];
            }

            if (in_array($onePrize['propsId'], $actIdList) && $onePrize['skin'] === 0) {
                return [-1, "唯一ID：{$level},活动券的皮肤必须选择"];
            }
        }

        return [0, ""];
    }

    private static function parseRewardTypeAndSkinId($rewardName, $propsConfig): array
    {
        foreach ($propsConfig as $oneProps) {
            //对比奖励名
            if ($oneProps['name'] == $rewardName) {
                return [$oneProps['id'], 0];
            }

            if (empty($oneProps['skinList'])) {
                continue;
            }

            //有皮肤列表时，对比皮肤名
            foreach ($oneProps['skinList'] as $oneSkin) {
                if ($oneSkin['name'] == $rewardName) {
                    return [$oneProps['id'], $oneSkin['id']];
                }
            }
        }

        return [0, 0];
    }

    private function getPropsConf(string $propsType): array
    {
        $props = $propsType == 'func' ? oo::cfg('props_func') : oo::cfg('props');

        $chestSkin = oo::commonOprModel('config')->chestSkin();

        $chestSkinArr = [];
        foreach ($chestSkin as $oneSkin) {
            $chestSkinArr[] = ["id" => $oneSkin['id'], "name" => $oneSkin['name']];
        }

        $data = [];
        foreach ($props as $oneProp) {
            $type = $oneProp['type'] ?? '';
            if ($type == 'act') {//道具活动
                $oneProp['skinList'] = [];
                $aidList = oo::commonOprRedis('games')->hGetAll(okeys::onlineOpenActivity($oneProp['msg']));
                foreach ($aidList as $aid) {
                    $actInfo = $this->getActivity($aid);

                    // 隐藏活动券不作为活动奖励发放
                    if ($actInfo['ishide']){
                        continue;
                    }

                    $oneProp['skinList'][] = ["id" => $actInfo['id'], "name" => $actInfo['name']];
                }
            }

            if ($oneProp['id'] == 19) {//皮肤宝箱
                $oneProp['skinList'] = $chestSkinArr;
            }
            $data[] = $oneProp;
        }

        return $data;
    }
    // 批量更新基础配置
    public static function multiUpdateCon(array $data): int
    {
        $key = okeys::basicConfigKey();
        $tb = otable::basicConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT `id` FROM {$tb} WHERE 1");
        $ids = array_column($ret, 'id');

        foreach ($data as $row) {
            if (in_array($row->id, $ids)) {
                $sql = "UPDATE {$tb} SET memo='{$row->memo}',item='{$row->item}',title='{$row->title}',content='{$row->content}' WHERE id={$row->id}";
            } else {
                $sql = "INSERT INTO {$tb} (id,item,title,content,memo) VALUES (NULL,'{$row->item}','{$row->title}','{$row->content}','{$row->memo}')";
            }
            $rs = oo::commonOprDb('games')->query($sql);
            if (!$rs) {
                return -1;
            }
            oo::commonOprRedis('games')->hSet($key, $row->item . '-' . $row->title, $row->content);
        }

        return 0;
    }
    // 更新basic config json
    public static function updateConJson()
    {
        $tb = otable::basicConfig();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $temp = oo::commonOprDb('slavedb')->getAll($sql);

        $epItem = ["android", "ios", 'Url', 'getSpinAd', 'BeginnerReward', 'Game', 'onoff','Client'];

        $json = [];
        foreach ($temp as $row) {
            if (in_array($row['item'], $epItem) || in_array($row['title'], ["fbInviteSpin", "initialSpins", "repairMoney"])) {
                if ($row['item'] == 'getSpinAd') {
                    $json['getSpinAd'][$row['title']] = $row['content'];
                } else if ($row['item'] == 'android') {
                    $json['android'][$row['title']] = $row['content'];
                } else if ($row['item'] == 'ios') {
                    $json['ios'][$row['title']] = $row['content'];
                } else if ($row['item'] == 'onoff') {
                    $json['onoff'][$row['title']] = $row['content'];
                } else {
                    if ($row['title'] == "repairMoney") {
                        $json["initialCoins"] = $row['content'];
                    } else {
                        $json[$row['title']] = $row['content'];
                    }
                }
            }
        }

        $filename = 'Game' . time() . '.json';
        oo::commonOprModel("json")->SaveJson($json, $filename);
        oo::commonOprModel("json")->setStaticConfig("Game", $filename);
    }
    /**
     * 获取配置
     * @param $item
     * @param $title
     * @return bool
     * Created by: Owen
     * Created on: 2020/7/8 15:05
     */
    public function getSysCon($item,$title){
        if (empty($item) ||  empty($title)) {
            return false;
        }
        $ret = oo::commonOprRedis('games')->hGet(okeys::systemConfig(),$item.'-'.$title);
        if(!empty($ret))return $ret;
        $table = otable::systemConfig();
        $sql = "SELECT content FROM {$table} WHERE item = '{$item}' AND title = '{$title}'";
        $res = oo::commonOprDb('slavedb')->getOne($sql,MYSQLI_ASSOC);
        oo::commonOprRedis('games')->hSet(otable::systemConfig(),$item.'-'.$title,$res['content']);
        return $res['content'];
    }

    /**
     * 更新配置
     * @param $item
     * @param $title
     * @return bool
     * Created by: Owen
     * Created on: 2020/7/8 15:05
     */
    public function setSysCon($item,$title,$content){
        if (empty($item) ||  empty($title)) {
            return false;
        }
        oo::commonOprRedis('games')->hDel(okeys::systemConfig(),$item.'-'.$title);
        $table = otable::systemConfig();
        $content = addslashes($content);
        $sql = "UPDATE {$table} SET content='{$content}' WHERE item = '{$item}' AND title = '{$title}'";
        oo::commonOprDb('games')->query($sql);
        return true;
    }

    /**
     * 获取用户分组配置
     * @param int $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/22 11:11
     */
    public function getUserGroupConfig($id = 0){
        $cacheKey = okeys::UserGroupConfig();
        $cache    = oo::commonOprRedis('games')->hGet($cacheKey,$id);
        if(empty($cache)){
            $tb = otable::UserGroupConfig();
            if($id){
                $cache = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('games')->hSet($cacheKey,$id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 用户分组条件配置
     * @param $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/22 11:20
     */
    public function getUserGroupConditionConfig($id = 0){
        $cacheKey = okeys::UserGroupConditionConfig();
        $cache    = oo::commonOprRedis('games')->hGet($cacheKey,$id);
        if(empty($cache)){
            $tb = otable::UserGroupConditionConfig();
            if($id){
                $cache = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('games')->hSet($cacheKey,$id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 活动图片资源目录配置
     * @param $id
     * @return mixed
     * Created by: Hss
     * Created on: 2020/8/14 15:14
     */
    public function getActiveImgNameConfig($name = 0,$sort = true){
        $cacheKey = okeys::ActiveImgNameConfig();
        $cache    = oo::commonOprRedis('games')->hGet($cacheKey,$name);
        if(empty($cache)){
            $tb = otable::ActiveImgNameConfig();
            if($name){
                $cache = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE name='{$name}' LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('games')->hSet($cacheKey,$name,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        if(empty($name)){
        	$temp = [];
        	foreach($cache as $key => $row){
        		if($sort){
        			$temp[$row['name']] = json_decode($row['content'],1);
        		}else{
        			$cache[$key]['content'] = json_decode($row['content'],1);
        		}
        	}

        	return $sort?$temp:$cache;
        }else{
        	$cache['content'] = json_decode($cache['content'],1);
        }
        return $cache;
    }

    /**
     * 邀请奖励配置 等级区间
     * @param $id
     * @return mixed
     * Created by: Hss
     * Created on: 2020/8/17 15:19
     */
    public function getInviteRewardConfig($section_id = 0,$sid = 1){
        $cacheKey = okeys::InviteRewardConfig($sid);
        $cache    = oo::commonOprRedis('games')->hGet($cacheKey,$section_id);
        if(empty($cache)){
            $tb = otable::InviteRewardConfig();
            if($section_id){
                $cache = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE section_id={$section_id},sid = {$sid} LIMIT 1",MYSQLI_ASSOC);
            }else{
                $cache = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE sid = {$sid}",MYSQLI_ASSOC);
            }
            oo::commonOprRedis('games')->hSet($cacheKey,$section_id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 获取用户分组配置
     * @param int $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/7/22 11:11
     */
    public function getUserGroupConfig2($id = 0){
        $between   = [4=>'point', 5=>'levelId', 6=>'active', 7=>'onlineTime', 8=>'regTime', 9=>'friendNum', 10=>'friendRank', 11=>'countryRank', 12=>'worldRank', 18=>'payNum'];
        $cacheKey = okeys::UserGroupConfig(2);
        $cache    = oo::commonOprRedis('games')->hGet($cacheKey,$id);

        if(empty($cache) || $cache == '[]'){
            $tb = otable::UserGroupConfig(2);
            if($id){
                $cache = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id} LIMIT 1",MYSQLI_ASSOC);
                $cache['condition'] = json_decode($cache['condition'],true);
                $cache['signIn']    = json_decode($cache['signIn'],true) ?? [];
                foreach ($cache['condition'] as $key=>$row){
                    if(in_array($row['condition'],array_keys($between)) && $row['condition'] != 0){
                        $cache['condition'][$key][$between[$row['condition']]] = explode(',',$row[$between[$row['condition']]]);
                    }
                }
                $cache['condition'] = array_values($cache['condition']);
            }else{
                $cache = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
                foreach ($cache as $key=>$row){
                    $cache[$key]['condition'] = json_decode($row['condition'],true);
                    $cache[$key]['signIn']    = json_decode($row['signIn'],true) ?? [];
                    foreach ($cache[$key]['condition'] as $k=>$v){
                        if(in_array($v['condition'],array_keys($between)) && $v['condition'] != 0){
                            $cache[$key]['condition'][$k][$between[intval($v['condition'])]] = explode(',',$v[$between[intval($v['condition'])]]);
                        }
                    }
                    $cache[$key]['condition'] = array_values($cache[$key]['condition']);
                }
            }
            oo::commonOprRedis('games')->hSet($cacheKey,$id,json_encode($cache));
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 根据cid 获取用户分组配置
     * @param $cid
     * @return mixed
     * Created by: Owen
     * Created on: 2021/1/20 20:06
     */
    public function getUserGroupConfigByCid($cid){
        $arr = $this->getUserGroupConfig2();
        foreach ($arr as $key=>$row){
            if($cid == 5 && $row['groupId'] == 0){
                $arr[$key]['id'] = 0;
            }
            if($cid != $row['cid']){
                unset($arr[$key]);
            }
        }
        return $arr;
    }

    /**
     * 宝箱配置
     * @param $id
     * @return array|false|mixed
     * Created by: Owen
     * Created on: 2020/9/14 15:38
     */
    public function getChestConfig($id){
        $cacheKey = okeys::ChestConfig($id);
        $cache    = oo::commonOprRedis('games')->get($cacheKey);
        if(empty($cache)){
            $tb  = otable::ChestConfig();
            $cache = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE propsId={$id}",MYSQLI_ASSOC);
            $cache = json_decode($cache['reward'],true);
            oo::commonOprRedis('games')->setex($cacheKey,json_encode($cache),7*24*60*60);
        }else{
            $cache = json_decode($cache,true);
        }
        return $cache;
    }

    /**
     * 宝箱数据
     * @param $id
     * @return mixed
     * Created by: Owen
     * Created on: 2020/9/14 15:20
     */
    public function getChestData($id){
        if(in_array($id,[19,20,21])){
            $conf = $this->getChestConfig($id);
            $conf = array_column($conf,NULL,'propsId');
            $coinsNum = array_column($conf[14]['pro'],'num');
            $spinsNum = array_column($conf[15]['pro'],'num');
            $petExp   = array_column($conf[8]['pro'] ,'num');
            return [
                'cardNum'      => $conf[17]['num'],
                'jokerCardNum' => $conf[18]['num'],
                'coinsNum'     => !empty($coinsNum) ? [min($coinsNum),max($coinsNum)] : [],
                'spinsNum'     => !empty($spinsNum) ? [min($spinsNum),max($spinsNum)] : [],
                'petExp'       => !empty($petExp)   ? [min($petExp),max($petExp)]     : [],
            ];
        }
        return false;
    }

    /**
     * 签到进度配置
     * @param int $progress,
     * @param int $section_id 区间
     * @return mixed
     * Created by: Owen \ Hss
     * Created on: 2020/4/24 15:21 \ 2020/4/24 15:21
     */
    public function getSignInProgressConfig($progress = 0,$section_id = 0){
        $tb  = otable::SignInProgressConfig();
        $arr =  oo::commonOprDb('slavedb')->getAll("SELECT progress,coins,spins,props FROM {$tb} WHERE section_id = {$section_id}",MYSQLI_ASSOC);
        $progressCount = count($arr);
        if(!empty($arr)){
            foreach ($arr as $k=>$v){
                $arr[$k]['coins'] = json_decode($v['coins'],true);
                $arr[$k]['props'] = json_decode($v['props'],true);
                $arr[$k]['count'] = $progressCount;
                $cache[$v['progress']] =  json_encode($arr[$k]);
            }
            $arr = array_column($arr,null,'progress');
        }
        $data = $progress===0?$arr:$arr[$progress];
        return $data;
    }

    /**
     * 获取道具配合
     * @return mixed
     * Created by: Owen
     * Created on: 2020/12/23 16:33
     */
    public function getPropsConfig(){
        $posts = ['frombg'=>1,'lid' =>1,'sid'=>1];
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url    = $this->config->item('officialUrl');
        $config = $this->curl->req($url, $posts);
        return json_decode($config,true)['props'];
    }

    public function getUserPropsData($uid){
        $cache = oo::commonOprRedis('games')->hGetAll(okeys::UserProps($uid));
        if(!empty($cache)){
            $cacheTemp = [];
            foreach ($cache as $row){
                $cacheTemp[] = json_decode($row,true);
            }
            return $cacheTemp;
        }
        $tb  = otable::userprops($uid);
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE uid = {$uid}", MYSQLI_ASSOC);
        return $ret;
    }

    public function chestSkin(){
        $tb = otable::ChestSkinConfig(2);
        return oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} ORDER BY id",MYSQLI_ASSOC);
    }

    public function SlotWeightChangConfig(){
        $tb = otable::SlotWeightChangConfig();
        return oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE `type` IN ('stealRetWeight','stealRetWeightV2','boxRetWeight','betRetWeightV2','betRetWeight','stealLimitWeight','betBoxRetWeight')",MYSQLI_ASSOC);
    }

    public function actionSlotWeightChangConfig($type,$data){
        $table = otable::SlotWeightChangConfig();
        $data = addslashes($data);
        $sql = "UPDATE {$table} SET config='{$data}' WHERE `type`='{$type}' LIMIT 1";
        $res = oo::commonOprDb('games')->query($sql);
        if($res){
            oo::commonOprRedis('games')->delete(okeys::stealRetCfg($type));
        }
        return $res;
    }

    public function getCurMaxLevelId(){
        return intval($this->getCon('basic','curMaxLevel'))??150;//当前世界最大等级
    }

    public function getActivityActionList($type = ""){
        if(empty($type)){
            return [];
        }
        $activityConf = otable::activityConf();
        $time = time();
        $whereUcType = ' AND uc_type = 1  ';
        if( in_array($type, ['collect_jigsw'])){
            $whereUcType = '';
        }
        $sql = "SELECT  id,name,name_en  FROM {$activityConf} WHERE `type` = '{$type}' AND is_online = 1 {$whereUcType} AND end_time > {$time}";
        return oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
    }

    //数数分组 除去隐藏分组
    public function hideSSGroup($allGroup = []){
        $configSSGroupShow = oo::commonOprRedis('statistics')->hGetAll(okeys::configSSGroupShow());
        $out = [
            0 => '数数-默认分组'
        ];
        foreach($allGroup as $id => $value){
            if(!in_array($id,$configSSGroupShow)){
                $out[$id] = $value;
            }
        }
        return $out;
    }
    //==============================
    public function getActivity($aid,$db=false){
        $key = okeys::activityInfo($aid);
        $cache = oo::commonOprRedis('games')->hGetAll($key);
        if(!$cache['id']||$db){
            if(!$db){
                oo::logs()->commlog(["aid"=>$aid,"error"=>"not find actInfo"],'activity/notCfg');
            }
            $tb =otable::activityConf();
            $sql = "SELECT * FROM {$tb} WHERE id={$aid}";
            $data = oo::commonOprDb('games')->getOne($sql,1);
            if(!empty($data)){
                $cache = $data;
                oo::commonOprRedis('games')->hMset($key,$data);
                oo::commonOprRedis('games')->expire($key,oo::redisRandomExpire(31*86400));
            }
        }
        return $cache;
    }

    /**
     * Notes:获取道具数据结构
     * User: wsc
     * Time: 2021/12/15 17:09
     * @return array
     */
    public function getPropsConfigFromLocal($propsType = '')
    {
        $props = $propsType == 'func' ? oo::cfg('props_func') : oo::cfg('props');
        $chestSkin = oo::commonOprModel('config')->chestSkin();

        $chestSkinArr = [];
        foreach ($chestSkin as $oneSkin) {
            $chestSkinArr[] = ["id" => $oneSkin['id'], "name" => $oneSkin['name']];
        }

        $data = [];
        foreach ($props as $oneProp) {
            $type = $oneProp['type'] ?? '';
            if ($type == 'act') {//道具活动
                $oneProp['skinList'] = [];
                $aidList = oo::commonOprRedis('games')->hGetAll(okeys::onlineOpenActivity($oneProp['msg']));
                foreach ($aidList as $aid) {
                    $actInfo = $this->getActivity($aid);
                    $oneProp['skinList'][] = ["id" => $actInfo['id'], "name" => $actInfo['name']];
                }
            }

            if ($oneProp['id'] == 19) {//皮肤宝箱
                $oneProp['skinList'] = $chestSkinArr;
            }
            $data[] = $oneProp;
        }
        return $data;
    }

    /**
     * Notes:公共配置表读取 crazy_api_config.common_conf
     * User: wsc
     * Time: 2022/4/8 14:12
     * @param $type
     * @return array
     */
    public function getCommonConf($type){
        $tb = otable::commonConfig();
        $sql = "Select * from {$tb} where type ='{$type}'";
        $rconf = oo::commonOprDb('slavedb')->getOne($sql,1);
        return json_decode($rconf['conf'],true);
    }
    /**
     * Notes:公共配置表更新 crazy_api_config.common_conf
     * User: wsc
     * Time: 2022/4/8 14:12
     * @param $type
     * @return array
     */
    public function saveCommonConf($type,$confArr,$title="test"){
        $conf = json_encode($confArr,32);
        $tb = otable::commonConfig();
        $sql = "Select * from {$tb} where type ='{$type}'";
        $rconf = oo::commonOprDb('slavedb')->getOne($sql,1);
        if($rconf){
            $sql = "UPDATE {$tb} SET conf='".$conf."'  where type='{$type}' ";
        }else{
            $sql = "INSERT INTO {$tb}(name, type, conf) VALUES('{$title}','{$type}', '{$conf}')";
        }
        $ret = oo::commonOprDb('games')->query($sql);
        return $ret;
    }


    public function upActivtityCoinCache()
    {
        $tb = otable::ActivityCoins();
        $sql = "SELECT * FROM {$tb}";
        $data = oo::commonOprDb('games')->getAll($sql, 1);
        if (empty($data)) {
            return;
        }
        oo::commonOprRedis('games')->delete(okeys::ActivityCoins());

        $fieldArr = funs::getTableColumns($tb);
        unset($fieldArr[0]);
        $collectArr = ['signIn', 'recall', 'super_collect', 'spins_master', 'crazy_build', 'time_limit_invite'];
        $serialPackArr = ['super_serial_pack2', 'super_serial_pack3', 'super_serial_pack4'];
        $rankArr = ['rank2'];

        $allFields = array_merge($fieldArr, $collectArr, $serialPackArr, $rankArr);

        $reward=[];
        foreach ($data as $k => $v) {
            foreach ($allFields as $field) {
                if (in_array($field,$collectArr)){
                    $value=$v['collect'];
                }elseif (in_array($field,$serialPackArr)){
                    $value=$v['super_serial_pack'];
                }elseif (in_array($field,$rankArr)){
                    $value=$v['rank'];
                }else{
                    $value=$v[$field] ?? $v['collect'];
                }
                $reward[$field][$v['levelId']] = $value;
            }
        }
        foreach ($allFields as $field) {
            oo::commonOprRedis('games')->hMset(okeys::activityCoinRewardByType($field), $reward[$field]);
        }
    }

    public function updateLvBaseCoinsCache()
    {
        $tb = otable::LvCoinsConfig();
        $sql = "SELECT * FROM {$tb}";
        $data = oo::commonOprDb('games')->getAll($sql);
        if (empty($data)) {
            return;
        }

        $reward = [];
        foreach ($data as $k => $v) {
            $reward[$v['type']][$v['lv']] = $v['value'];
        }
        foreach ($reward as $type => $typeCfg) {
            oo::commonOprRedis('games')->hMset(okeys::lvBaseCoinsByType($type), $typeCfg);
        }
    }

    /**
     * 皮肤宝箱配置
     * @param $id
     * @return array|false|mixed
     * Created by: Owen
     * Created on: 2020/9/14 15:38
     */
    public function getChestSkinConfig($id){
        $cacheKey = okeys::NewChestSkinConfig($id);
        $cache    = oo::commonOprRedis('games')->hGetAll($cacheKey);
        if(empty($cache)){
            $tb    = otable::ChestSkinConfig(2);
            $data = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE id={$id}",MYSQLI_ASSOC);
            $cache['info'] = $data['reward'];
            $cache['skin'] = $id;
            $cache['skinResourceId'] = $data['skinResourceId'];
            oo::commonOprRedis('games')->hMset($cacheKey,$cache);
            oo::commonOprRedis('games')->expire($cacheKey,oo::redisRandomExpire(7*24*60*60));
//            oo::commonOprRedis('games')->setex($cacheKey,json_encode($cache),oo::redisRandomExpire(7*24*60*60));
        }
        $cache['info'] = json_decode($cache['info'],true);

        return $cache;
    }
}
