<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * 用户操作日志模型
 */
class UserBehaviorLogModel extends Model
{
    // 设置表名
    protected $table = 'merchant_user_behavior_log';
    
    // 设置主键
    protected $pk = 'id';
    
    // 操作状态常量
    const STATUS_FAILED = 0;  // 操作失败
    const STATUS_SUCCESS = 1; // 操作成功
    
    /**
     * 记录操作日志
     * @param array $data 日志数据
     * @return bool
     */
    public static function recordBehavior(array $data): bool
    {
        try {
            $log = new self();
            $log->merchant_id = $data['merchant_id'] ?? 0;
            $log->user_id = $data['user_id'] ?? 0;
            $log->behavior = $data['behavior'] ?? '';
            $log->behavior_desc = $data['behavior_desc'] ?? '';
            $log->behavior_ip = $data['behavior_ip'] ?? '';
            $log->behavior_url = $data['behavior_url'] ?? '';
            $log->create_time = time();
            $log->behavior_status = $data['behavior_status'] ?? self::STATUS_SUCCESS;
            
            return $log->save();
        } catch (\Exception $e) {
            // 记录日志失败不影响业务流程
            return false;
        }
    }
    
    /**
     * 获取操作日志列表
     * @param int $merchantId 商户ID
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param array $filters 过滤条件
     * @return array
     */
    public static function getBehaviorLogs(int $merchantId, int $page = 1, int $limit = 20, array $filters = []): array
    {
        $where = [
            ['merchant_id', '=', $merchantId]
        ];
        
        // 用户ID筛选
        if (!empty($filters['user_id'])) {
            $where[] = ['user_id', '=', $filters['user_id']];
        }
        
        // 行为类型筛选
        if (!empty($filters['behavior'])) {
            $where[] = ['behavior', '=', $filters['behavior']];
        }
        
        // 操作状态筛选
        if (isset($filters['behavior_status']) && $filters['behavior_status'] !== '') {
            $where[] = ['behavior_status', '=', $filters['behavior_status']];
        }
        
        // IP地址筛选
        if (!empty($filters['behavior_ip'])) {
            $where[] = ['behavior_ip', 'like', '%' . $filters['behavior_ip'] . '%'];
        }
        
        // 时间范围筛选
        if (!empty($filters['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($filters['start_time'])];
        }
        if (!empty($filters['end_time'])) {
            $where[] = ['create_time', '<=', strtotime($filters['end_time'])];
        }
        
        // 关键词搜索（在行为描述中搜索）
        if (!empty($filters['keyword'])) {
            $where[] = ['behavior_desc', 'like', '%' . $filters['keyword'] . '%'];
        }
        
        $query = self::where($where);
        
        $total = $query->count();
        
        $list = $query->field('id, merchant_id, user_id, behavior, behavior_desc, behavior_ip, behavior_url, create_time, behavior_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['behavior_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 getRecentBehaviors(int $userId, int $limit = 10): array
    {
        $list = self::where('user_id', $userId)
            ->field('behavior, behavior_desc, behavior_ip, behavior_url, create_time, behavior_status')
            ->order('id', 'desc')
            ->limit($limit)
            ->select()
            ->toArray();
            
        // 格式化数据
        foreach ($list as &$log) {
            $log['status_text'] = $log['behavior_status'] == self::STATUS_SUCCESS ? '成功' : '失败';
            $log['create_time_text'] = date('Y-m-d H:i:s', $log['create_time']);
            
            // 解析请求参数
            try {
                $log['params'] = json_decode($log['behavior_desc'], true) ?: [];
            } catch (\Exception $e) {
                $log['params'] = [];
            }
        }
        
        return $list;
    }
    
    /**
     * 获取操作统计信息
     * @param int $merchantId 商户ID
     * @param int $userId 用户ID（可选）
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    public static function getBehaviorStatistics(int $merchantId, int $userId = 0, string $startDate = '', string $endDate = ''): array
    {
        $where = [
            ['merchant_id', '=', $merchantId]
        ];
        
        if ($userId > 0) {
            $where[] = ['user_id', '=', $userId];
        }
        
        if ($startDate) {
            $where[] = ['create_time', '>=', strtotime($startDate)];
        }
        
        if ($endDate) {
            $where[] = ['create_time', '<=', strtotime($endDate . ' 23:59:59')];
        }
        
        // 总操作次数
        $totalCount = self::where($where)->count();
        
        // 成功次数
        $successCount = self::where($where)
            ->where('behavior_status', self::STATUS_SUCCESS)
            ->count();
            
        // 失败次数
        $failedCount = self::where($where)
            ->where('behavior_status', self::STATUS_FAILED)
            ->count();
            
        // 活跃用户数
        $activeUsers = self::where($where)
            ->group('user_id')
            ->count();
            
        // 按行为类型统计
        $behaviorStats = self::where($where)
            ->field('behavior, count(*) as count')
            ->group('behavior')
            ->select()
            ->toArray();
            
        // 行为统计已经是权限配置中的描述，无需额外处理
        
        return [
            'total_count' => $totalCount,
            'success_count' => $successCount,
            'failed_count' => $failedCount,
            'success_rate' => $totalCount > 0 ? round($successCount / $totalCount * 100, 2) : 0,
            'active_users' => $activeUsers,
            'behavior_stats' => $behaviorStats
        ];
    }
    
    /**
     * 获取所有行为类型（从权限配置中获取）
     * @return array
     */
    public static function getAllBehaviors(): array
    {
        $behaviors = [];
        $permissions = config('permission.permissions');
        
        foreach ($permissions as $controller => $moduleInfo) {
            $module = $moduleInfo['module'] ?? $controller;
            foreach ($moduleInfo['actions'] ?? [] as $action => $desc) {
                $behaviors[] = [
                    'value' => $module . '-' . $desc,
                    'label' => $module . '-' . $desc
                ];
            }
        }
        
        return $behaviors;
    }
}