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

use app\dice\model\lottery_pool_config\DiceLotteryPoolConfig;
use app\dice\helper\AdminScopeHelper;
use plugin\saiadmin\basic\BaseController;
use app\dice\logic\lottery_pool_config\DiceLotteryPoolConfigLogic;
use app\dice\validate\lottery_pool_config\DiceLotteryPoolConfigValidate;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;

/**
 * 色子奖池配置控制器
 */
class DiceLotteryPoolConfigController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new DiceLotteryPoolConfigLogic();
        $this->validate = new DiceLotteryPoolConfigValidate;
        parent::__construct();
    }

    /**
     * 获取 DiceLotteryPoolConfig 列表数据，用于 lottery_config_id 下拉（值为 id，显示为 name），并附带 T1-T5 档位权重
     * @param Request $request
     * @return Response 返回 [ ['id' => int, 'name' => string, 't1_weight' => int, ... 't5_weight' => int], ... ]
     */
    #[Permission('色子奖池配置列表', 'dice:lottery_pool_config:index:index')]
    public function getOptions(Request $request): Response
    {
        $query = DiceLotteryPoolConfig::field('id,name,remark,t1_weight,t2_weight,t3_weight,t4_weight,t5_weight')
            ->order('id', 'asc');
        AdminScopeHelper::applyConfigScope($query, $this->adminInfo ?? null, $request->input('dept_id'));
        $list = $query->select();
        $data = $list->map(function ($item) {
            $row = is_array($item) ? $item : $item->toArray();
            $display = DiceLotteryPoolConfig::displayLabel($row);
            return [
                'id'           => (int) ($row['id'] ?? 0),
                'name'         => (string) ($row['name'] ?? ''),
                'remark'       => (string) ($row['remark'] ?? ''),
                'display_name' => $display,
                't1_weight'    => (int) ($row['t1_weight'] ?? 0),
                't2_weight'    => (int) ($row['t2_weight'] ?? 0),
                't3_weight'    => (int) ($row['t3_weight'] ?? 0),
                't4_weight'    => (int) ($row['t4_weight'] ?? 0),
                't5_weight'    => (int) ($row['t5_weight'] ?? 0),
            ];
        })->toArray();
        return $this->success($data);
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    #[Permission('色子奖池配置列表', 'dice:lottery_pool_config:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['name', ''],
            ['type', ''],
        ]);
        $query = $this->logic->search($where);
        AdminScopeHelper::applyConfigScope($query, $this->adminInfo ?? null, $request->input('dept_id'));
        $data = $this->logic->getList($query);
        return $this->success($data);
    }

    /**
     * 读取数据
     * @param Request $request
     * @return Response
     */
    #[Permission('色子奖池配置读取', 'dice:lottery_pool_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('not found');
        }
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    #[Permission('色子奖池配置添加', 'dice:lottery_pool_config:index:save')]
    public function save(Request $request): Response
    {
        $data = $request->post();
        $this->validate('save', $data);
        AdminScopeHelper::prepareConfigSaveData($data, $this->adminInfo ?? null, $request->input('dept_id'), $data);
        $result = $this->logic->add($data);
        if ($result) {
            return $this->success('add success');
        } else {
            return $this->fail('add failed');
        }
    }

    /**
     * 更新数据
     * @param Request $request
     * @return Response
     */
    #[Permission('色子奖池配置修改', 'dice:lottery_pool_config:index:update')]
    public function update(Request $request): Response
    {
        $data = $request->post();
        if ($data === [] || $data === null) {
            $data = $request->all();
        }
        $this->validate('update', $data);
        $requestDeptId = AdminScopeHelper::pickRequestDeptId($request->input('dept_id'), is_array($data) ? $data : []);
        $model = $this->logic->read($data['id'] ?? 0);
        if ($model) {
            $recordDeptId = is_array($model) ? ($model['dept_id'] ?? null) : ($model->dept_id ?? null);
            if (! AdminScopeHelper::canAccessDept($this->adminInfo ?? null, $recordDeptId, $requestDeptId)) {
                return $this->fail('no permission to update this record');
            }
        }
        $result = $this->logic->edit($data['id'], $data, $this->adminInfo ?? null, $requestDeptId);
        if ($result) {
            return $this->success('update success');
        } else {
            return $this->fail('update failed');
        }
    }

    /**
     * 删除数据
     * @param Request $request
     * @return Response
     */
    #[Permission('色子奖池配置删除', 'dice:lottery_pool_config:index:destroy')]
    public function destroy(Request $request): Response
    {
        $ids = $request->post('ids', '');
        if (empty($ids)) {
            return $this->fail('please select data to delete');
        }
        $result = $this->logic->destroy($ids);
        if ($result) {
            return $this->success('delete success');
        } else {
            return $this->fail('delete failed');
        }
    }

    /**
     * 获取当前彩金池（Redis 实例化，无则按 type=0 创建）
     * 返回含玩家累计盈利 profit_amount 实时值，供前端轮询展示
     */
    #[Permission('色子奖池配置列表', 'dice:lottery_pool_config:index:getCurrentPool')]
    public function getCurrentPool(Request $request): Response
    {
        $deptId = AdminScopeHelper::resolveConfigDeptId($this->adminInfo ?? null, $request->input('dept_id'));
        $data = $this->logic->getCurrentPool($deptId);
        return $this->success($data);
    }

    /**
     * 更新当前彩金池：仅可修改 safety_line、t1_weight～t5_weight，不可修改 profit_amount
     */
    #[Permission('色子奖池配置修改', 'dice:lottery_pool_config:index:updateCurrentPool')]
    public function updateCurrentPool(Request $request): Response
    {
        $data = $request->post();
        if ($data === [] || $data === null) {
            $data = $request->all();
        }
        $requestDeptId = AdminScopeHelper::pickRequestDeptId($request->input('dept_id'), is_array($data) ? $data : []);
        $deptId = AdminScopeHelper::resolveConfigDeptId($this->adminInfo ?? null, $requestDeptId);
        $this->logic->updateCurrentPool($data, $deptId);
        return $this->success('save success');
    }

    /**
     * 重置当前彩金池的玩家累计盈利：将 profit_amount 置为 0
     */
    #[Permission('色子奖池配置修改', 'dice:lottery_pool_config:index:resetProfitAmount')]
    public function resetProfitAmount(Request $request): Response
    {
        $deptId = AdminScopeHelper::resolveConfigDeptId($this->adminInfo ?? null, $request->input('dept_id'));
        $this->logic->resetProfitAmount($deptId);
        return $this->success('reset success');
    }
}
