<?php

class RunningRabbitActModel extends ActBaseModel implements ActInterface
{
    function formatActData(array &$actConfig)
    {
        $config = $actConfig['runningRabbitConfig'];
        unset($actConfig['runningRabbitConfig']);
        $formattedConfig = [];
        foreach ($config as  $lvIdx => &$lvItem){

            if (empty($lvItem['stages']))$this->response(__LINE__, '层级配置为空', $lvItem);
            foreach ($lvItem['stages'] as  $spinsIdx => &$spinsItem){

                if (empty($spinsItem['stages']['levels']))$this->response(__LINE__, '关卡配置为空', $spinsItem);
                foreach ($spinsItem['stages']['levels'] as  &$level){

                    if (empty($level['grids']))$this->response(__LINE__, '格子配置为空', $spinsItem);
                    $grids = [];
//                    jsonDump($level);
                    foreach ($level['grids'] as $grid){
                        if(empty($grids[$grid['grid']])){
                            $gridIdx =  count($grids);
                            $grids[$grid['grid']] = [];
                        }else{
                            $gridIdx =  $grids[$grid['grid']][0]['grid'];
                        }

                        $oppositeGrid = 0;
                        if($gridIdx < 9)$oppositeGrid = $gridIdx + 8;

                        if ($gridIdx < 8 && empty($grid['weight']))$this->response(__LINE__, '权重配置为空', $grids);
//                        if (empty($grid['prize']))$this->response(__LINE__, '奖励配置为空', $grids);


                        $grids[$grid['grid']][] = [
                            "grid" => $gridIdx,
                            "layer" => count($grids[$grid['grid']]),
                            "weight" =>  intval($grid['weight']),
                            "bonus" => boolval( $grid['bonus']),
                            "spendLowest" =>  intval($grid['spendLowest']),
                            "oppositeGrid" =>  $oppositeGrid,
                            "prize" => $grid['prize'] ?? [],
                            "color" => intval($grid['color']),
                        ];
                    }

                    if ( count($grids) < 16 )$this->response(__LINE__, '格子数小于16', $grids);
                    $level['grids'] = array_values($grids);
                }
                $spinsItem['stages']['levels'] = array_values($spinsItem['stages']['levels']);

                $progressTmp = [];
                foreach ($spinsItem['stages']['progress'] as  $progressType => $progress){
                    if (!empty($progress['config'])){
                        $progressTmp[$progressType] = $progress;
                    }
                }
                $spinsItem['stages']['progress'] = $progressTmp;

                $formattedConfig["{$lvIdx}_{$spinsIdx}"] = [
                    'lvStart' => $lvItem['lvStart'],
                    'lvEnd' => $lvItem['lvEnd'],

                    'spinsStart' => $spinsItem['spinsStart'],
                    'spinsEnd' => $spinsItem['spinsEnd'],

                    'stages' => $spinsItem['stages'],
                ];
            }
        }
//        jsonDump($formattedConfig);
        $this->saveTokenGoods($actConfig, 'extraData');
        $actConfig['reward_info'] = $formattedConfig;
    }

    function writeActCache(array $actConfig)
    {
        $conditionKeys = okeys::activityConditionKeys($actConfig['aid']);
        $stageRewardKeys = okeys::activityRewardsStageKeys($actConfig['aid']);
        $stageExtraConfKeys = okeys::activityStageExtraConfigKeys($actConfig['aid']);
        $rewardConf = json_decode($actConfig['reward_info'], true);
        $extraData = json_decode($actConfig['extraData'], true);

        foreach ($rewardConf as $idx => $item) {
            $condition = $this->getStageConditionLvSpins($item, $item);
            oo::commonOprRedis('games')->hset($stageRewardKeys, $idx, json_encode($item['stages'], 32));
            oo::commonOprRedis('games')->hset($conditionKeys, $idx, json_encode($condition, 32));
            oo::commonOprRedis('games')->hset($stageExtraConfKeys, $idx, json_encode(['tokenGoods' =>$extraData[$idx] ?? []], 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)
    {

        $rewardsConfig = [];
        $actConfig['reward_info'] = json_decode($actConfig['reward_info'], true);
        foreach ($actConfig['reward_info'] as $item){
            $lvKey = "{$item['lvStart']}-{$item['lvEnd']}";
            $spinsKey = "{$item['spinsStart']}-{$item['spinsEnd']}";

            $lvIdx = $this->getGroupMappingIdx(CONDITION_TYPE_LV, $lvKey);
            $spinsIdx = $this->getGroupMappingIdx(CONDITION_TYPE_SPINS, $spinsKey, $lvIdx);

            if (empty($rewardsConfig[$lvIdx]))
                $rewardsConfig[$lvIdx] = [
                    'stages' => [],
                    'lvStart' => $item['lvStart'],
                    'lvEnd' => $item['lvEnd'],
                ];
            if (empty($rewardsConfig[$lvIdx]['stages'][$spinsIdx]))
                $rewardsConfig[$lvIdx]['stages'][$spinsIdx] = [
                    'stages' => [
                        'levels' => [],
                        'progress' => $item['stages']['progress'],
                    ],
                    'spinsStart' =>  $item['spinsStart'],
                    'spinsEnd' => $item['spinsEnd'],
                ];

            foreach ($item['stages']['levels'] as $level){
                $grids = [];
                foreach ($level['grids'] as $grid){
                    foreach ($grid as $layer){
                        $layer['bonus'] = intval($layer['bonus']);
                        $grids[] = $layer;
                    }
                }
                $rewardsConfig[$lvIdx]['stages'][$spinsIdx]['stages']['levels'][] = $grids;
            }
        }
        $actConfig['reward_info'] = json_encode($rewardsConfig);
    }

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

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

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

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

            list($idx, $level, $grid, $weight, $spendLowest, $bonus) = $item;


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

            $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['levels'] = $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['levels'] ?? [];
            $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['levels'][$level] = $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['levels'][$level] ?? [
                'level' => count($activityConfig[$lvStage]['stages'][$spinsStage]['stages']['levels']) + 1,
                'grids' => [],
            ];

            $rewardsTemp = $this->parseLineRewards(array_slice($item, 6));
//            if (empty($rewardsTemp)) $this->response(-1, "第{$line}行,奖励不能为空");
            $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['levels'][$level]['grids'][] = [
                "grid"=>    $grid,
                "layer"=>   0,
                "weight"=>  $weight,
                "spendLowest"=> $spendLowest,
                "prize"=>   $rewardsTemp,
                "color"=>   1,
                "bonus"=>  boolval($this->parseYesOrNo($bonus)),
                "oppositeGrid"=> 0,
            ];
        }

        $this->parseProgressSheet($activityConfig, $idxMapping, $progressSheet);

        $basicConfig['runningRabbitConfig'] = $activityConfig;
        $this->formatTokenGoodsSheet($basicConfig, $tokenGoodsSheet, $idxMapping);

    }

    public function parseProgressSheet(array &$activityConfig, $idxMapping, $progressSheet, $type = 0)
    {

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

            list($idx, $target) = $item;


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


            $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['progress'][$type] = $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['progress'][$type] ?? [
                'color' => 1,
                'config' => [],
            ];


            $rewardsTemp = $this->parseLineRewards(array_slice($item, 2));
            if (empty($rewardsTemp)) $this->response(-1, "第{$line}行,奖励不能为空");
            $activityConfig[$lvStage]['stages'][$spinsStage]['stages']['progress'][$type]['config'][] = [
                "stage" => count($activityConfig[$lvStage]['stages'][$spinsStage]['stages']['progress'][$type]['config']) + 1,
                "target" =>$target,
                "prize" =>$rewardsTemp
            ];
        }
    }
}