package com.pangu.system.controller;

import com.pangu.common.core.controller.BaseController;
import com.pangu.common.core.domain.AjaxResult;
import com.pangu.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 日志管理Controller
 * @author 湖北新华业务中台研发团队
 */
@RestController
@RequestMapping("/api/system/log")
public class SysLogController extends BaseController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // ==================== 操作日志 ====================

    /**
     * 查询操作日志列表
     */
    @GetMapping("/operlog/list")
    public TableDataInfo operlogList(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String operName,
            @RequestParam(required = false) Integer businessType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String beginTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT oper_id, title, business_type, method, request_method, operator_type, ");
        sql.append("oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, ");
        sql.append("json_result, status, error_msg, oper_time, cost_time ");
        sql.append("FROM sys_oper_log WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        if (title != null && !title.isEmpty()) {
            sql.append("AND title LIKE ? ");
            params.add("%" + title + "%");
        }
        if (operName != null && !operName.isEmpty()) {
            sql.append("AND oper_name LIKE ? ");
            params.add("%" + operName + "%");
        }
        if (businessType != null) {
            sql.append("AND business_type = ? ");
            params.add(businessType);
        }
        if (status != null) {
            sql.append("AND status = ? ");
            params.add(status);
        }
        if (beginTime != null && !beginTime.isEmpty()) {
            sql.append("AND oper_time >= ? ");
            params.add(beginTime);
        }
        if (endTime != null && !endTime.isEmpty()) {
            sql.append("AND oper_time <= ? ");
            params.add(endTime + " 23:59:59");
        }
        
        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, params.toArray(), Integer.class);
        
        sql.append("ORDER BY oper_time DESC LIMIT ? OFFSET ?");
        params.add(pageSize);
        params.add((pageNum - 1) * pageSize);
        
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(rows);
        dataInfo.setTotal(total != null ? total : 0);
        return dataInfo;
    }

    /**
     * 删除操作日志
     */
    @DeleteMapping("/operlog/{operIds}")
    public AjaxResult removeOperlog(@PathVariable String operIds) {
        String[] ids = operIds.split(",");
        for (String id : ids) {
            jdbcTemplate.update("DELETE FROM sys_oper_log WHERE oper_id = ?", Long.valueOf(id));
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 清空操作日志
     */
    @DeleteMapping("/operlog/clean")
    public AjaxResult cleanOperlog() {
        jdbcTemplate.update("TRUNCATE TABLE sys_oper_log");
        return AjaxResult.success("清空成功");
    }

    // ==================== 登录日志 ====================

    /**
     * 查询登录日志列表
     */
    @GetMapping("/logininfor/list")
    public TableDataInfo logininforList(
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String ipaddr,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String beginTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT info_id, user_name, ipaddr, login_location, browser, os, status, msg, login_time ");
        sql.append("FROM sys_logininfor WHERE 1=1 ");
        
        List<Object> params = new ArrayList<>();
        if (userName != null && !userName.isEmpty()) {
            sql.append("AND user_name LIKE ? ");
            params.add("%" + userName + "%");
        }
        if (ipaddr != null && !ipaddr.isEmpty()) {
            sql.append("AND ipaddr LIKE ? ");
            params.add("%" + ipaddr + "%");
        }
        if (status != null && !status.isEmpty()) {
            sql.append("AND status = ? ");
            params.add(status);
        }
        if (beginTime != null && !beginTime.isEmpty()) {
            sql.append("AND login_time >= ? ");
            params.add(beginTime);
        }
        if (endTime != null && !endTime.isEmpty()) {
            sql.append("AND login_time <= ? ");
            params.add(endTime + " 23:59:59");
        }
        
        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, params.toArray(), Integer.class);
        
        sql.append("ORDER BY login_time DESC LIMIT ? OFFSET ?");
        params.add(pageSize);
        params.add((pageNum - 1) * pageSize);
        
        List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql.toString(), params.toArray());
        
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(rows);
        dataInfo.setTotal(total != null ? total : 0);
        return dataInfo;
    }

    /**
     * 删除登录日志
     */
    @DeleteMapping("/logininfor/{infoIds}")
    public AjaxResult removeLogininfor(@PathVariable String infoIds) {
        String[] ids = infoIds.split(",");
        for (String id : ids) {
            jdbcTemplate.update("DELETE FROM sys_logininfor WHERE info_id = ?", Long.valueOf(id));
        }
        return AjaxResult.success("删除成功");
    }

    /**
     * 清空登录日志
     */
    @DeleteMapping("/logininfor/clean")
    public AjaxResult cleanLogininfor() {
        jdbcTemplate.update("TRUNCATE TABLE sys_logininfor");
        return AjaxResult.success("清空成功");
    }

    /**
     * 账号解锁
     */
    @GetMapping("/logininfor/unlock/{userName}")
    public AjaxResult unlock(@PathVariable String userName) {
        // 这里可以添加解锁逻辑，比如清除登录失败次数等
        return AjaxResult.success("解锁成功");
    }
}
