<?php

class LuckFoxActModel extends ActBaseModel implements ActInterface
{
    function formatActData(array &$actConfig)
    {

        foreach ($actConfig['luckyFoxConfig'] as &$lvItem){
            if(empty($lvItem['stages']))$this->response(-1, "存在空数值");
            foreach ($lvItem['stages'] as &$spinItem){
                if(empty($spinItem['list']))$this->response(-1, "存在空数值");

                $formatConf = [];
                foreach ($spinItem['list'] as $item){
                    if (empty($item['grid']) || empty($item['layer']) || empty($item['weight']) || empty($item['prize'])) {
                        $this->response(-1, "存在空数值");
                    }
                    $formatConf[$item['grid']] = $formatConf[$item['grid']] ?? [];
                    $formatConf[$item['grid']][] = $item;
                }
                $spinItem['list'] = array_values($formatConf);
            }
        }
        $actConfig['reward_info'] = $actConfig['luckyFoxConfig'];
        unset($actConfig['luckyFoxConfig']);
        $this->saveTokenGoods($actConfig, 'extraData');
    }

    function writeActCache(array $actConfig)
    {
        $conditionKeys = okeys::activityConditionKeys($actConfig['aid']);
        $stageRewardKeys = okeys::activityRewardsStageKeys($actConfig['aid']);
        $stageExtraConfKeys = okeys::activityStageExtraConfigKeys($actConfig['aid']);
        $rewardInfo = json_decode($actConfig['reward_info'], true);
        $extraData = json_decode($actConfig['extraData'], true);
        foreach ($rewardInfo as $idx1 => $item1) {
            foreach ($item1['stages'] as $idx2 => $item2) {
                $stageKey = "{$idx1}_{$idx2}";

                $stageConditions = $this->getStageConditionLvSpins($item1, $item2);
                oo::commonOprRedis('games')->hset($conditionKeys, $stageKey, json_encode($stageConditions, 32));
                oo::commonOprRedis('games')->hset($stageRewardKeys, $stageKey, json_encode($item2['list'], 32));
                oo::commonOprRedis('games')->hset($stageExtraConfKeys, $stageKey, json_encode(['tokenGoods' =>$extraData[$stageKey] ?? []], 32));
            }
        }
        $expireTime = max($actConfig['end_time'], time() + 60);#redis最少一分钟
        oo::commonOprRedis('games')->expireAt($conditionKeys, oo::redisRandomExpire($expireTime));
        oo::commonOprRedis('games')->expireAt($stageRewardKeys, oo::redisRandomExpire($expireTime));
        oo::commonOprRedis('games')->expireAt($stageExtraConfKeys, oo::redisRandomExpire($expireTime));
        return true;
    }

    function serializeShowConf(array &$actConfig)
    {
    }

    function importActData(array &$basicConfig, $sheetArray)
    {

        $sheetIdx = 0;
        $stagesMappingSheet = $sheetArray[++$sheetIdx] ?? [];
        $stagesRewardsSheet = $sheetArray[++$sheetIdx] ?? [];
        $tokenGoodsSheet = $sheetArray[++$sheetIdx] ?? [];

        list($activityConfig, $idxMapping) = $this->parseLvSpinsStagesMapping($stagesMappingSheet);

        foreach ($stagesRewardsSheet as $k => $item) {
            $filterLine = array_filter($item);
            if (empty($filterLine)) continue;
            $line = $k + 1;
            if ($k == 0) continue;

            list($idx, $grid, $layer, $weight) = $item;


            if (empty($idxMapping[$idx])) $this->response(-1, "第{$line}行,唯一id:{$idx} 无对应关系");    #奖励不能为空
            list($lvStage, $spinsStage) = $idxMapping[$idx];

            $rewardStage = count($activityConfig[$lvStage]['stages'][$spinsStage]['list']) + 1;

            $rewardsTemp = $this->parseLineRewards(array_slice($item, 4));
            if (empty($rewardsTemp)) $this->response(-1, "第{$line}行,奖励不能为空");    #奖励不能为空
            $activityConfig[$lvStage]['stages'][$spinsStage]['list'][$rewardStage] = [
                'grid' => $grid,
                'layer' => $layer,
                'weight' => $weight,
                'prize' => $rewardsTemp,
            ];
        }

        $basicConfig['luckyFoxConfig'] = $activityConfig;

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

    private function parseExtraSheet(array $sheet): array
    {
        $baseConfig = ["openLv" => 0, "spinsRatio" => 0, "resultMul" => []];
        foreach ($sheet as $item) {
            $label = trim($item[0]);
            if (empty($label)) {
                continue;
            }
            $value = $item[1];
            switch ($label) {
                case '开放等级':
                    $baseConfig['openLv'] = $value;
                    break;
                case '任务可选':
                    $baseConfig['canSelectTask'] = $value == '是' ? 1 : 0;
                    break;
                case '体力存量系数':
                    $baseConfig['spinsRatio'] = $value;
                    break;
                case '豹子倍数':
                    $baseConfig['resultMul'][] = ["type" => "AAA", "mul" => $value];
                    break;
                case '顺子倍数':
                    $baseConfig['resultMul'][] = ["type" => "ABC", "mul" => $value];
                    break;
                case '对子倍数':
                    $baseConfig['resultMul'][] = ["type" => "AA", "mul" => $value];
                    break;
            }
        }

        return $baseConfig;
    }

    private function parsePrdSheet(array $sheet): array
    {
        $prdConf = [];
        for ($i = 1; $i < count($sheet); $i++) {
            $row = $sheet[$i];
            if (empty(array_filter($row))) {
                continue;
            }

            $line = $i + 1;
            list($prdLv, $co1, $co2) = $row;
            if ($prdLv != count($prdConf) + 1) $this->response(-1, "第{$line}行,prd配置等级不连续");

            $prdConf[$prdLv] = [$co1, $co2];
        }

        return $prdConf;
    }

    private function parseStageSheet(array $sheet): array
    {
        $rewardsConfig = [];

        for ($i = 1; $i < count($sheet); $i++) {
            $row = $sheet[$i];
            if (empty(array_filter($row))) {
                continue;
            }

            list($idx, $lvMin, $lvMax, $yMin, $yMax, $ssGroup) = $row;
            $yKey = "{$yMin}-$yMax";
            $lvKey = "{$lvMin}-$lvMax";

            $lvIdx = $this->getGroupMappingIdx(CONDITION_TYPE_LV, $lvKey);
            $yIdx = $this->getGroupMappingIdx(CONDITION_TYPE_COIN_Y, $yKey, $lvIdx);
            $ssIdx = $this->getGroupMappingIdx(CONDITION_TYPE_SHUSHU, $ssGroup, "{$yIdx}_{$lvIdx}");

            if (empty($rewardsConfig[$lvIdx]))
                $rewardsConfig[$lvIdx] = [
                    'stages' => [],
                    'start' => $lvMin,
                    'end' => $lvMax,
                ];
            if (empty($rewardsConfig[$lvIdx]['stages'][$yIdx]))
                $rewardsConfig[$lvIdx]['stages'][$yIdx] = [
                    'stages' => [],
                    'start' => $yMin,
                    'end' => $yMax,
                ];

            $shushus = $this->parseShushuGroups($ssGroup);
            if (empty($rewardsConfig[$lvIdx]['stages'][$yIdx]['stages'][$ssIdx]))
                $rewardsConfig[$lvIdx]['stages'][$yIdx]['stages'][$ssIdx] = [
                    'idx' => $idx,
                    'stages' => [],
                    'shushu' => $shushus,
                ];
        }

        return $rewardsConfig;
    }

    private function parseRewardSheet(array $sheet): array
    {
        $rewardArrMap = [];

        # 解析阶段奖励配置
        $taskTypeMap = [
            1 => '投掷骰子',
            2 => '获得金币',
            3 => 'HUGE WIN',
            4 => '在对子中获得金币' ,
            5 => '在顺子中获得金币' ,
            6 => '在豹子中获得金币' ,
        ];

        for ($i = 1; $i < count($sheet); $i++) {
            $row = $sheet[$i];
            if (empty(array_filter($row))) {
                continue;
            }
            $line = $i + 1;

            list($idx, $stageIdx, $taskStr, $target, $betStr) = $row;

            $prize = $this->parseLineRewards(array_slice($row, 5), $line);
            if (empty($prize)) $this->response(-1, "第{$line}行,奖励不能为空");    #奖励不能为空

            $taskType = array_search($taskStr, $taskTypeMap);
            if (empty($taskType)) $this->response(-1, "任务类型不存在：{$taskStr},line:$line," . __LINE__);

            $bet = explode(',', strtr($betStr, ['，' => ',', ' ' => '']));
            $bet = array_filter($bet);

            $rewardArrMap[$idx][] = [
                'id' => $stageIdx,
                'taskType' => $taskType,
                'target' => $target,
                'prize' => $prize,
                'bet' => $bet,
            ];
        }

        return $rewardArrMap;
    }

    private function parseRankRewardSheet(array $sheet): array
    {
        $rewardArrMap = [];

        for ($i = 1; $i < count($sheet); $i++) {
            $row = $sheet[$i];
            if (empty(array_filter($row))) {
                continue;
            }
            $line = $i + 1;

            list($idx, $rankPos) = $row;

            $prize = $this->parseLineRewards(array_slice($row, 2), $line);
            if (empty($prize)) $this->response(-1, "第{$line}行,奖励不能为空");    #奖励不能为空


            $rewardArrMap[$idx][] = [
                'rankPos' => $rankPos,
                'prize' => $prize,
            ];
        }
        return $rewardArrMap;
    }

    private function packageConf(array $extraConf, array $prdConf, array $stageConf, array $rewardConf, array $rankConf): array
    {
        $luckyDiceConf = [];

        $luckyDiceConf['extraConf'] = $extraConf;
        $luckyDiceConf['prdConf'] = $prdConf;

        foreach ($stageConf as &$item) {
            foreach ($item['stages'] as &$item2) {
                foreach ($item2['stages'] as &$item3) {
                    $id = $item3['idx'];
                    unset($item3['idx']);

                    $item3['stages'] = [
                        'tasks' => $rewardConf[$id] ?? [],
                        'ranks' => $rankConf[$id] ?? [],
                    ];
                    if (empty($item3['stages']['tasks'])) {
                        $this->response(-1 * __LINE__, "唯一ID:{$id}, 任务配置为空");
                    }
                    if (empty($item3['stages']['ranks'])) {
                        $this->response(-1 * __LINE__, "唯一ID:{$id}, 排行配置为空");
                    }
                }
            }
        }
        $luckyDiceConf['rewardConf'] = $stageConf;

        return $luckyDiceConf;
    }

}