<?php

class TrafficPermitActModel extends ActBaseModel implements ActInterface
{

    static  $taskMapping = [
        "邀请好友" => 1,
        "完成世界" => 2,
        "偷" => 3,
        "打" => 4,
        "和大盗莫里一起偷袭" => 5,
        "和拳手莫里一起进攻" => 6,
        "转一次黄金转盘" => 7,
        "夺宝一次" => 8,
        "玩一次黄金矿工" => 9,
        "分享游戏" => 10,
        "召回好友" => 11,
        "消耗体力200" => 12,
        "消耗体力800" => 13,
        "消耗体力2000" => 14,
        "消耗体力8000" => 15,
    ];

    static  $permissionMapping = [
        '通行证专属头像框' => 2 ,
        '赠送N个通行证等级' => 3 ,
    ];
    function serializeShowConf(array &$actConfig)
    {

    }

    function formatActData(array &$actConfig)
    {
//        $this->response(1, '666', $actConfig['trafficPermit']);
        if (empty($actConfig['trafficPermit']) ) $this->response(1, '保存失败，奖励配置-不为空');
        $maxReward = [];
        $prizeTypes = ['prize', 'specialPrize'];
        $taskTypes = ['task1' => '双日任务', 'task2' => '单日任务'];
        $permitTypes = ['normal' => '普通版权限', 'special' => '精英版权限'];
        foreach ($actConfig['trafficPermit'] as $key => $row) {
            foreach ($prizeTypes as $prizeType){
                $prize = json_decode(urldecode($row['maxRewards'][$prizeType]), true) ?? [];
                if(empty($row['maxRewards'][$prizeType]))$this->response(1, '保存失败，额外奖励配置异常', $row );
                $actConfig['trafficPermit'][$key]['maxRewards'][$prizeType] = $prize;
            }

            // 等级奖励
            foreach ($row['levels'] as $level => $item){
                foreach ($prizeTypes as $prizeType){
                    $prize = json_decode(urldecode($item[$prizeType]), true) ?? [];
                    if(empty($row['maxRewards'][$prizeType]))$this->response(1, '保存失败，奖励配置异常', $row );
                    $actConfig['trafficPermit'][$key]['levels'][$level][$prizeType] = $prize;
//                    $json[$level][$prizeType] = $prize;
                }
            }
            if(empty($maxReward))$maxReward = $actConfig['trafficPermit'][$key]['maxRewards'];

            // 任务
            foreach ($taskTypes as $taskType => $taskTypeText){
                if(empty($row[$taskType]))$this->response(1, "保存失败，{$taskTypeText} 配置为空", $row );

                $taskTypeArr = array_column($row[$taskType], 'type');
                if (count($taskTypeArr) != count(array_unique($taskTypeArr))) {
                    $this->response(1, "{$taskTypeText}重复");
                }

                $actConfig['trafficPermit'][$key][$taskType] = array_values($row[$taskType]);
            }

            // 权限
            foreach ($permitTypes as $permitType => $permitTypeText){
                if(empty($row['permitRewards'][$permitType]))$this->response(1, "保存失败，{$permitTypeText} 配置为空", $row );

                if (empty($row['permitRewards'][$permitType]['price'])) $this->response(__LINE__, $permitTypeText . ' 价格不能为0');

                $sku = $this->getSkuByPrice($row['permitRewards'][$permitType]['price']);
                if (empty($sku)) $this->response(__LINE__, $row['permitRewards'][$permitType]['price'] . ' 未找到对应SKU');
                $actConfig['trafficPermit'][$key]['permitRewards'][$permitType]['sku'] = $sku;
            }

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

    function writeActCache(array $actConfig)
    {
        $conditionKeys = okeys::activityConditionKeys($actConfig['aid']);
        $stageRewardKeys = okeys::activityRewardsStageKeys($actConfig['aid']);
        $extraReward = json_decode($actConfig['reward_pro'], true) ?? [];
        $expireTime = max($actConfig['end_time'], time() + 60);#redis最少一分钟
        foreach ($extraReward as $idx1 => $item1) {
            $condition = [
                CONDITION_TYPE_LV => [
                    'shushu' => [],
                    'start' => $item1['lvStart'],
                    'end' => $item1['lvEnd'],
                    'type' => CONDITION_TYPE_LV,
                ],
            ];

            $stageKey = $idx1;
            $stageConditions = array_values($condition);
            oo::commonOprRedis('games')->hset($conditionKeys, $stageKey, json_encode($stageConditions, 32));
            oo::commonOprRedis('games')->hset($stageRewardKeys, $stageKey, json_encode($item1, 32));
        }

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

    function importActData(array &$basicConfig, $sheetArray)
    {
        $sheetIdx = 0;
        $stageMappingSheet = $sheetArray[++$sheetIdx];
        $trafficPermitBasicConfSheet = $sheetArray[++$sheetIdx];
        $prizeSheet = $sheetArray[++$sheetIdx];
        $specialPrizeSheet = $sheetArray[++$sheetIdx];
        $taskSheets[1] = $sheetArray[++$sheetIdx];
        $taskSheets[2] = $sheetArray[++$sheetIdx];

        $permissionSheets['normal'] = $sheetArray[++$sheetIdx];
        $permissionSheets['special'] = $sheetArray[++$sheetIdx];
        $alertConfSheet = $sheetArray[++$sheetIdx];


        list($rewardsConfig, $idxMapping) = $this->parseLvStagesMapping($stageMappingSheet);
        $this->parsePrizeSheet($prizeSheet,  $idxMapping, $rewardsConfig);
        $this->parseSpecialPrizeSheet($specialPrizeSheet, $idxMapping, $rewardsConfig);

        // 基础配置
        $basicKeys = [
            'openLv',
            'guideLv',
            'upLvDiamondNum',
            'passExp',
            'itemColor',
            'iconColor',
            'maxLevelExpGap',
        ];
        foreach ($trafficPermitBasicConfSheet as $k => $line){
            if(empty($k))continue;
            list($idx, $openLv,  $guideLv,  $upLvDiamondNum,  $passExp,  $itemColor,  $iconColor,  $maxLevelExpGap) = $line;
            if(empty($idxMapping[$idx][0]))$this->response(__LINE__, "分层id：{$idx} 无对应分层关系", [$rewardsConfig, $idxMapping, $idx]);
            $lvIdx = $idxMapping[$idx][0];
            $rewardsConfig[$lvIdx]["basic"] = [];
            foreach ($basicKeys as $basicKey ){
                $rewardsConfig[$lvIdx]["basic"][$basicKey] = $$basicKey;
            }
        }

        // 任务
        foreach ($taskSheets as $taskTypeKey => $sheet){
            foreach ($sheet as $k => $line){
                if(empty($k))continue;
                list($idx, $taskName, $num, $getNum) = $line;
                if(empty($idxMapping[$idx][0]))$this->response(__LINE__, "分层id：{$idx} 无对应分层关系", [$rewardsConfig, $idxMapping, $idx]);
                $lvIdx = $idxMapping[$idx][0];
                if(empty(self::$taskMapping[$taskName]))$this->response(__LINE__, "任务类型：{$idx} 不存在", [$rewardsConfig, $idxMapping, $idx]);
                $rewardsConfig[$lvIdx]["task{$taskTypeKey}"] = $rewardsConfig[$lvIdx]["task{$taskTypeKey}"] ?? [];
                $rewardsConfig[$lvIdx]["task{$taskTypeKey}"][] = [
                    'id' => count($rewardsConfig[$lvIdx]["task{$taskTypeKey}"]) + 1,
                    'type' => self::$taskMapping[$taskName],
                    'num' => $num,
                    'getNum' => $getNum,
                ];
            }
        }

        // 权限
        $gid = 0;
        foreach ($permissionSheets as $permissionType => $sheet){
            switch ($permissionType){
                case 'normal':$gid = 1770;break;
                case 'special':$gid = 1814;break;
                default:$this->response(__LINE__, "权限类型异常：{$permissionType}", [$rewardsConfig, $idxMapping, $idx]);
            }
            foreach ($sheet as $k => $line){
                if(empty($k))continue;
                list($idx, $price, $permissionName, $value) = $line;
                if(empty($idxMapping[$idx][0]))$this->response(__LINE__, "分层id：{$idx} 无对应分层关系", [$rewardsConfig, $idxMapping, $idx]);
                $lvIdx = $idxMapping[$idx][0];
                $sku = $this->getSkuByPrice($price);
                if(empty(self::$permissionMapping[$permissionName]))$this->response(__LINE__, "通行证权限奖励类型：{$idx} 不存在", [$rewardsConfig, $idxMapping, $idx]);
                $rewardsConfig[$lvIdx]["permitRewards"] = $rewardsConfig[$lvIdx]["permitRewards"] ?? [];
                if(empty($rewardsConfig[$lvIdx]["permitRewards"][$permissionType])){
                    $rewardsConfig[$lvIdx]["permitRewards"][$permissionType] = [
                        'price' => $price,
                        'gid' => $gid,
                        'rewards' => [],
                    ];
                }
                $rewardsConfig[$lvIdx]["permitRewards"][$permissionType]['rewards'][] = [
                    'type' => self::$permissionMapping[$permissionName],
                    'value' => $value,
                ];
            }
        }

        // 弹窗
        foreach ($alertConfSheet as $k => $line){
            if(empty($k))continue;
            list($idx, $statusText, $firstLv, $intervalLv) = $line;
            if(empty($idxMapping[$idx][0]))$this->response(__LINE__, "分层id：{$idx} 无对应分层关系", [$rewardsConfig, $idxMapping, $idx]);
            $lvIdx = $idxMapping[$idx][0];
            $rewardsConfig[$lvIdx]["alertConfig"] = [
                'status' => $this->parseYesOrNo($statusText),
                'firstStage' => intval($firstLv),
                'intervalStage' => intval($intervalLv),
            ];
        }

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

    function parsePrizeSheet($prizeSheet, $idxMapping, &$rewardsConfig){
        foreach ($prizeSheet as $k => $item){
            if(empty($k) || empty($item))continue;
            $lineNum = $k + 1;
            list($idx, $level, $max, $isGrand) = $item;
            $isGrand = $this->parseYesOrNo($isGrand);
            if(empty($idxMapping[$idx][0]))$this->response(__LINE__, "分层id：{$idx} 无对应分层关系", [$rewardsConfig, $idxMapping, $idx]);
            $lvIdx = $idxMapping[$idx][0];
            $prize = $this->parseLineRewards(array_slice($item, 4),  $lineNum);
            $prize = urlencode(json_encode($prize));
            if(empty($rewardsConfig[$lvIdx]))$this->response(__LINE__, "分层配置异常", [$rewardsConfig, $idxMapping, $idx]);
            if(empty($rewardsConfig[$lvIdx]['maxRewards']['prize'])){   // 额外奖励
                if($level > -1)
                    $this->response(__LINE__, "免费奖励，第{$lineNum}行，应该配置额外奖励", [$rewardsConfig, $idxMapping, $idx]);
                $rewardsConfig[$lvIdx]['maxRewards']['prize'] = $prize;
            }else{  // 等级奖励
                $rewardsConfig[$lvIdx]['levels'] = $rewardsConfig[$lvIdx]['levels'] ?? [];
                if($level != count($rewardsConfig[$lvIdx]['levels'])){
                    $this->response(__LINE__, "免费奖励，第{$lineNum}行，等级配置不连续", [$rewardsConfig, $idxMapping, $idx]);
                }
                $rewardsConfig[$lvIdx]['levels'][$level] = [
                    'levelId' => $level,
                    'max' => $max,
                    'isGrandPrize' => $isGrand,
                    'prize' => $prize,
                ];
            }

        }
    }

    function parseSpecialPrizeSheet($prizeSheet, $idxMapping, &$rewardsConfig){
        foreach ($prizeSheet as $k => $item){
            if(empty($k) || empty($item))continue;
            $lineNum = $k + 1;
            list($idx, $level) = $item;
            if(empty($idxMapping[$idx][0]))$this->response(__LINE__, "分层id：{$idx} 无对应分层关系", [$rewardsConfig, $idxMapping, $idx]);
            $lvIdx = $idxMapping[$idx][0];
            $prize = $this->parseLineRewards(array_slice($item, 2),  $lineNum);
            $prize = urlencode(json_encode($prize));
            if(empty($rewardsConfig[$lvIdx]))$this->response(__LINE__, "分层配置异常", [$rewardsConfig, $idxMapping, $idx]);
            if(empty($rewardsConfig[$lvIdx]['maxRewards']['specialPrize'])){   // 额外奖励
                if($level > -1)
                    $this->response(__LINE__, "令牌奖励， 第{$lineNum}行，应该配置额外奖励", [$rewardsConfig, $idxMapping, $idx]);
                $rewardsConfig[$lvIdx]['maxRewards']['specialPrize'] = $prize;
            }else{  // 等级奖励
                if(isset($tmpLevel) && $level != $tmpLevel + 1){
                    $this->response(__LINE__, "令牌奖励，第{$lineNum}行，等级配置不连续", [$level , $tmpLevel]);
                }

                if(empty($rewardsConfig[$lvIdx]['levels'][$level])){
                    $this->response(__LINE__, "令牌奖励， 第{$lineNum}行，等级配置异常", [$rewardsConfig, $idxMapping, $idx]);
                }
                $rewardsConfig[$lvIdx]['levels'][$level]['specialPrize'] = $prize;
            }
            $tmpLevel = $level;

        }
    }


    function parsePermissionSheet($sheetData, $type = 'normal'){
        $gid = 0;
        switch ($type){
            case 'normal':$gid = 1770;break;
            case 'special':$gid = 1814;break;
            default:$this->response(__LINE__, "配置异常");
        }
        $permissionMapping = [
            '通行证专属头像框' => 2 ,
            '赠送N个通行证等级' => 3 ,
        ];
        $price = 0;
        $types = [];
        $values = [];

        foreach ($sheetData as $k => $item){
            if(empty($item[0]))continue;
            switch ($item[0]){
                case '价格':
                    $sku = $this->getSkuByPrice($item[1]);
                    if(empty($sku)){
                        $this->response(__LINE__, "价格配置异常:{$item[1]}");
                    }
                    $price = $item[1];
                    break;
                case '奖励':
                    if(empty($item[1]) || empty($permissionMapping[$item[1]]))
                        $this->response(__LINE__, "通行证权限配置异常:{$item[1]}");
                    $types[] = $permissionMapping[$item[1]];
                    $values[] = intval($item[2]);
            }
        }
        return [
            'price' => $price,
            'gid' => $gid,
            'rewards' => [
                'type' => $types,
                'value' => $values,
            ],
        ];
    }
    function parsePermissionAlertSheet($sheetData){
        $alertConfig = [
            'status' => 0,
            'firstStage' => 0,
            'intervalStage' => 0,
        ];
        foreach ($sheetData as $k => $item){
            if(empty($item[0]))continue;
            switch ($item[0]){
                case '弹窗开关':
                    $alertConfig['status'] = $this->parseYesOrNo($item[1]);break;
                case '第一次触发弹窗的通行证等级':
                    $alertConfig['firstStage'] = intval($item[1]);break;
                case '通行证等级每升满X级就触发一次弹窗':
                    $alertConfig['intervalStage'] = intval($item[1]);break;
            }
        }
        return $alertConfig;
    }
    function parseTrafficPermitBasicConf($sheetData): array
    {
        $data = [];
        $textMapping = [
            '开放等级' => 'openLv',
            '指引等级' => 'guideLv',
            '提升等级钻石数' => 'upLvDiamondNum',
            '通行证获得经验' => 'passExp',
            '扫光颜色' => 'itemColor',
            '图标底色' => 'iconColor',
            '额外等级经验差' => 'maxLevelExpGap',
        ];
        foreach ($sheetData as $item){
            @list($prefix, $value) = $item;
            if(empty($textMapping[$prefix]))continue;
            $data[$textMapping[$prefix]] = $value;
        }
        return $data;
    }
}