<?php

class TarotActModel extends ActBaseModel implements ActInterface
{

    function formatActData(array &$actConfig)
    {
        if (empty($actConfig['pinataRewardConfig'])) $this->response(-1, '保存失败，奖励配置为空');
        foreach ($actConfig['pinataRewardConfig'] as $lvIdx => &$lvItem) {
            if (empty($lvItem['stages'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间配置为空");

            foreach ($lvItem['stages'] as $spinIdx => &$spinItem) {
                if (empty($spinItem['stages'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间配置为空");

                foreach ($spinItem['stages'] as $shushuIdx => &$shushuItem) {
                    if (empty($shushuItem['shushu'])) $shushuItem['shushu'] = [0];
                    if (empty($shushuItem['collect'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，阶段配置为空");
                    if (empty($shushuItem['pinata'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，关卡配置为空");
                    foreach ($shushuItem['pinata'] as $stageIdx => &$stageItem) {
                        if (empty($stageItem['rewards'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，第{$stageIdx}关，塔罗牌配置为空");
                        $bonusCNt = 0;
                        foreach ($stageItem['rewards'] as $pIdx => &$pItem) {
                            $pIdx++;
                            $pItem['reward'] = @json_decode(urldecode($pItem['reward']), true) ?? [];
                            switch ($pItem['type']) {
                                case PINATA_REWARD_TYPE_BONUS:
                                    $bonusCNt++;
                                case PINATA_REWARD_TYPE_NORMAL:
                                    if (empty($pItem['reward']))
                                        $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，第{$stageIdx}关，第{$pIdx}个塔罗牌 非纪念品奖励配置为空");
                                    break;
                                case PINATA_REWARD_TYPE_COLLECTS:
                                    if (empty($pItem['collect_num']))
                                        $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，第{$stageIdx}关，第{$pIdx}个塔罗牌 纪念品数量配置为空");
                                    break;
                                default:
                                    $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，第{$stageIdx}关，第{$pIdx}个塔罗牌 奖励类型异常：{$pItem['type']}");
                                    break;
                            }
                        }

                    }

                    foreach ($shushuItem['collect'] as $cIdx => &$cItem) {
                        $cItem['rewards'] = @json_decode(urldecode($cItem['rewards']), true) ?? [];
                        if (empty($cItem['target'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，第{$cIdx}阶段 阶段值为空");
                        if (empty($cItem['rewards'])) $this->response(-1, "保存失败，第{$lvIdx}层等级区间,第{$spinIdx}层体力区间,第{$shushuIdx}层数数区间，第{$cIdx}阶段 奖励配置为空");
                    }
                }
            }
        }
        $actConfig['extraData'] = $actConfig['pinataRewardConfig'];
        unset($actConfig['pinataRewardConfig']);

        $this->saveTokenGoods($actConfig, 'reward_conf');
    }

    function writeActCache(array $actConfig)
    {
        $conditionKeys = okeys::activityConditionKeys($actConfig['aid']);
        $stageRewardKeys = okeys::activityRewardsStageKeys($actConfig['aid']);
        $stageExtraConfKeys = okeys::activityStageExtraConfigKeys($actConfig['aid']);
        $stageConfig = json_decode($actConfig['extraData'], true) ?? [];
        $extraData = json_decode($actConfig['reward_conf'], true);
        $expireTime = max($actConfig['end_time'], time() + 60);#redis最少一分钟
        foreach ($stageConfig as $idx1 => $item1) {
            $condition = [
                CONDITION_TYPE_LV => [
                    'shushu' => [],
                    'start' => $item1['start'],
                    'end' => $item1['end'],
                    'type' => CONDITION_TYPE_LV,
                ],
            ];
            foreach ($item1['stages'] as $idx2 => $item2) {
                $condition[CONDITION_TYPE_SPINS] = [
                    'shushu' => [],
                    'start' => $item2['start'],
                    'end' => $item2['end'],
                    'type' => CONDITION_TYPE_SPINS,
                ];

                foreach ($item2['stages'] as $idx3 => $item3) {
                    $condition[CONDITION_TYPE_SHUSHU] = [
                        'shushu' => $item3['shushu'],
                        'start' => 0,
                        'end' => 0,
                        'type' => CONDITION_TYPE_SHUSHU,
                    ];

                    $stageKey = "{$idx1}_{$idx2}_{$idx3}";
                    $stageConditions = array_values($condition);
                    unset($item3['shushu']);
                    oo::commonOprRedis('games')->hset($conditionKeys, $stageKey, json_encode($stageConditions, 32));
                    oo::commonOprRedis('games')->hset($stageRewardKeys, $stageKey, json_encode($item3, 32));
                    oo::commonOprRedis('games')->hset($stageExtraConfKeys, $stageKey, json_encode(['tokenGoods' =>$extraData[$stageKey] ?? []], 32));
                }
            }
        }
        oo::commonOprRedis('games')->expireAt($conditionKeys, oo::redisRandomExpire($expireTime));
        oo::commonOprRedis('games')->expireAt($stageRewardKeys, oo::redisRandomExpire($expireTime));
        oo::commonOprRedis('games')->expireAt($stageExtraConfKeys, oo::redisRandomExpire($expireTime));
    }

    function serializeShowConf(array &$actConfig)
    {
    }

    function importActData(array &$basicConfig, $sheetArray)
    {
        $gashTypeMap = ["普通" => 0, "大奖" => 1, "幸运蛋" => 2];
        $sheetIdx = 0;
        $stagesMappingArray = $sheetArray[++$sheetIdx] ?? [];
        $pinataRewardsArray = $sheetArray[++$sheetIdx] ?? [];
        $stagesRewardsArray = $sheetArray[++$sheetIdx] ?? [];
        $tokenGoodsArray = $sheetArray[++$sheetIdx] ?? [];
        list($rewardsConfig, $idxMapping) = $this->parseLvSpinsShushuStagesMapping($stagesMappingArray);

        $rewardTypes = [
            '大奖' => PINATA_REWARD_TYPE_BONUS,
            '纪念品' => PINATA_REWARD_TYPE_COLLECTS,
            '通用奖励' => PINATA_REWARD_TYPE_NORMAL,
        ];
        foreach ($pinataRewardsArray as $k => $item) {
            $filterLine = array_filter($item);
            if (empty($filterLine)) continue;
            $line = $k + 1;
            if ($k == 0) continue;
            $rewardBasic = array_slice($item, 0, 7);
            $rewardsLine = array_slice($item, 7);
            list($idx, $stageIdx, $pinataIdx, $rewardType, $weight, $min_token_spend, $collect_num) = $rewardBasic;
            if (empty($rewardTypes[$rewardType])) $this->response(-1 * __LINE__, "第{$line}行,奖励类型:{$rewardType}不存在");
            $rewardType = $rewardTypes[$rewardType];
            @list($lvIdx, $spinsIdx, $ssIdx) = $idxMapping[$idx];
            if (empty($rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx])) $this->response(-1 * __LINE__, "第{$line}行,分组映射id:{$idx}不存在");
            if (empty($rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['pinata'][$stageIdx]))
                $rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['pinata'][$stageIdx] = [
                    'stage' => $stageIdx,
                    'rewards' => [],
                ];
            $stageCnt = count($rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['pinata']);
            if ($stageCnt + 1 != $stageIdx && $stageCnt != $stageIdx) $this->response(-1 * __LINE__, "第{$line}行,关卡序号不连续", [$stageCnt, $stageIdx]);
            $pinataCnt = count($rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['pinata'][$stageIdx]['rewards']);
            if ($pinataCnt + 1 != $pinataIdx) $this->response(-1 * __LINE__, "第{$line}行,皮纳塔序号不连续");

            $rewardsTemp = $this->parseLineRewards($rewardsLine, $line);

            $rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['pinata'][$stageIdx]['rewards'][] = [
                'id' => $pinataIdx,
                'type' => $rewardType,
                'weight' => $weight,
                'min_token_spend' => $min_token_spend,
                'collect_num' => $collect_num,
                'reward' => urlencode(json_encode($rewardsTemp)),
            ];
        }

        # 解析阶段奖励
        foreach ($stagesRewardsArray as $k => $item) {
            $filterLine = array_filter($item);
            if (empty($filterLine)) continue;
            $line = $k + 1;
            if ($k == 0) continue;
            $rewardBasic = array_slice($item, 0, 3);
            $rewardsLine = array_slice($item, 3);

            list($idx, $stageIdx, $target) = $rewardBasic;
            @list($lvIdx, $spinsIdx, $ssIdx) = $idxMapping[$idx];
            if (empty($rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx])) $this->response(-1 * __LINE__, "阶段奖励配置，第{$line}行,分组映射id:{$idx}不存在");

            $stageCnt = count($rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['collect']);
            if ($stageCnt + 1 != $stageIdx) $this->response(-1 * __LINE__, "阶段奖励配置，第{$line}行,阶段序号不连续");
            $rewardsTemp = $this->parseLineRewards($rewardsLine, $line);

            $rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages'][$ssIdx]['collect'][$stageIdx] = [
                'stage' => $stageIdx,
                'target' => $target,
                'rewards' => urlencode(json_encode($rewardsTemp)),
            ];
        }

        $basicConfig['pinataRewardConfig'] = $rewardsConfig;

//        $this->formatTokenGoodsSheet($basicConfig, $tokenGoodsArray, $idxMapping);
    }

}