<?php
// +----------------------------------------------------------------------
// | saiadmin [ saiadmin快速开发框架 ]
// +----------------------------------------------------------------------
namespace app\dice\controller\reward;

use app\dice\logic\reward\DiceRewardLogic;
use app\dice\logic\reward_config_record\DiceRewardConfigRecordLogic;
use app\dice\model\reward\DiceReward;
use app\dice\model\play_record_test\DicePlayRecordTest;
use app\dice\model\reward_config_record\DiceRewardConfigRecord;
use plugin\saiadmin\basic\BaseController;
use support\think\Db;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;

/**
 * 奖励对照控制器（dice_reward，按方向分页列表 + 权重编辑）
 */
class DiceRewardController extends BaseController
{
    /**
     * 分页列表，按 direction 区分顺时针(0)/逆时针(1)
     * 参数：direction(必), tier(选), page, limit, orderField, orderType
     */
    #[Permission('奖励对照列表', 'dice:reward:index:index')]
    public function index(Request $request): Response
    {
        $direction = $request->input('direction', null);
        if ($direction === null || $direction === '') {
            return $this->fail('请传入 direction（0=顺时针 1=逆时针）');
        }
        $direction = (int) $direction;
        if (!in_array($direction, [DiceReward::DIRECTION_CLOCKWISE, DiceReward::DIRECTION_COUNTERCLOCKWISE], true)) {
            return $this->fail('direction 必须为 0（顺时针）或 1（逆时针）');
        }
        $tier = $request->input('tier', '');
        $page = (int) $request->input('page', 1);
        $limit = (int) $request->input('limit', 10);
        $orderField = $request->input('orderField', 'r.tier');
        $orderType = $request->input('orderType', 'asc');

        $logic = new DiceRewardLogic();
        $data = $logic->getListWithConfig($direction, [
            'tier'       => $tier,
            'orderField' => $orderField,
            'orderType'  => $orderType,
        ], $page, $limit);
        return $this->success($data);
    }

    /**
     * 权重编辑弹窗：按档位分组获取当前方向的配置+权重（单方向，用于兼容）
     * 参数：direction 0=顺时针 1=逆时针
     */
    #[Permission('奖励对照列表', 'dice:reward:index:index')]
    public function weightRatioList(Request $request): Response
    {
        $direction = (int) $request->input('direction', 0);
        if (!in_array($direction, [DiceReward::DIRECTION_CLOCKWISE, DiceReward::DIRECTION_COUNTERCLOCKWISE], true)) {
            $direction = DiceReward::DIRECTION_CLOCKWISE;
        }
        $logic = new DiceRewardLogic();
        $data = $logic->getListGroupedByTierForDirection($direction);
        return $this->success($data);
    }

    /**
     * 权重编辑弹窗：按档位分组获取配置+顺时针/逆时针权重（dice_reward 双方向）
     * 返回与 reward_config 权重配比一致结构，供奖励对照页弹窗同时编辑 direction=0/1
     * 拉取前先刷新缓存，保证与列表页（直查 DB）数据一致，避免表格与弹窗权重不一致
     */
    #[Permission('奖励对照列表', 'dice:reward:index:index')]
    public function weightRatioListWithDirection(Request $request): Response
    {
        DiceReward::refreshCache();
        $logic = new DiceRewardLogic();
        $data = $logic->getListGroupedByTierWithDirection();
        return $this->success($data);
    }

    /**
     * 一键测试权重：创建测试记录并启动单进程后台执行，按付费/免费、顺逆方向交替写入 dice_play_record_test
     * 参数：lottery_config_id 可选，不选则传 paid_tier_weights / free_tier_weights 自定义档位；
     *       paid_s_count, paid_n_count, free_s_count, free_n_count；或兼容旧版 s_count, n_count
     */
    #[Permission('奖励对照列表', 'dice:reward:index:index')]
    public function startWeightTest(Request $request): Response
    {
        $post = is_array($request->post()) ? $request->post() : [];
        $params = [
            'lottery_config_id'       => $post['lottery_config_id'] ?? null,
            'paid_lottery_config_id'  => $post['paid_lottery_config_id'] ?? null,
            'free_lottery_config_id'  => $post['free_lottery_config_id'] ?? null,
            's_count'                 => $post['s_count'] ?? null,
            'n_count'                 => $post['n_count'] ?? null,
            'paid_s_count'            => $post['paid_s_count'] ?? null,
            'paid_n_count'            => $post['paid_n_count'] ?? null,
            'free_s_count'            => $post['free_s_count'] ?? null,
            'free_n_count'            => $post['free_n_count'] ?? null,
            'paid_tier_weights'       => $post['paid_tier_weights'] ?? null,
            'free_tier_weights'       => $post['free_tier_weights'] ?? null,
        ];
        $adminId = isset($this->adminInfo['id']) ? (int) $this->adminInfo['id'] : null;
        try {
            $logic = new DiceRewardConfigRecordLogic();
            $recordId = $logic->createWeightTestRecord($params, $adminId);
            return $this->success(['record_id' => $recordId]);
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 查询一键测试进度：total_play_count、over_play_count、status、remark
     */
    #[Permission('奖励对照列表', 'dice:reward:index:index')]
    public function getTestProgress(Request $request): Response
    {
        $recordId = (int) $request->input('record_id', 0);
        if ($recordId <= 0) {
            return $this->fail('请传入 record_id');
        }
        $record = DiceRewardConfigRecord::find($recordId);
        if (!$record) {
            return $this->fail('记录不存在');
        }
        $arr = $record->toArray();
        $data = [
            'total_play_count' => (int) ($arr['total_play_count'] ?? 0),
            'over_play_count'  => (int) ($arr['over_play_count'] ?? 0),
            'status'           => (int) ($arr['status'] ?? 0),
            'remark'           => $arr['remark'] ?? null,
            'result_counts'    => $arr['result_counts'] ?? null,
            'tier_counts'      => $arr['tier_counts'] ?? null,
        ];
        return $this->success($data);
    }

    /**
     * 一键清空测试数据：清空 dice_play_record_test 表
     */
    #[Permission('奖励对照列表', 'dice:reward:index:index')]
    public function clearPlayRecordTest(Request $request): Response
    {
        try {
            $table = (new DicePlayRecordTest())->getTable();
            Db::execute('TRUNCATE TABLE `' . $table . '`');
            return $this->success('已清空测试数据');
        } catch (\Throwable $e) {
            return $this->fail('清空失败：' . $e->getMessage());
        }
    }

    /**
     * 权重编辑弹窗：按方向+点数批量更新权重（写入 dice_reward）
     * 参数：items: [{ grid_number, weight_clockwise, weight_counterclockwise }, ...]
     */
    #[Permission('奖励对照修改', 'dice:reward:index:update')]
    public function batchUpdateWeights(Request $request): Response
    {
        $items = $request->post('items', []);
        if (!is_array($items)) {
            return $this->fail('参数 items 必须为数组');
        }
        try {
            $logic = new DiceRewardLogic();
            $logic->batchUpdateWeights($items);
            return $this->success('保存成功');
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 权重编辑弹窗：批量更新当前方向的权重（单方向，用于兼容）
     * 参数：direction(必), items: [{ id, weight }, ...]
     */
    #[Permission('奖励对照修改', 'dice:reward:index:update')]
    public function batchUpdateWeightsByDirection(Request $request): Response
    {
        $direction = (int) $request->post('direction', 0);
        if (!in_array($direction, [DiceReward::DIRECTION_CLOCKWISE, DiceReward::DIRECTION_COUNTERCLOCKWISE], true)) {
            return $this->fail('direction 必须为 0（顺时针）或 1（逆时针）');
        }
        $items = $request->post('items', []);
        if (!is_array($items)) {
            return $this->fail('参数 items 必须为数组');
        }
        try {
            $logic = new DiceRewardLogic();
            $logic->batchUpdateWeightsByDirection($direction, $items);
            return $this->success('保存成功');
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }
}
