package com.pangu.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pangu.common.core.domain.AjaxResult;

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

    @Autowired
    private JdbcTemplate jdbcTemplate;

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

    @GetMapping("/operlog/list")
    public AjaxResult operlogList(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String operName,
            @RequestParam(required = false) Integer businessType,
            @RequestParam(required = false) Integer status,
            @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);
        }

        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class, params.toArray());

        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());

        return AjaxResult.success().put("rows", rows).put("total", total != null ? total : 0);
    }

    @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 AjaxResult logininforList(
            @RequestParam(required = false) String userName,
            @RequestParam(required = false) String ipaddr,
            @RequestParam(required = false) String status,
            @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);
        }

        String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") t";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class, params.toArray());

        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());

        return AjaxResult.success().put("rows", rows).put("total", total != null ? total : 0);
    }

    @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();
    }
}
