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

use plugin\saiadmin\basic\BaseController;
use app\dice\logic\reward_config\DiceRewardConfigLogic;
use app\dice\logic\reward\DiceRewardLogic;
use app\dice\validate\reward_config\DiceRewardConfigValidate;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;

/**
 * 奖励配置控制器
 */
class DiceRewardConfigController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new DiceRewardConfigLogic();
        $this->validate = new DiceRewardConfigValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置列表', 'dice:reward_config:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['grid_number_min', ''],
            ['grid_number_max', ''],
            ['ui_text', ''],
            ['real_ev_min', ''],
            ['real_ev_max', ''],
            ['tier', ''],
        ]);
        $query = $this->logic->search($where);
        $data = $this->logic->getList($query);
        return $this->success($data);
    }

    /**
     * 读取数据
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置读取', 'dice:reward_config:index:read')]
    public function read(Request $request): Response
    {
        $id = $request->input('id', '');
        $model = $this->logic->read($id);
        if ($model) {
            $data = is_array($model) ? $model : $model->toArray();
            return $this->success($data);
        } else {
            return $this->fail('未查找到信息');
        }
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置添加', 'dice:reward_config:index:save')]
    public function save(Request $request): Response
    {
        $data = $request->post();
        $this->validate('save', $data);
        $result = $this->logic->add($data);
        if ($result) {
            return $this->success('添加成功');
        } else {
            return $this->fail('添加失败');
        }
    }

    /**
     * 更新数据
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置修改', 'dice:reward_config:index:update')]
    public function update(Request $request): Response
    {
        $data = $request->post();
        $this->validate('update', $data);
        $result = $this->logic->edit($data['id'], $data);
        if ($result) {
            return $this->success('修改成功');
        } else {
            return $this->fail('修改失败');
        }
    }

    /**
     * 批量更新奖励索引配置（第一页：id、grid_number、ui_text、real_ev、tier、remark）
     * @param Request $request items: [{ id, grid_number?, ui_text?, real_ev?, tier?, remark? }, ...]
     * @return Response
     */
    #[Permission('奖励配置修改', 'dice:reward_config:index:update')]
    public function batchUpdate(Request $request): Response
    {
        $items = $request->post('items', []);
        if (! is_array($items)) {
            return $this->fail('参数 items 必须为数组');
        }
        $err = $this->logic->validateBatchUpdateItems($items);
        if ($err !== null) {
            return $this->fail($err);
        }
        foreach ($items as $item) {
            $this->validate('batch_update', array_merge($item, ['id' => $item['id']]));
        }
        $this->logic->batchUpdate($items);
        return $this->success('保存成功');
    }

    /**
     * 删除数据
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置删除', 'dice:reward_config:index:destroy')]
    public function destroy(Request $request): Response
    {
        $ids = $request->post('ids', '');
        if (empty($ids)) {
            return $this->fail('请选择要删除的数据');
        }
        $result = $this->logic->destroy($ids);
        if ($result) {
            return $this->success('删除成功');
        } else {
            return $this->fail('删除失败');
        }
    }

    /**
     * T1-T5、BIGWIN 权重配比：按档位分组返回配置列表（含顺时针/逆时针权重，来自 dice_reward）
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置列表', 'dice:reward_config:index:index')]
    public function weightRatioList(Request $request): Response
    {
        $rewardLogic = new DiceRewardLogic();
        $data = $rewardLogic->getListGroupedByTierWithDirection();
        return $this->success($data);
    }

    /**
     * T1-T5、BIGWIN 权重配比：按 DiceReward 主键 id 批量更新 weight（写入 dice_reward，修改后刷新缓存）
     * items: [ { id: DiceReward.id, weight: 1-10000 }, ... ]
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置修改', 'dice:reward_config:index:update')]
    public function batchUpdateWeights(Request $request): Response
    {
        $items = $request->post('items', []);
        if (!is_array($items)) {
            return $this->fail('参数 items 必须为数组');
        }
        try {
            $rewardLogic = new DiceRewardLogic();
            $rewardLogic->batchUpdateWeights($items);
            return $this->success('保存成功');
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 大奖权重：按 grid_number 批量保存 BIGWIN 权重（仅更新 dice_reward_config 表，不操作 dice_reward）
     * items: [ { grid_number: 5-30, weight: 0-10000 }, ... ]
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置修改', 'dice:reward_config:index:update')]
    public function saveBigwinWeightsByGrid(Request $request): Response
    {
        $items = $request->post('items', []);
        if (! is_array($items)) {
            return $this->fail('参数 items 必须为数组');
        }
        $err = $this->logic->validateBigwinWeightItems($items);
        if ($err !== null) {
            return $this->fail($err);
        }
        $this->logic->batchUpdateBigwinWeight($items);
        return $this->success('保存成功');
    }

    /**
     * 创建奖励对照：按当前 dice_reward_config 为两种方向（顺时针0、逆时针1）生成所有色子可能对应的 dice_reward 记录
     * 权重默认 1，可在「奖励对照」页的权重编辑弹窗中调整
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置修改', 'dice:reward_config:index:update')]
    public function createRewardReference(Request $request): Response
    {
        try {
            $rewardLogic = new DiceRewardLogic();
            $result = $rewardLogic->createRewardReferenceFromConfig();
            return $this->success($result, '创建奖励对照成功');
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 权重配比测试：仅模拟落点统计，不创建游玩记录。按当前配置在内存中模拟 N 次抽奖，返回各 grid_number 落点次数，可选保存到 dice_reward_config_record。
     * @param Request $request test_count: 100|500|1000, save_record: bool, lottery_config_id: int|null 奖池配置ID，用于设定 T1-T5 概率
     * @return Response
     */
    #[Permission('奖励配置列表', 'dice:reward_config:index:index')]
    public function runWeightTest(Request $request): Response
    {
        $testCount = (int) $request->post('test_count', 100);
        $saveRecord = (bool) $request->post('save_record', true);
        $adminId = isset($this->adminInfo['id']) ? (int) $this->adminInfo['id'] : null;
        $lotteryConfigId = $request->post('lottery_config_id', null);
        if ($lotteryConfigId !== null && $lotteryConfigId !== '') {
            $lotteryConfigId = (int) $lotteryConfigId;
        } else {
            $lotteryConfigId = null;
        }
        try {
            $result = $this->logic->runWeightTest($testCount, $saveRecord, $adminId, $lotteryConfigId);
            return $this->success($result);
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }
}
