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

use app\dice\helper\AdminScopeHelper;
use plugin\saiadmin\basic\BaseController;
use app\dice\logic\play_record\DicePlayRecordLogic;
use app\dice\validate\play_record\DicePlayRecordValidate;
use app\dice\model\player\DicePlayer;
use app\dice\model\lottery_pool_config\DiceLotteryPoolConfig;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;

/**
 * 玩家抽奖记录控制器
 */
class DicePlayRecordController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new DicePlayRecordLogic();
        $this->validate = new DicePlayRecordValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录列表', 'dice:play_record:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['username', ''],
            ['lottery_config_name', ''],
            ['lottery_type', ''],
            ['is_win', ''],
            ['win_coin_min', ''],
            ['win_coin_max', ''],
            ['roll_number_min', ''],
            ['roll_number_max', ''],
            ['reward_ui_text', ''],
            ['reward_tier', ''],
            ['direction', ''],
        ]);
        $query = $this->logic->search($where);
        AdminScopeHelper::applyAdminScope($query, $this->adminInfo ?? null, $request->input('dept_id'));
        $query->with([
            'dicePlayer',
            'diceLotteryPoolConfig',
        ]);

        // 按当前筛选条件统计：平台总盈利 = 付费金额(paid_amount 求和) - 玩家总收益(win_coin 求和)
        $sumQuery = clone $query;
        $playerTotalWin = (float) $sumQuery->sum('win_coin');
        $paidAmountQuery = clone $query;
        $paidAmount = (float) $paidAmountQuery->where('lottery_type', 0)->sum('paid_amount');
        $totalWinCoin = round($paidAmount - $playerTotalWin, 2);

        $data = $this->logic->getList($query);
        $data['total_win_coin'] = $totalWinCoin;
        return $this->success($data);
    }

    /**
     * 获取玩家选项（id、username）
     */
    #[Permission('玩家抽奖记录列表', 'dice:play_record:index:index')]
    public function getPlayerOptions(Request $request): Response
    {
        $query = DicePlayer::field('id,username');
        AdminScopeHelper::applyAdminScope($query, $this->adminInfo ?? null, $request->input('dept_id'));
        $list = $query->select();
        $data = $list->map(function ($item) {
            return ['id' => $item['id'], 'username' => $item['username'] ?? ''];
        })->toArray();
        return $this->success($data);
    }

    /**
     * 获取彩金池配置选项（id、name）
     */
    #[Permission('玩家抽奖记录列表', 'dice:play_record:index:index')]
    public function getLotteryConfigOptions(Request $request): Response
    {
        $query = DiceLotteryPoolConfig::field('id,name,remark')->order('id', 'asc');
        $requestDeptId = AdminScopeHelper::pickRequestDeptId(
            $request->input('dept_id'),
            $request->all()
        );
        AdminScopeHelper::applyConfigScope($query, $this->adminInfo ?? null, $requestDeptId);
        $list = $query->select();
        $data = $list->map(function ($item) {
            $row = is_array($item) ? $item : $item->toArray();
            return [
                'id'           => (int) ($row['id'] ?? 0),
                'name'         => (string) ($row['name'] ?? ''),
                'remark'       => (string) ($row['remark'] ?? ''),
                'display_name' => DiceLotteryPoolConfig::displayLabel($row),
            ];
        })->toArray();
        return $this->success($data);
    }

    /**
     * 读取数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录读取', 'dice:play_record:index:read')]
    public function read(Request $request): Response
    {
        $id = $request->input('id', '');
        $model = $this->logic->read($id);
        if (!$model) {
            return $this->fail('not found');
        }
        if (!AdminScopeHelper::canAccessDept($this->adminInfo ?? null, $model->dept_id ?? null)) {
            return $this->fail('no permission to view this record');
        }
        $data = is_array($model) ? $model : $model->toArray();
        return $this->success($data);
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家抽奖记录添加', 'dice:play_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:play_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');
        }
    }

}
