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

use app\dice\helper\AdminScopeHelper;
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('please provide direction (0=clockwise, 1=counterclockwise)');
        }
        $direction = (int) $direction;
        if (!in_array($direction, [DiceReward::DIRECTION_CLOCKWISE, DiceReward::DIRECTION_COUNTERCLOCKWISE], true)) {
            return $this->fail('direction must be 0 (clockwise) or 1 (counterclockwise)');
        }
        $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,
            $this->adminInfo ?? null,
            $request->input('dept_id')
        );
        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;
        }
        $deptId = AdminScopeHelper::resolveConfigDeptId($this->adminInfo ?? null, $request->input('dept_id'));
        DiceReward::refreshCache($deptId);
        $logic = new DiceRewardLogic();
        $data = $logic->getListGroupedByTierForDirection($direction, $deptId);
        return $this->success($data);
    }

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

    /**
     * 一键测试权重：创建测试记录并启动单进程后台执行，写入 dice_play_record_test
     * 参数：lottery_config_id 可选；paid_tier_weights / free_tier_weights 自定义档位；
     *       paid_s_count, paid_n_count
     * chain_free_mode=1：仅按付费次数模拟；付费抽到再来一次/T5 则在队列中插入免费局（同底注、lottery_type=免费、paid_amount=0）
     * kill_mode_enabled=1：测试内启用杀分；当模拟池盈利达到 test_safety_line 后，付费抽奖切到 killScore
     */
    #[Permission('一键测试权重', 'dice:reward:index:startWeightTest')]
    public function startWeightTest(Request $request): Response
    {
        $post = is_array($request->post()) ? $request->post() : [];
        $params = [
            'ante'                     => $post['ante'] ?? null,
            '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,
            'paid_s_count'            => $post['paid_s_count'] ?? null,
            'paid_n_count'            => $post['paid_n_count'] ?? null,
            'paid_tier_weights'       => $post['paid_tier_weights'] ?? null,
            'free_tier_weights'       => $post['free_tier_weights'] ?? null,
            'chain_free_mode'         => $post['chain_free_mode'] ?? null,
            'kill_mode_enabled'       => $post['kill_mode_enabled'] ?? null,
            'test_safety_line'        => $post['test_safety_line'] ?? null,
            'dept_id'                 => $post['dept_id'] ?? null,
            'ante_config_id'          => $post['ante_config_id'] ?? null,
            'ante_random'             => $post['ante_random'] ?? null,
        ];
        $adminId = isset($this->adminInfo['id']) ? (int) $this->adminInfo['id'] : null;
        $requestDeptId = AdminScopeHelper::pickRequestDeptId($request->input('dept_id'), $post);
        try {
            $logic = new DiceRewardConfigRecordLogic();
            $recordId = $logic->createWeightTestRecord($params, $adminId, $this->adminInfo ?? null, $requestDeptId);
            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('please provide record_id');
        }
        $record = DiceRewardConfigRecord::find($recordId);
        if (!$record) {
            return $this->fail('record not found');
        }
        $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('test data cleared');
        } catch (\Throwable $e) {
            return $this->fail('clear failed: ' . $e->getMessage());
        }
    }

    /**
     * 权重编辑弹窗：按方向+点数批量更新权重（写入 dice_reward）
     * 参数：items: [{ grid_number, weight_clockwise, weight_counterclockwise }, ...]
     */
    #[Permission('权重配比', 'dice:reward:index:batchUpdateWeights')]
    public function batchUpdateWeights(Request $request): Response
    {
        $items = $request->post('items', []);
        if (!is_array($items)) {
            return $this->fail('parameter items must be an array');
        }
        try {
            $deptId = AdminScopeHelper::resolveConfigDeptId($this->adminInfo ?? null, $request->input('dept_id'));
            $logic = new DiceRewardLogic();
            $logic->batchUpdateWeights($items, $deptId);
            return $this->success('save 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 must be 0 (clockwise) or 1 (counterclockwise)');
        }
        $items = $request->post('items', []);
        if (!is_array($items)) {
            return $this->fail('parameter items must be an array');
        }
        try {
            $deptId = AdminScopeHelper::resolveConfigDeptId($this->adminInfo ?? null, $request->input('dept_id'));
            $logic = new DiceRewardLogic();
            $logic->batchUpdateWeightsByDirection($direction, $items, $deptId);
            return $this->success('save success');
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }
}
