<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use think\facade\Request;
use app\model\UserLoginLogModel;
use app\model\UserModel;

/**
 * 登录日志控制器
 */
class LoginLog extends BaseController
{
    /**
     * 获取登录日志列表
     */
    public function list()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 20, 'intval');
        $userId = Request::get('user_id', 0, 'intval');
        
        // 过滤条件
        $filters = [
            'login_status' => Request::get('login_status', ''),
            'login_ip' => Request::get('login_ip', '', 'trim'),
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
        ];
        
        try {
            $result = UserLoginLogModel::getLoginLogs($userInfo['merchant_id'], $userId, $page, $limit, $filters);
            return json_success($result, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取登录日志失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取登录统计信息
     */
    public function statistics()
    {
        $userInfo = $this->request->userInfo;
        
        $userId = Request::get('user_id', 0, 'intval');
        $startDate = Request::get('start_date', '', 'trim');
        $endDate = Request::get('end_date', '', 'trim');
        
        // 如果没有指定日期范围，默认获取最近30天
        if (empty($startDate)) {
            $startDate = date('Y-m-d', strtotime('-30 days'));
        }
        if (empty($endDate)) {
            $endDate = date('Y-m-d');
        }
        
        try {
            $statistics = UserLoginLogModel::getLoginStatistics($userInfo['merchant_id'], $userId, $startDate, $endDate);
            
            return json_success([
                'statistics' => $statistics,
                'date_range' => [
                    'start_date' => $startDate,
                    'end_date' => $endDate
                ]
            ], '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取登录统计失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户最近登录记录
     */
    public function recentLogs()
    {
        $userInfo = $this->request->userInfo;
        
        $userId = Request::get('user_id', 0, 'intval');
        $limit = Request::get('limit', 10, 'intval');
        
        // 如果没有指定用户ID，则获取当前用户的登录记录
        if ($userId == 0) {
            $userId = $userInfo['user_id'];
        } else {
            // 验证用户是否属于当前商户
            $user = UserModel::where('user_id', $userId)
                ->where('merchant_id', $userInfo['merchant_id'])
                ->find();
            
            if (!$user) {
                return json_error([], '用户不存在');
            }
        }
        
        try {
            $logs = UserLoginLogModel::getRecentLogs($userId, $limit);
            
            // 格式化日志数据
            foreach ($logs as &$log) {
                $log['status_text'] = $log['login_status'] == UserLoginLogModel::STATUS_SUCCESS ? '成功' : '失败';
                $log['login_time_text'] = date('Y-m-d H:i:s', $log['login_time']);
            }
            
            return json_success([
                'logs' => $logs,
                'user_id' => $userId
            ], '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取最近登录记录失败：' . $e->getMessage());
        }
    }
    
    /**
     * 导出登录日志
     */
    public function export()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $userId = Request::get('user_id', 0, 'intval');
        
        // 过滤条件
        $filters = [
            'login_status' => Request::get('login_status', ''),
            'login_ip' => Request::get('login_ip', '', 'trim'),
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
        ];
        
        try {
            // 获取所有符合条件的数据（不分页）
            $result = UserLoginLogModel::getLoginLogs($userInfo['merchant_id'], $userId, 1, 100000, $filters);
            
            // 生成CSV数据
            $csvData = "ID,用户名,昵称,登录设备,登录IP,登录时间,登录状态\n";
            
            foreach ($result['list'] as $log) {
                // 格式化登录时间
                $loginTime = date('Y-m-d H:i:s', $log['login_time']);
                
                // 处理设备信息，移除换行符
                $device = str_replace(["\r", "\n"], ' ', $log['login_device']);
                
                $csvData .= sprintf(
                    "%d,%s,%s,%s,%s,%s,%s\n",
                    $log['id'],
                    $log['user_name'],
                    $log['nick_name'],
                    $device,
                    $log['login_ip'],
                    $loginTime,
                    $log['status_text']
                );
            }
            
            // 返回CSV数据
            return response($csvData)
                ->header(['Content-Type' => 'text/csv; charset=utf-8'])
                ->header(['Content-Disposition' => 'attachment; filename="login_logs_' . date('YmdHis') . '.csv"'])
                ->header(['Cache-Control' => 'no-cache, must-revalidate']);
                
        } catch (\Exception $e) {
            return json_error([], '导出登录日志失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取登录日志详情
     */
    public function detail()
    {
        $userInfo = $this->request->userInfo;
        
        $id = Request::get('id', 0, 'intval');
        if (!$id) {
            return json_error([], '日志ID不能为空');
        }
        
        try {
            $log = UserLoginLogModel::where('id', $id)
                ->where('merchant_id', $userInfo['merchant_id'])
                ->find();
                
            if (!$log) {
                return json_error([], '日志不存在');
            }
            
            // 获取用户信息
            $user = UserModel::where('user_id', $log->user_id)->find();
            if ($user) {
                $log->user_name = $user->user_name;
                $log->nick_name = $user->nick_name;
            }
            
            // 格式化数据
            $log->status_text = $log->login_status == UserLoginLogModel::STATUS_SUCCESS ? '成功' : '失败';
            $log->login_time_text = date('Y-m-d H:i:s', $log->login_time);
            
            return json_success($log, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取日志详情失败：' . $e->getMessage());
        }
    }
}