<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * 商户游戏模型
 */
class GameModel extends Model
{
    // 设置表名
    protected $name = 'game_list';

    // 设置主键
    protected $pk = 'id';

    // 设置自动时间戳
    protected $autoWriteTimestamp = 'int';

    // 设置字段类型
    protected $type = [
        'id' => 'int',
        'merchant_id' => 'int',
        'game_platform' => 'string',
        'game_id' => 'int',
        'title' => 'string',
        'title_en' => 'string',
        'image' => 'string',
        'image_en' => 'string',
        'rtp' => 'float',
        'rtp_type' => 'int',
        'free_game_status' => 'int',
        'bet_line_count' => 'int',
        'bet_max_level' => 'int',
        'max_multiple_count' => 'int',
        'deposit_list' => 'string',
        'default_deposit' => 'float',
        'default_deposit_level' => 'int',
        'min_deposit' => 'float',
        'terminal_spin' => 'int',
        'status' => 'int',
        'create_time' => 'int',
        'update_time' => 'int',
    ];

    // 状态常量
    const STATUS = [
        0 => "初始",
        1 => "正常",
        2 => "维护",
    ];

    // 止损止赢功能开关状态
    const FREE_STATUS = [
        0 => '关闭',
        1 => '开启',
    ];

    // 购买免费游戏功能开关状态
    const TERMINAL_SPIN_STATUS = [
        0 => '关闭',
        1 => '开启',
    ];

    /**
     * 获取状态文本
     */
    public static function getStatusText($status): string
    {
        return self::STATUS[$status] ?? '未知';
    }

    /**
     * 获取RTP类型文本
     */
    public static function getRtpTypeText($rtpType): string
    {
        $rtpTypeMap = $GLOBALS['gamePgGameConfig']['rtp_type_config'];
        return $rtpTypeMap[$rtpType]['name'] ?? '未知';
    }

    /**
     * 获取游戏平台文本
     */
    public static function getPlatFormText($platform): string
    {
        $platforms = self::getAllPlatforms();
        return $platforms[$platform] ?? '未知';
    }

    /**
     * 获取游戏列表
     */
    public static function getGameList($merchantId, $page = 1, $limit = 10, $filters = [])
    {
        $query = self::where('merchant_id', $merchantId); // 按商户ID过滤

        // 应用过滤条件
        if (!empty($filters['title'])) {
            $query->where(function($q) use ($filters) {
                $q->where('title', 'like', '%' . $filters['title'] . '%')
                  ->whereOr('title_en', 'like', '%' . $filters['title'] . '%');
            });
        }

        if (!empty($filters['game_id'])) {
            $query->where('game_id', $filters['game_id']);
        }

        if (isset($filters['game_platform']) && $filters['game_platform'] !== '') {
            $query->where('game_platform', $filters['game_platform']);
        }

        if (isset($filters['status']) && $filters['status'] !== '') {
            $query->where('status', $filters['status']);
        }

        if (isset($filters['rtp_type']) && $filters['rtp_type'] !== '') {
            $query->where('rtp_type', $filters['rtp_type']);
        }

        if (isset($filters['free_game_status']) && $filters['free_game_status'] !== '') {
            $query->where('free_game_status', $filters['free_game_status']);
        }

        if (isset($filters['terminal_spin']) && $filters['terminal_spin'] !== '') {
            $query->where('terminal_spin', $filters['terminal_spin']);
        }

        // RTP范围
        if (!empty($filters['rtp_min'])) {
            $query->where('rtp', '>=', $filters['rtp_min']);
        }
        if (!empty($filters['rtp_max'])) {
            $query->where('rtp', '<=', $filters['rtp_max']);
        }

        // 最高倍数范围
        if (!empty($filters['max_multiple_min'])) {
            $query->where('max_multiple_count', '>=', $filters['max_multiple_min']);
        }
        if (!empty($filters['max_multiple_max'])) {
            $query->where('max_multiple_count', '<=', $filters['max_multiple_max']);
        }

        // 创建时间范围
        if (!empty($filters['create_time_start'])) {
            $query->where('create_time', '>=', strtotime($filters['create_time_start']));
        }
        if (!empty($filters['create_time_end'])) {
            $query->where('create_time', '<=', strtotime($filters['create_time_end']));
        }

        // 排序
        $order = $filters['order'] ?? 'id';
        $sort = $filters['sort'] ?? 'desc';
        $query->order($order, $sort);

        // 获取总数
        $total = $query->count();

        // 获取列表
        $list = $query->page($page, $limit)->select()->toArray();

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    public static function getGames($merchantId, $filters = [], $field = ['id', 'game_id', 'title'])
    {
        $query = self::where('merchant_id', $merchantId);
        // 排序
        $order = $filters['order'] ?? 'id';
        $sort = $filters['sort'] ?? 'desc';
        $query->order($order, $sort);

        return $query->field($field)->select()->toArray();
    }    

    /**
     * 获取游戏详情
     */
    public static function getGameDetail($merchantId, $filters = [])
    {
        $query = self::where('merchant_id', $merchantId);
        if (!empty($filters['id'])) {
            $query->where('id', $filters['id']);
        }

        if (!empty($filters['game_id'])) {
            $query->where('game_id', $filters['game_id']);
        }

        return $query->find()->toArray();
    }

    /**
     * 创建游戏
     */
    public static function createGame($merchantId, $data)
    {
        // 处理押注配置
        if (isset($data['deposit_list']) && is_array($data['deposit_list'])) {
            $data['deposit_list'] = json_encode($data['deposit_list']);
        }
        
        // 添加商户ID
        $data['merchant_id'] = $merchantId;
        
        return self::create($data);
    }

    /**
     * 更新游戏
     */
    public static function updateGame($merchantId, $id, $data)
    {
        // 处理押注配置
        if (isset($data['deposit_list']) && is_array($data['deposit_list'])) {
            $data['deposit_list'] = json_encode($data['deposit_list']);
        }
        
        return self::where('id', $id)
            ->where('merchant_id', $merchantId)
            ->update($data);
    }

    /**
     * 更新游戏状态
     */
    public static function updateGameStatus($merchantId, $ids, $status)
    {
       return self::whereIn('id', $ids)
            ->where('merchant_id', $merchantId)
            ->update(['status' => $status]);
    }    

    /**
     * 获取所有游戏平台
     */
    public static function getAllPlatforms(): array
    {
        return $GLOBALS['gameGameTypeConfig'];
    }

    /**
     * 解析押注配置
     */
    public function getDepositListAttr($value)
    {
        if (empty($value)) {
            return [];
        }
        
        // 如果是JSON字符串，解析它
        $decoded = json_decode($value, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $decoded;
        }
        
        // 如果是逗号分隔的字符串，转换为数组
        if (strpos($value, ',') !== false) {
            return array_map('floatval', explode(',', $value));
        }
        
        return [];
    }

    /**
     * 检查游戏ID是否已存在
     */
    public static function checkGameIdExists($merchantId, $gameId, $excludeId = null): bool
    {
        $query = self::where('game_id', $gameId)
            ->where('merchant_id', $merchantId);
        if ($excludeId) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->count() > 0;
    }
    
    /**
     * 删除游戏
     */
    public static function deleteGame($merchantId, $id): bool
    {
        return self::where('id', $id)
            ->where('merchant_id', $merchantId)
            ->delete() > 0;
    }
}