<?php

class TokenRankModel extends ActBaseModel implements ActInterface
{
    static $tokenTypes = [
        44 => "拼图碎片" ,// 44,
        45 => "玛雅转盘代币" ,// 45,
        51 => "幸运小丑代币" ,//=> 51,幸运小丑(狐狸)代币
        60 => "超级扭蛋代币" ,//=> 60,
        65 => "幸运旅途代币" ,//=> 65,
        70 => "塔罗牌代币" ,//=> 70,
        72 => "推币机代币" ,//=> 72,
        74 => "暴走兔子代币" ,//=> 74,
        77 => "星图代币" ,//=> 77,
        79 => "西部矿洞代币" ,//=> 79,
    ];

    function serializeShowConf(array &$actConfig)
    {

    }

    function formatActData(array &$actConfig)
    {

        if (empty(intval($actConfig['tokenRankBasicConfig']['minScore']))) $this->response(1, '保存失败，上榜门槛积分配置为空');
        if (empty($actConfig['tokenRankBasicConfig']['tokens'])) $this->response(1, '保存失败，代币积分配置为空');

        // 基础配置
        $tokens = [];
        foreach ($actConfig['tokenRankBasicConfig']['tokens'] as $tokenConf){
            if(in_array($tokenConf['tokenType'], array_keys($tokens)))$this->response(1, '保存失败，代币积分配置重复', $actConfig['tokenRankBasicConfig']);
            if (empty($tokenConf['score'])) $this->response(1, '保存失败，代币积分配置为空');
            $tokens[$tokenConf['tokenType']] = $tokenConf['score'];
        }
        $actConfig['reward_conf'] = [
            'minScore' => intval($actConfig['tokenRankBasicConfig']['minScore']),
            'tokens' => $tokens,
        ];
        unset( $actConfig['tokenRankBasicConfig']);

        // 奖励配置
        if (empty($actConfig['tokenRankConfig'])) $this->response(1, '保存失败，奖励配置为空');
        foreach ($actConfig['tokenRankConfig'] as $idx => $item) {
            if(empty($item['stages']))$this->response(__LINE__, '保存失败，阶段奖励配置为空');
            foreach ($item['stages'] as $stage){
                if(empty($stage['stepnum']))$this->response(__LINE__, '保存失败，阶段值配置为空');
                if(empty($stage['prize']))$this->response(__LINE__, '保存失败，阶段奖励配置为空');

            }
            if(empty($item['ranks']))$this->response(__LINE__, '保存失败，排行奖励配置为空');
            foreach ($item['ranks'] as $stage){
                if(empty($stage['rankPos']))$this->response(__LINE__, '保存失败，排名值配置为空');
                if(empty($stage['prize']))$this->response(__LINE__, '保存失败，排名奖励配置为空');

            }
        }
        $actConfig['pro'] = $actConfig['tokenRankConfig'];
        unset( $actConfig['tokenRankConfig']);

        // 分房配置
        $roomAllotConf = [];
        if (empty($actConfig['tokenRankRoomConfig'])) $this->response(1, '保存失败，分房配置为空');
        foreach ($actConfig['tokenRankRoomConfig'] as $roomConf){
            if(empty($roomConf['stages']))$this->response(1, '保存失败，分房配置, 体力区间配置为空');

            foreach ($roomConf['stages'] as $stage){
                if(empty($stage['spinsEnd']))$this->response(1, '保存失败，分房配置, 体力上限配置为空', $stage);
                if(empty($stage['numLimit']))$this->response(1, '保存失败，分房配置, 房间人数配置为空', $stage);
            }
            $roomAllotConf[] = [
                'lvStart' => $roomConf['lv_start'] ,
                'lvEnd' => $roomConf['lv_end'] ,
                'stages' => $roomConf['stages'] ,
            ];
        }
        $actConfig['extraData'] = [
            'roomAllotConf' => $roomAllotConf
        ];
        unset( $actConfig['tokenRankRoomConfig']);

//        $this->response(__LINE__, __LINE__, $actConfig);
    }

    function writeActCache(array $actConfig)
    {
        $conditionKeys = okeys::activityConditionKeys($actConfig['aid']);
        $stageRewardKeys = okeys::activityRewardsStageKeys($actConfig['aid']);
        $rewardInfo = json_decode($actConfig['reward_pro'], true) ?? [];
        $expireTime = ActBaseModel::getActCacheExpireTime($actConfig['end_time']);#redis最少一分钟
        foreach ($rewardInfo as $idx1 => $item1) {
            $condition = $this->getStageConditionLvSpinsShushu($item1, $item1, $item1);
            $stageKey = $idx1;
            $stageConditions = array_values($condition);
            oo::commonOprRedis('games')->hset($conditionKeys, $stageKey, json_encode($stageConditions, 32));
            oo::commonOprRedis('games')->hset($stageRewardKeys, $stageKey, json_encode([
                'stages' => $item1['stages'] ,
                'ranks' => $item1['ranks'] ,
            ], 32));
        }

        oo::commonOprRedis('games')->expireAt($conditionKeys, oo::redisRandomExpire($expireTime));
        oo::commonOprRedis('games')->expireAt($stageRewardKeys, oo::redisRandomExpire($expireTime));
    }

    function importActData(array &$basicConfig, $sheetArray)
    {
        $basicConfig['tokenRankBasicConfig'] = [
            'minScore' => 0,
            'tokens' => [],
        ];
        $sheetIdx = 0;
        $basicSheet = $sheetArray[$sheetIdx] ?? [];
        $extraConf = $sheetArray[++$sheetIdx] ?? [];
        $stageMappingSheet = $sheetArray[++$sheetIdx] ?? [];
        $rewardsSheet      = $sheetArray[++$sheetIdx] ?? [];
        $rankRewardsSheet      = $sheetArray[++$sheetIdx] ?? [];
        $roomConfSheet      = $sheetArray[++$sheetIdx] ?? [];

        // 基础配置
        foreach ($basicSheet as $item){
            if ($item[0] != '上榜门槛积分')continue;
            $basicConfig['tokenRankBasicConfig']['minScore'] = intval($item[1]);
        }
        $tokenTextMap = array_flip(self::$tokenTypes);
        for ($j = 1; $j < count($extraConf); $j++) {
            list($tokenText, $score) = $extraConf[$j];
            if(empty($tokenTextMap[$tokenText]))$this->response(__LINE__, "代币：{$tokenText} 不存在");
            $basicConfig['tokenRankBasicConfig']['tokens'][] = [
                'tokenType' =>$tokenTextMap[$tokenText],
                'score' =>intval($score),
            ];
        }

        //
        $rewardsConfig = $this->parseLvSpinsShushuStagesMappingV1($stageMappingSheet);
        $rewardsConfig = array_column($rewardsConfig, null, 'id');
        // 阶段奖励
        foreach ($rewardsSheet as $k => $item){
            $lineNum = $k + 1;
            $item = array_filter($item);
            if(empty($k) || empty($item))continue;
            list($idx, $stage, $stepnum) = $item;
            if(empty($rewardsConfig[$idx]))$this->response(__LINE__, "第{$lineNum}行,唯一ID：{$idx} 不存在");
            $rewardsConfig[$idx]['stages'] = $rewardsConfig[$idx]['stages'] ?? [];
            $stageCnt = count($rewardsConfig[$idx]['stages']);
            $rewardsConfig[$idx]['stages'][] = [
                'stage' => $stageCnt + 1,
                'stepnum' => $stepnum,
                'prize' => $this->parseLineRewards(array_slice($item, 3), $lineNum),
            ];
        }

        // 排行奖励
        foreach ($rankRewardsSheet as $k => $item){
            $lineNum = $k + 1;
            $item = array_filter($item);
            if(empty($k) || empty($item))continue;
            list($idx, $rank, $rankPos) = $item;
            if(empty($rewardsConfig[$idx]))$this->response(__LINE__, "第{$lineNum}行,唯一ID：{$idx} 不存在");
            $rewardsConfig[$idx]['ranks'] = $rewardsConfig[$idx]['ranks'] ?? [];
            $stageCnt = count($rewardsConfig[$idx]['ranks']);
            $rewardsConfig[$idx]['ranks'][] = [
                'stage' => $stageCnt + 1,
                'rankPos' => $rankPos,
                'prize' => $this->parseLineRewards(array_slice($item, 3), $lineNum),
            ];
        }
        $basicConfig['tokenRankConfig'] = array_values($rewardsConfig);

        $roomConf = [];
        foreach ($roomConfSheet as $k => $item) {
            $item = array_filter($item);
            if(empty($k) || empty($item))continue;
            $stageKey = "{$item[0]}_{$item[1]}";
            $roomConf[$stageKey] = $roomConf[$stageKey] ?? [
                'lv_start' => intval($item[0]),
                'lv_end' => intval($item[1]),
                'stages' => [],
            ];
            $roomConf[$stageKey]['stages'][] = [
                "spinsStart" => intval($item[2]),
                "spinsEnd" => intval($item[3]),
                "numLimit" => intval($item[4]),
            ];
        }
        $basicConfig['tokenRankRoomConfig'] = array_values($roomConf);
//        $this->response(__LINE__, __LINE__, $basicConfig);
    }

    function getActBasicConfig(): array
    {
        return [
            'tokenMap' => self::$tokenTypes
        ];
    }
}