<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * 用户登录日志模型
 */
class UserLoginLogModel extends Model
{
    // 设置表名
    protected $table = 'merchant_user_login_log';
    
    // 设置主键
    protected $pk = 'id';
    
    // 登录状态常量
    const STATUS_FAILED = 0;  // 登录失败
    const STATUS_SUCCESS = 1; // 登录成功
    
    /**
     * 记录登录日志
     * @param array $data 日志数据
     * @return bool
     */
    public static function recordLogin(array $data): bool
    {
        try {
            $log = new self();
            $log->merchant_id = $data['merchant_id'] ?? 0;
            $log->user_id = $data['user_id'] ?? 0;
            $log->login_device = $data['login_device'] ?? '';
            $log->login_ip = $data['login_ip'] ?? '';
            $log->login_time = time();
            $log->login_status = $data['login_status'] ?? self::STATUS_FAILED;
            
            return $log->save();
        } catch (\Exception $e) {
            // 记录日志失败不影响登录流程
            return false;
        }
    }
    
    /**
     * 获取登录日志列表
     * @param int $merchantId 商户ID
     * @param int $userId 用户ID（可选）
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param array $filters 过滤条件
     * @return array
     */
    public static function getLoginLogs(int $merchantId, int $userId = 0, int $page = 1, int $limit = 20, array $filters = []): array
    {
        $where = [
            ['merchant_id', '=', $merchantId]
        ];
        
        // 如果指定了用户ID
        if ($userId > 0) {
            $where[] = ['user_id', '=', $userId];
        }
        
        // 登录状态筛选
        if (isset($filters['login_status']) && $filters['login_status'] !== '') {
            $where[] = ['login_status', '=', $filters['login_status']];
        }
        
        // IP地址筛选
        if (!empty($filters['login_ip'])) {
            $where[] = ['login_ip', 'like', '%' . $filters['login_ip'] . '%'];
        }
        
        // 时间范围筛选
        if (!empty($filters['start_time'])) {
            $where[] = ['login_time', '>=', strtotime($filters['start_time'])];
        }
        if (!empty($filters['end_time'])) {
            $where[] = ['login_time', '<=', strtotime($filters['end_time'])];
        }
        
        $query = self::where($where);
        
        $total = $query->count();
        
        $list = $query->field('id, merchant_id, user_id, login_device, login_ip, login_time, login_status')
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select();
            
        // 获取相关用户信息
        if ($list->count() > 0) {
            $userIds = array_unique(array_column($list->toArray(), 'user_id'));
            $users = UserModel::whereIn('user_id', $userIds)
                ->field('user_id, user_name, nick_name')
                ->select()
                ->toArray();
            
            $userMap = [];
            foreach ($users as $user) {
                $userMap[$user['user_id']] = $user;
            }
            
            // 添加用户信息到日志记录
            foreach ($list as &$log) {
                $log['user_name'] = $userMap[$log['user_id']]['user_name'] ?? '';
                $log['nick_name'] = $userMap[$log['user_id']]['nick_name'] ?? '';
                $log['status_text'] = $log['login_status'] == self::STATUS_SUCCESS ? '成功' : '失败';
            }
        }
        
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }
    
    /**
     * 获取用户最近登录记录
     * @param int $userId 用户ID
     * @param int $limit 获取数量
     * @return array
     */
    public static function getRecentLogs(int $userId, int $limit = 10): array
    {
        return self::where('user_id', $userId)
            ->field('login_device, login_ip, login_time, login_status')
            ->order('id', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
    }
    
    /**
     * 获取登录统计信息
     * @param int $merchantId 商户ID
     * @param int $userId 用户ID（可选）
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    public static function getLoginStatistics(int $merchantId, int $userId = 0, string $startDate = '', string $endDate = ''): array
    {
        $where = [
            ['merchant_id', '=', $merchantId]
        ];
        
        if ($userId > 0) {
            $where[] = ['user_id', '=', $userId];
        }
        
        if ($startDate) {
            $where[] = ['login_time', '>=', strtotime($startDate)];
        }
        
        if ($endDate) {
            $where[] = ['login_time', '<=', strtotime($endDate . ' 23:59:59')];
        }
        
        // 总登录次数
        $totalCount = self::where($where)->count();
        
        // 成功次数
        $successCount = self::where($where)
            ->where('login_status', self::STATUS_SUCCESS)
            ->count();
            
        // 失败次数
        $failedCount = self::where($where)
            ->where('login_status', self::STATUS_FAILED)
            ->count();
            
        // 独立IP数
        $uniqueIps = self::where($where)
            ->group('login_ip')
            ->count();
            
        return [
            'total_count' => $totalCount,
            'success_count' => $successCount,
            'failed_count' => $failedCount,
            'success_rate' => $totalCount > 0 ? round($successCount / $totalCount * 100, 2) : 0,
            'unique_ips' => $uniqueIps
        ];
    }
}