<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class GameRtp extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('cron:game_rtp')
            ->setDescription('the game_rtp command');
    }

    protected function execute(Input $input, Output $output)
    {
        $setting = Db::name('game_rtp_setting')->order('id', 'desc')->find();
        if (!$setting) {
            trace('RTP 定时任务：未找到配置项，终止执行。', 'cron');
            return false;
        }

        if (strtoupper($setting['auto_game_rtp']) != 1) {
            trace('RTP 定时任务：当前配置为 OFF 关闭状态，跳过。', 'cron');
            return false;
        }

        $currentTime = time();
        $diffMinute = ($currentTime - $setting['last_execute_time']) / 60;
        if ($diffMinute < $setting['auto_frequency']) {
            // 时间还未达到设定的分钟间隔（例如10分钟），不重复执行
            trace('RTP 定时任务：时间还未达到设定的分钟间隔，跳过。', 'cron');
            return true;
        }

        $amountArr = json_decode($setting['auto_rtp_amount'], true);
        $minRtp = isset($amountArr['min']) ? intval($amountArr['min']) : 30;
        $maxRtp = isset($amountArr['max']) ? intval($amountArr['max']) : 90;
        // 安全防御：防止后台把最大最小值填反
        if ($minRtp > $maxRtp) {
            $temp = $minRtp;
            $minRtp = $maxRtp;
            $maxRtp = $temp;
        }

        $gameQuery = Db::name('game');
        if (!empty($setting['provider_display'])) {
            $providers = json_decode($setting['provider_display'], true);
            if (is_array($providers) && !empty($providers)) {
                $gameQuery->whereIn('provider_site', $providers);
            }
        }

        $games = $gameQuery->field('id')->select()->toArray();

        if (!empty($games)) {
            Db::startTrans();
            try {
                foreach ($games as $game) {
                    $individualRtp = mt_rand($minRtp, $maxRtp);
                    Db::name('game')->where('id', $game['id'])->update([
                        'rtp'         => $individualRtp,
                        'update_time' => $currentTime
                    ]);
                }
                Db::name('game_rtp_setting')->where('id', $setting['id'])->update(['last_execute_time' => $currentTime]);
                Db::commit();
                trace("RTP 定时任务：成功随机调整了 " . count($games) . " 款游戏的 RTP 控水值（区间: {$minRtp}% - {$maxRtp}%）", 'cron');
            } catch (\Exception $e) {
                Db::rollback();
                trace("RTP 定时任务执行失败: " . $e->getMessage(), 'error');
            }
        }

        return true;
    }
}
