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

use app\dice\helper\AdminScopeHelper;
use app\dice\basic\DiceBaseLogic;
use plugin\saiadmin\exception\ApiException;
use app\dice\model\player_wallet_record\DicePlayerWalletRecord;
use app\dice\model\player\DicePlayer;
use app\api\cache\UserCache;

/**
 * 玩家钱包流水逻辑层
 */
class DicePlayerWalletRecordLogic extends DiceBaseLogic
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new DicePlayerWalletRecord();
        // 默认按主键倒序：最新数据优先展示
        $this->setOrderType('DESC');
    }

    /**
     * 按与列表相同的筛选条件汇总平台币变化（不含 with / 分页 / 排序）
     */
    public function sumCoinBySearch(array $where, ?array $adminInfo, $requestDeptId = null): float
    {
        $query = $this->search($where);
        AdminScopeHelper::applyAdminScope($query, $adminInfo, $requestDeptId);
        $table = $this->model->getTable();
        $sum = $query->sum($table . '.coin');
        return round((float) $sum, 2);
    }

    /**
     * 添加数据（补全抽奖次数字段默认值）
     */
    public function add(array $data): mixed
    {
        $data['total_ticket_count'] = $data['total_ticket_count'] ?? 0;
        $data['paid_ticket_count'] = $data['paid_ticket_count'] ?? 0;
        $data['free_ticket_count'] = $data['free_ticket_count'] ?? 0;
        return parent::add($data);
    }

    /**
     * 管理员钱包操作（加点/扣点）：更新玩家平台币并创建流水记录
     * @param array $data player_id, type (3=加点 4=扣点), coin (正数), remark (可选)
     * @param int $adminId 当前管理员 id
     * @return mixed
     * @throws ApiException
     */
    public function adminOperate(array $data, int $adminId): mixed
    {
        $playerId = (int) ($data['player_id'] ?? 0);
        $type = (int) ($data['type'] ?? 0);
        $coin = (float) ($data['coin'] ?? 0);

        if ($playerId <= 0 || !in_array($type, [3, 4], true)) {
            throw new ApiException('Invalid params: player_id and type are required (3=add, 4=deduct)');
        }
        if ($coin <= 0) {
            throw new ApiException('Coin change must be greater than 0');
        }

        $player = DicePlayer::where('id', $playerId)->find();
        if (!$player) {
            throw new ApiException('Player not found');
        }

        $walletBefore = (float) ($player['coin'] ?? 0);
        if ($type === 4 && $walletBefore < $coin) {
            throw new ApiException('Deduct amount cannot exceed current balance');
        }

        $walletAfter = $type === 3 ? $walletBefore + $coin : $walletBefore - $coin;
        $remark = trim((string) ($data['remark'] ?? ''));
        if ($remark === '') {
            $remark = $type === 3 ? '管理员加点' : '管理员扣点';
        }

        DicePlayer::where('id', $playerId)->update(['coin' => $walletAfter]);

        // 出于安全：删除该玩家相关缓存，后续 API 按需重建
        UserCache::deleteUser($playerId);
        if (isset($player->username) && $player->username !== '') {
            UserCache::deletePlayerByUsername($player->username);
        }

        $playerAdminId = ($player->admin_id ?? null) ? (int) $player->admin_id : null;
        $playerDeptId = ($player->dept_id ?? null) ? (int) $player->dept_id : null;
        $record = [
            'player_id' => $playerId,
            'admin_id' => $playerAdminId,
            'dept_id' => $playerDeptId,
            'coin' => $type === 3 ? $coin : -$coin,
            'type' => $type,
            'wallet_before' => $walletBefore,
            'wallet_after' => $walletAfter,
            'remark' => $remark,
            'user_id' => $adminId,
            'total_ticket_count' => 0,
            'paid_ticket_count' => 0,
            'free_ticket_count' => 0,
        ];

        return $this->model->create($record);
    }
}
