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

use app\dice\logic\reward_config_record\DiceRewardConfigRecordLogic;
use app\dice\validate\reward_config_record\DiceRewardConfigRecordValidate;
use app\dice\helper\AdminScopeHelper;
use plugin\saiadmin\basic\BaseController;
use plugin\saiadmin\app\model\system\SystemUser;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;

/**
 * 奖励配置权重测试记录控制器
 */
class DiceRewardConfigRecordController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new DiceRewardConfigRecordLogic();
        $this->validate = new DiceRewardConfigRecordValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置权重测试记录列表', 'dice:reward_config_record:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['paid_planned_spins', ''],
            ['ante', ''],
        ]);
        $query = $this->logic->search($where);
        AdminScopeHelper::applyAdminScope($query, $this->adminInfo ?? null, $request->input('dept_id'));
        $data = $this->logic->getList($query);
        return $this->success($data);
    }

    /**
     * 读取数据
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置权重测试记录读取', 'dice:reward_config_record: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();
            $data['admin_name'] = $this->getAdminName((int) ($data['admin_id'] ?? 0));
            return $this->success($data);
        } else {
            return $this->fail('not found');
        }
    }

    /**
     * 根据管理员 ID 获取姓名（realname 优先，否则 username）
     */
    private function getAdminName(int $adminId): string
    {
        if ($adminId <= 0) {
            return '—';
        }
        $user = SystemUser::where('id', $adminId)->field('id,realname,username')->find();
        if (!$user) {
            return '';
        }
        $user = is_array($user) ? $user : $user->toArray();
        $name = trim((string) ($user['realname'] ?? ''));
        if ($name !== '') {
            return $name;
        }
        $name = trim((string) ($user['username'] ?? ''));
        return $name !== '' ? $name : (string) $adminId;
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    #[Permission('奖励配置权重测试记录添加', 'dice:reward_config_record:index:save')]
    public function save(Request $request): Response
    {
        $data = $request->post();
        $this->validate('save', $data);
        AdminScopeHelper::prepareBusinessSaveData($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:reward_config_record: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');
        }
    }

    /**
     * 导入：测试记录 → DiceReward、DiceRewardConfig(BIGWIN)、DiceLotteryPoolConfig(付费/免费 T1-T5)
     * @param Request $request record_id, paid_lottery_config_id(可选), free_lottery_config_id(可选), lottery_config_id(兼容旧版)
     */
    #[Permission('导入权重配置', 'dice:reward_config_record:index:importFromRecord')]
    public function importFromRecord(Request $request): Response
    {
        $recordId = (int) $request->post('record_id', 0);
        if ($recordId <= 0) {
            return $this->fail('please specify test record');
        }
        $paidId = $request->post('paid_lottery_config_id', null);
        $freeId = $request->post('free_lottery_config_id', null);
        $legacyId = $request->post('lottery_config_id', null);
        $paidLotteryConfigId = $paidId !== null && $paidId !== '' ? (int) $paidId : null;
        $freeLotteryConfigId = $freeId !== null && $freeId !== '' ? (int) $freeId : null;
        $lotteryConfigId = $legacyId !== null && $legacyId !== '' ? (int) $legacyId : null;
        try {
            $this->logic->importFromRecord($recordId, $paidLotteryConfigId, $freeLotteryConfigId, $lotteryConfigId);
            return $this->success('import success, refreshed DiceReward, DiceRewardConfig(BIGWIN), and pool config');
        } catch (\plugin\saiadmin\exception\ApiException $e) {
            return $this->fail($e->getMessage());
        }
    }
}
