<?php
declare (strict_types = 1);

namespace app\controller;

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

/**
 * 操作日志控制器
 */
class BehaviorLog extends BaseController
{
    /**
     * 获取操作日志列表
     */
    public function list()
    {
        $userInfo = $this->request->userInfo;
        
        // 获取查询参数
        $page = Request::get('page', 1, 'intval');
        $limit = Request::get('limit', 20, 'intval');
        
        // 过滤条件
        $filters = [
            'user_id' => Request::get('user_id', 0, 'intval'),
            'behavior' => Request::get('behavior', '', 'trim'),
            'behavior_status' => Request::get('behavior_status', ''),
            'behavior_ip' => Request::get('behavior_ip', '', 'trim'),
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
            'keyword' => Request::get('keyword', '', 'trim'),
        ];
        
        try {
            $result = UserBehaviorLogModel::getBehaviorLogs($userInfo['merchant_id'], $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 = UserBehaviorLogModel::getBehaviorStatistics($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 = UserBehaviorLogModel::getRecentBehaviors($userId, $limit);
            
            return json_success([
                'logs' => $logs,
                'user_id' => $userId
            ], '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取最近操作记录失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取所有行为类型
     */
    public function getBehaviorTypes()
    {
        try {
            $behaviors = UserBehaviorLogModel::getAllBehaviors();
            return json_success($behaviors, '获取成功');
        } 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 = UserBehaviorLogModel::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->behavior_status == UserBehaviorLogModel::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 json_success($log, '获取成功');
        } catch (\Exception $e) {
            return json_error([], '获取日志详情失败：' . $e->getMessage());
        }
    }
    
    /**
     * 导出操作日志
     */
    public function export()
    {
        $userInfo = $this->request->userInfo;
        
        // 过滤条件
        $filters = [
            'user_id' => Request::get('user_id', 0, 'intval'),
            'behavior' => Request::get('behavior', '', 'trim'),
            'behavior_status' => Request::get('behavior_status', ''),
            'behavior_ip' => Request::get('behavior_ip', '', 'trim'),
            'start_time' => Request::get('start_time', '', 'trim'),
            'end_time' => Request::get('end_time', '', 'trim'),
            'keyword' => Request::get('keyword', '', 'trim'),
        ];
        
        try {
            // 获取所有符合条件的数据（不分页）
            $result = UserBehaviorLogModel::getBehaviorLogs($userInfo['merchant_id'], 1, 100000, $filters);
            
            // 生成CSV数据
            $csvData = "ID,用户名,昵称,操作行为,请求参数,操作IP,操作URL,操作时间,操作状态\n";
            
            foreach ($result['list'] as $log) {
                // 处理请求参数，移除换行符
                $params = str_replace(["\r", "\n"], ' ', $log['behavior_desc']);
                
                $csvData .= sprintf(
                    "%d,%s,%s,%s,%s,%s,%s,%s,%s\n",
                    $log['id'],
                    $log['user_name'],
                    $log['nick_name'],
                    $log['behavior'],
                    $params,
                    $log['behavior_ip'],
                    $log['behavior_url'],
                    $log['create_time_text'],
                    $log['status_text']
                );
            }
            
            // 返回CSV数据
            return response($csvData)
                ->header(['Content-Type' => 'text/csv; charset=utf-8'])
                ->header(['Content-Disposition' => 'attachment; filename="behavior_logs_' . date('YmdHis') . '.csv"'])
                ->header(['Cache-Control' => 'no-cache, must-revalidate']);
                
        } catch (\Exception $e) {
            return json_error([], '导出操作日志失败：' . $e->getMessage());
        }
    }
}