<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\model\PlayerLoginLogModel;
use app\model\GameBetGameModel;

/**
 * 商户用户模型 - 连接到fortue_tiger数据库的tp_merchants_user表
 */
class MerchantsUserModel extends Model
{
    // 设置数据库连接
    protected $connection = 'fortue_tiger';
    
    // 设置表名
    protected $name = 'merchants_user';

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

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

    // 设置字段类型
    protected $type = [
        'user_id' => 'int',
        'app_id' => 'int',
        'uname' => 'int',
        'nickname' => 'string',
        'cid' => 'int',
        'token' => 'string',
        'short_token' => 'string',
        'login_time' => 'int',
        'reg_ip' => 'string',
        'login_ip' => 'string',
        'today_count' => 'int',
        'history_day_count' => 'int',
        'adjust_status' => 'int',
        'status' => 'int',
        'disabled_login' => 'int',
        'create_time' => 'int',
        'update_time' => 'int',
    ];

    // 状态常量
    const STATUS_NORMAL = 1;    // 正常
    const STATUS_FROZEN = 0;    // 冻结

    // 禁止登录状态
    const LOGIN_ENABLED = 1;    // 允许登录
    const LOGIN_DISABLED = 0;   // 禁止登录

    // 调控状态常量
    const ADJUST_STATUS_NORMAL = 1;     // 正常
    const ADJUST_STATUS_WIN = 2;        // 放水(赢)
    const ADJUST_STATUS_LOSE = 3;       // 收割(输)

    /**
     * 获取状态文本
     */
    public static function getStatusText($status): string
    {
        $statusMap = [
            self::STATUS_NORMAL => '正常',
            self::STATUS_FROZEN => '冻结',
        ];
        return $statusMap[$status] ?? '未知';
    }

    /**
     * 获取调控状态文本
     */
    public static function getAdjustStatusText($adjustStatus): string
    {
        $adjustStatusMap = [
            self::ADJUST_STATUS_NORMAL => '正常',
            self::ADJUST_STATUS_WIN => '放水',
            self::ADJUST_STATUS_LOSE => '收割',
        ];
        return $adjustStatusMap[$adjustStatus] ?? '未知';
    }

    /**
     * 获取禁止登录状态文本
     */
    public static function getDisabledLoginText($disabled): string
    {
        $disabledMap = [
            self::LOGIN_ENABLED => '允许',
            self::LOGIN_DISABLED => '禁止',
        ];
        return $disabledMap[$disabled] ?? '未知';
    }

    /**
     * 通过unameList批量获取指定平台用户详情
     * @param $merchantId
     * @param $wheres
     * @return mixed
     */
    public static function getPlayerListByIds($merchantId, $wheres = [], $field = [])
    {
        $query = self::where('app_id', $merchantId)->where($wheres);
        if(!empty($field)) {
            $query = $query->field($field);
        }
        return $query->select()->toArray();
    }

    /**
     * 根据商户ID获取玩家列表
     */
    public static function getPlayerListByMerchant($merchantId, $page = 1, $limit = 10, $filters = [])
    {
        $query = self::where('app_id', $merchantId);

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

        if (!empty($filters['nickname'])) {
            $query->where('nickname', 'like', '%' . $filters['nickname'] . '%');
        }

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

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

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

        if (!empty($filters['login_ip'])) {
            $query->where('login_ip', 'like', '%' . $filters['login_ip'] . '%');
        }

        if (!empty($filters['reg_ip'])) {
            $query->where('reg_ip', 'like', '%' . $filters['reg_ip'] . '%');
        }

        // 登录时间范围
        if (!empty($filters['login_time_start'])) {
            $query->where('login_time', '>=', strtotime($filters['login_time_start']));
        }
        if (!empty($filters['login_time_end'])) {
            $query->where('login_time', '<=', strtotime($filters['login_time_end']));
        }

       
        $order = $filters['order'] ?? 'user_id';
        $sort = $filters['sort'] ?? 'desc';
        $query->order($order, $sort);

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

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

        $user_ids = array_column($list, 'user_id');

        // 获取余额
        $userBalanceConfig = MerchantsUserBalanceModel::getUsersBalanceList($merchantId, $user_ids);
        // 获取今日登录次数
        $loginFilter = [
            'start_time' => date('Y-m-d'),
            'end_time' => date('Y-m-d', strtotime('tomorrow')),
        ];
        $loginCount = PlayerLoginLogModel::getLoginPlayerCount($merchantId, $user_ids, $loginFilter);
        $betGameFilter = [
            'start_time' => date('Y-m-d'),
            'end_time' => date('Y-m-d', strtotime('tomorrow')),
            'user_ids' => $user_ids,
        ];        
        // 获取今日输赢、今日下注
        $betGameSummary = GameBetGameModel::getGameUserSummary($merchantId, $betGameFilter);
        
        // 转换字段名以保持与原有接口的兼容性
        foreach ($list as &$item) {
            $userBalanceInfo = $userBalanceConfig[$item['user_id']] ?? [];
            $item['merchant_id'] = $item['app_id'];
            $item['today_login_count'] = $loginCount[$item['user_id']]['count'] ?? 0;
            $item['history_login_count'] = $item['history_day_count'];
            // 添加原系统中可能需要但新表中没有的字段
            $item['balance'] =  $userBalanceInfo['balance'] ?? 0;
            $item['today_win_amount'] = $betGameSummary['game_profit'] ?? 0;
            $item['history_win_amount'] = (float)$item['total_win_amount'];
            $item['today_bet_amount'] = $betGameSummary['bet_amount'] ?? 0;;

            // 移除字段
            unset($item['app_id']);
            unset($item['token']);
            unset($item['short_token']);            
        }

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

    /**
     * 获取玩家详情
     */
    public static function getPlayerDetail($playerId, $merchantId)
    {
        $player = self::where('user_id', $playerId)
            ->where('app_id', $merchantId)
            ->find();
            
        if ($player) {
            $player = $player->toArray();
            // 移除敏感字段
            unset($player['token']);
            unset($player['short_token']);
            
            // 转换字段名
            $player['merchant_id'] = $player['app_id'];
            $player['today_login_count'] = $player['today_count'];
            $player['history_login_count'] = $player['history_day_count'];
            // 添加原系统中可能需要但新表中没有的字段
            $player['balance'] = 0;
            $player['today_win_amount'] = 0;
            $player['history_win_amount'] = 0;
            $player['today_bet_amount'] = 0;
        }
        
        return $player;
    }

    /**
     * 更新玩家状态
     */
    public static function updatePlayerStatus($playerIds, $merchantId, $status)
    {
        return self::where('app_id', $merchantId)
            ->whereIn('user_id', $playerIds)
            ->update(['status' => $status]);
    }

    /**
     * 更新玩家调控状态
     */
    public static function updatePlayerAdjustStatus($playerIds, $merchantId, $adjustStatus)
    {
        return self::where('app_id', $merchantId)
            ->whereIn('user_id', $playerIds)
            ->update(['adjust_status' => $adjustStatus]);
    }

    /**
     * 更新玩家禁止登录状态
     */
    public static function updatePlayerLoginStatus($playerIds, $merchantId, $disabledLogin)
    {
        return self::where('app_id', $merchantId)
            ->whereIn('uname', $playerIds)
            ->update(['disabled_login' => $disabledLogin]);
    }

    /**
     * 获取玩家统计信息
     */
    public static function getPlayerStatistics($merchantId, $filters = [])
    {
        $where = [
            ['app_id', '=', $merchantId]
        ];
        
        $getWhere = function(string $timeField) use ($where, $filters) {
            // 时间筛选
            if (!empty($filters['start_time'])) {
                $startTime = strtotime($filters['start_time']);
                $where[] = [$timeField, '>=', $startTime];
            }
            
            if (!empty($filters['end_time'])) {
                $endTime = strtotime($filters['end_time']);
                $where[] = [$timeField, '<=', $endTime];
            }            
            return $where;
        };

        // 获取每日注册用户数
        $registerUsers = self::where($getWhere('create_time'))->field([
                    "FROM_UNIXTIME(create_time, '%Y-%m-%d') as date", // 日期
                    'COUNT(user_id) as count',  // 注册用户数
            ])
            ->group('date')
            ->select()
            ->toArray();
        // 获取每日登录用户数
        $loginUsers = PlayerLoginLogModel::getLoginDateCount($merchantId, $filters);

        $staticData = ['register' => array_column($registerUsers, null, 'date'), 'login' => $loginUsers];
        return $staticData;
    }
}