<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
// | Author: your name
// +----------------------------------------------------------------------
namespace app\dice\model\reward_config_record;

use app\dice\model\play_record_test\DicePlayRecordTest;
use app\dice\model\DiceModel;
use think\model\relation\HasMany;

/**
 * 奖励配置权重测试记录模型
 *
 * dice_reward_config_record 奖励配置权重测试记录
 *
 * @property int $id 主键
 * @property int $test_count 测试次数 100/500/1000/5000/10000
 * @property array $weight_config_snapshot 测试时权重配比快照：按档位 id,grid_number,tier,weight
 * @property array $tier_weights_snapshot 测试时 T1-T5 档位权重快照（来自奖池配置）
 * @property int|null $lottery_config_id 测试时使用的奖池配置 ID（兼容旧：付费+免费共用）
 * @property int|null $paid_lottery_config_id 付费抽奖奖池配置 ID，默认 type=0
 * @property int|null $free_lottery_config_id 免费抽奖奖池配置 ID，默认 type=1
 * @property int $total_play_count 总模拟次数
 * @property int $over_play_count 已完成次数
 * @property int $status 状态 -1失败 0进行中 1成功
 * @property string|null $remark 失败时记录原因
 * @property int|null $ante 底注/注数（dice_ante_config.mult）
 * @property int $paid_s_count 付费抽奖顺时针次数
 * @property int $paid_n_count 付费抽奖逆时针次数
 * @property int $chain_free_mode 1=链式再来一次免费抽奖
 * @property int $kill_mode_enabled 测试内杀分开关 1=开启
 * @property int $test_safety_line 测试内安全线（模拟玩家累计盈利阈值）
 * @property int $paid_planned_spins 计划付费抽奖次数(顺+逆)
 * @property int $play_again_count 再来一次次数(T5触发次数)
 * @property array|null $paid_tier_weights 付费自定义档位权重 T1-T5
 * @property array|null $free_tier_weights 免费自定义档位权重 T1-T5
 * @property array $result_counts 落点统计 grid_number=>出现次数
 * @property array|null $tier_counts 档位出现次数 T1=>count
 * @property float|null $platform_profit 平台赚取金额（付费金额 paid_amount 求和-玩家总收益）
 * @property array|null $bigwin_weight 测试时 BIGWIN 档位权重快照（JSON：grid_number=>weight）
 * @property int|null $admin_id 执行测试的管理员ID
 * @property string|null $create_time 创建时间
 */
class DiceRewardConfigRecord extends DiceModel
{
    /** 状态：失败 */
    public const STATUS_FAIL = -1;
    /** 状态：待执行（队列中） */
    public const STATUS_RUNNING = 0;
    /** 状态：执行中（已被某进程领取，防止定时器重入重复执行） */
    public const STATUS_EXECUTING = 2;
    /** 状态：成功 */
    public const STATUS_SUCCESS = 1;

    protected $pk = 'id';

    protected $table = 'dice_reward_config_record';

    protected $json = ['weight_config_snapshot', 'tier_weights_snapshot', 'result_counts', 'tier_counts', 'paid_tier_weights', 'free_tier_weights', 'bigwin_weight'];

    protected $jsonAssoc = true;

    /**
     * 关联的测试抽奖记录（通过 reward_config_record_id）
     */
    public function playRecordTests(): HasMany
    {
        return $this->hasMany(DicePlayRecordTest::class, 'reward_config_record_id', 'id');
    }

    /** 计划付费抽奖次数（顺+逆） */
    public function searchPaidPlannedSpinsAttr($query, $value): void
    {
        if ($value !== '' && $value !== null) {
            $query->where('paid_planned_spins', '=', $value);
        }
    }

    /** 底注/注数（dice_ante_config.mult） */
    public function searchAnteAttr($query, $value): void
    {
        if ($value !== '' && $value !== null) {
            $query->where('ante', '=', $value);
        }
    }

    /**
     * 根据关联的 DicePlayRecordTest 统计平台赚取平台币
     * platform_profit = 关联的付费(lottery_type=0)付费金额求和(paid_amount) - 关联的 win_coin 求和
     * @param int $recordId dice_reward_config_record.id
     * @return float
     */
    public static function computePlatformProfitFromRelated(int $recordId): float
    {
        $paidAmount = (float) DicePlayRecordTest::where('reward_config_record_id', $recordId)
            ->where('lottery_type', 0)
            ->sum('paid_amount');
        $sumWinCoin = (float) DicePlayRecordTest::where('reward_config_record_id', $recordId)
            ->sum('win_coin');
        return round($paidAmount - $sumWinCoin, 2);
    }

    /**
     * 根据关联的 DicePlayRecordTest 统计再来一次次数（reward_tier=T5）
     * @param int $recordId
     * @return int
     */
    public static function computePlayAgainCountFromRelated(int $recordId): int
    {
        return (int) DicePlayRecordTest::where('reward_config_record_id', $recordId)
            ->where('reward_tier', 'T5')
            ->count();
    }

    /**
     * 根据关联的 DicePlayRecordTest 统计落点次数
     * result_counts = [grid_number => 出现次数]，只统计 roll_number 在 5-30 之间的记录
     * @param int $recordId
     * @return array<int,int>
     */
    public static function computeResultCountsFromRelated(int $recordId): array
    {
        $rows = DicePlayRecordTest::where('reward_config_record_id', $recordId)
            ->where('roll_number', '>=', 5)
            ->where('roll_number', '<=', 30)
            ->field('roll_number, COUNT(*) AS c')
            ->group('roll_number')
            ->select()
            ->toArray();

        $result = [];
        foreach ($rows as $row) {
            $grid = (int) ($row['roll_number'] ?? 0);
            $cnt = (int) ($row['c'] ?? 0);
            if ($grid > 0 && $cnt > 0) {
                $result[$grid] = $cnt;
            }
        }
        return $result;
    }
}
