<?php

class OnePlusActModel extends ActBaseModel implements ActInterface
{
    public $actType = '';
    public $goodsNumMap = [
        ONE_PLUS_GIFT => 2,
        ONE_PLUS_TWO => 3,
        ONE_PLUS_THREE => 4,
        ONE_PLUS_SIX => 7,
    ];

    public $extraConfigFieldMapping = [
        '最大购买次数' => 'maxNum',
    ];
    public function __construct($type)
    {
        parent::__construct();
        $this->actType = $type;
    }

    function formatActData(array &$actConfig)
    {
        $config = $actConfig['onePlusConfig'];
        if (empty($config))$this->response(__LINE__, '配置异常');
        foreach ($config as $lvIdx => &$lvItem){
            if (empty($lvItem['stages']))$this->response(__LINE__, "第{$lvIdx}层体力层配置为空", [$lvItem]);

            foreach ($lvItem['stages'] as $ssIdx => &$ssItem){
                if (empty($ssItem['stages']))$this->response(__LINE__, "第{$lvIdx}层体力层,第{$ssIdx}层数数层配置为空", [$ssItem]);

                $goodsNum = count($ssItem['stages']);
                if ($goodsNum != $this->goodsNumMap[$this->actType])
                    $this->response(__LINE__, "第{$lvIdx}层体力层,第{$ssIdx}层数数层,奖励数异常：{$goodsNum} ≠ {$this->goodsNumMap[$this->actType]}", [$ssItem]);
                $price = 0;
                foreach ($ssItem['stages'] as $rIdx => &$item){
                    $rKey = $rIdx+1;

                    $price += $item['gprice'];
                    if(empty($price))$this->response(__LINE__, "第{$lvIdx}层体力层,第{$ssIdx}层数数层, 价格为0", $item);

                    $item['prizes'] = @json_decode(urldecode($item['prizes']), true) ?? [];
                    if(empty($item['prizes']))$this->response(__LINE__, "第{$lvIdx}层体力层,第{$ssIdx}层数数层,第{$rKey}个奖励,配置为空", $item);
                }
            }
        }
        $actConfig['reward_info'] = $config;
        $actConfig['reward_conf'] = [
            'maxNum' => intval($actConfig['maxNum']), //最大购买次数
        ];
        unset($actConfig['onePlusConfig'], $actConfig['maxNum']);
    }

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

        foreach ($rewardConf as $idx1 => $item1) {
            foreach ($item1['stages'] as $idx2 => $item2) {
                $idx = "{$idx1}_{$idx2}";
                $condition = $this->getStageConditionLvShushu($item1, $item2);
                oo::commonOprRedis('games')->hset($stageRewardKeys, $idx, json_encode(['goods' =>$item2['stages']], 32));
                oo::commonOprRedis('games')->hset($conditionKeys, $idx, json_encode($condition, 32));
//                    oo::commonOprRedis('games')->hset($stageExtraConfKeys, $idx, json_encode(['tokenGoods' =>$extraReward[$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)
    {
        // TODO: Implement serializeShowConf() method.
    }

    function importActData(array &$basicConfig, $sheetArray)
    {
        $sheetIdx = -1;
        $basicArray = $sheetArray[++$sheetIdx] ?? [];
        $stagesMappingArray = $sheetArray[++$sheetIdx] ?? [];
        $stagesRewardsArray = $sheetArray[++$sheetIdx] ?? [];


        $maxNumConfig = self::parseExtraBasicConfig($this->extraConfigFieldMapping, $basicArray);
        $basicConfig['maxNum'] = intval($maxNumConfig['maxNum']);

        list($rewardsConfig, $idxMapping) = $this->parseLvShushuStagesMapping($stagesMappingArray);

        $this->parseRewardSheet($rewardsConfig, $idxMapping, $stagesRewardsArray);

        $basicConfig['onePlusConfig'] = $rewardsConfig;
    }


    public function getActBasicConfig():array
    {
        return [
            'gtype' => ActBaseModel::getGtypeByActType($this->actType)
        ];
    }

    private function parseRewardSheet(&$rewardsConfig, $idxMapping, $stagesRewardsSheet){
        $gType = ActBaseModel::getGtypeByActType($this->actType);
        $gidBegin = $gType * 10000;
        for($i=1;$i < count($stagesRewardsSheet);$i++){
            $lineNum = $i+1;
            list($idx, $ridx, $price) = $stagesRewardsSheet[$i];
            if(empty($idxMapping[$idx]))$this->response(-1 * __LINE__, "第{$lineNum}行，映射关系不存在:{$idx}", [$idxMapping, $stagesRewardsSheet[$i]]);
            list($lvIdx, $ssIdx) = $idxMapping[$idx];

            $prizes = $this->parseLineRewards(array_slice($stagesRewardsSheet[$i], 3), $lineNum);

            $sku = $this->getSkuByPrice($price);
            $rewardsConfig[$lvIdx]['stages'][$ssIdx]['stages'] = $rewardsConfig[$lvIdx]['stages'][$ssIdx]['stages'] ?? [];
            $goodsCnt = count($rewardsConfig[$lvIdx]['stages'][$ssIdx]['stages']);
            $gid = $gidBegin + $goodsCnt;
            $rewardsConfig[$lvIdx]['stages'][$ssIdx]['stages'][] = [
                "gprice"=>  $goodsCnt > 0 ? 0 : $price ,
                "gsku"=>    $sku,
                "gdiscount"=>1,
                "gid"=>$gid,
                "prizes"=> urlencode(json_encode($prizes, JSON_NUMERIC_CHECK)),
            ];
        }
    }
}