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

use app\dice\helper\AdminScopeHelper;
use plugin\saiadmin\basic\BaseController;
use app\dice\logic\player_wallet_record\DicePlayerWalletRecordLogic;
use app\dice\validate\player_wallet_record\DicePlayerWalletRecordValidate;
use app\dice\model\player\DicePlayer;
use plugin\saiadmin\service\Permission;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

/**
 * 玩家钱包流水控制器
 */
class DicePlayerWalletRecordController extends BaseController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->logic = new DicePlayerWalletRecordLogic();
        $this->validate = new DicePlayerWalletRecordValidate;
        parent::__construct();
    }

    /**
     * 数据列表
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家钱包流水列表', 'dice:player_wallet_record:index:index')]
    public function index(Request $request): Response
    {
        $where = $request->more([
            ['type', ''],
            ['username', ''],
            ['coin_min', ''],
            ['coin_max', ''],
            ['create_time_min', ''],
            ['create_time_max', ''],
        ]);
        $deptId = $request->input('dept_id');
        $totalCoinChange = $this->logic->sumCoinBySearch($where, $this->adminInfo ?? null, $deptId);

        $query = $this->logic->search($where);
        AdminScopeHelper::applyAdminScope($query, $this->adminInfo ?? null, $deptId);
        $query->with([
            'dicePlayer',
            'operator',
        ]);

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

    /**
     * 获取玩家选项（id、username）用于下拉
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家钱包流水列表', 'dice:player_wallet_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);
    }

    /**
     * 获取指定玩家当前平台币（用于钱包操作前）
     * 类型 0=充值 1=提现 2=购买抽奖次数，操作前均为当前平台币
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家钱包流水读取', 'dice:player_wallet_record:index:read')]
    public function getPlayerWalletBefore(Request $request): Response
    {
        $playerId = $request->input('player_id');
        if ($playerId === null || $playerId === '') {
            return $this->fail('missing player_id');
        }
        $player = DicePlayer::field('coin,dept_id')->where('id', $playerId)->find();
        if (!$player) {
            return $this->fail('Player not found');
        }
        if (!AdminScopeHelper::canAccessDept($this->adminInfo ?? null, $player->dept_id ?? null)) {
            return $this->fail('no permission to operate this player');
        }
        return $this->success(['wallet_before' => (float) $player['coin']]);
    }

    /**
     * 读取数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家钱包流水读取', 'dice:player_wallet_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:player_wallet_record:index:adminOperate')]
    public function adminOperate(Request $request): Response
    {
        $data = $request->post();
        $playerId = $data['player_id'] ?? null;
        $type = isset($data['type']) ? (int) $data['type'] : null;
        $coin = isset($data['coin']) ? (float) $data['coin'] : null;

        if ($playerId === null || $playerId === '') {
            return $this->fail('please select player');
        }
        if (!in_array($type, [3, 4], true)) {
            return $this->fail('operation type must be 3 (add) or 4 (deduct)');
        }
        if ($coin === null || $coin <= 0) {
            return $this->fail('Coin change must be greater than 0');
        }

        $data['player_id'] = $playerId;
        $data['type'] = $type;
        $data['coin'] = $coin;
        $data['remark'] = $data['remark'] ?? '';

        $adminId = null;
        $checkAdmin = request()->header('check_admin');
        if (!empty($checkAdmin['id'])) {
            $adminId = (int) $checkAdmin['id'];
        }
        if (($adminId === null || $adminId <= 0)) {
            try {
                $token = JwtToken::getExtend();
                if (!empty($token['id']) && ($token['plat'] ?? '') === 'saiadmin') {
                    $adminId = (int) $token['id'];
                }
            } catch (\Throwable $e) {
                // JWT 无效或未携带
            }
        }
        if ($adminId === null || $adminId <= 0) {
            return $this->fail('please login first');
        }

        $player = DicePlayer::field('dept_id')->where('id', $playerId)->find();
        if ($player && !AdminScopeHelper::canAccessDept($this->adminInfo ?? null, $player->dept_id ?? null, $request->input('dept_id'))) {
            return $this->fail('no permission to operate this player');
        }

        try {
            $this->logic->adminOperate($data, $adminId);
            return $this->success('operation success');
        } catch (\Throwable $e) {
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 保存数据
     * @param Request $request
     * @return Response
     */
    #[Permission('玩家钱包流水添加', 'dice:player_wallet_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');
        }
        return $this->fail('add failed');
    }

}
