package controller

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"nms_nbi/src/framework/i18n"
	"nms_nbi/src/framework/utils/ctx"
	"nms_nbi/src/framework/utils/date"
	"nms_nbi/src/framework/utils/file"
	"nms_nbi/src/framework/utils/parse"
	"nms_nbi/src/framework/vo/result"
	"nms_nbi/src/modules/system/model"
	"nms_nbi/src/modules/system/service"

	"github.com/gin-gonic/gin"
)

// 实例化控制层 SysLogOperateController 结构体
var NewSysLogOperate = &SysLogOperateController{
	SysLogOperateService: service.NewSysLogOperateImpl,
}

// 操作日志记录信息
//
// PATH /system/log/operate
type SysLogOperateController struct {
	// 操作日志服务
	SysLogOperateService service.ISysLogOperate
}

// 操作日志列表
//
// GET /list
func (s *SysLogOperateController) List(c *gin.Context) {
	querys := ctx.QueryMap(c)
	data := s.SysLogOperateService.SelectSysLogOperatePage(querys)

	rows := data["rows"].([]model.SysLogOperate)
	// 闭包函数处理多语言
	language := ctx.AcceptLanguage(c)
	converI18n := func(language string, arr *[]model.SysLogOperate) {
		for i := range *arr {
			(*arr)[i].Title = i18n.TKey(language, (*arr)[i].Title)
			(*arr)[i].OperLocation = i18n.TKey(language, (*arr)[i].OperLocation)
		}
	}
	converI18n(language, &rows)

	c.JSON(200, result.Ok(data))
}

// 操作日志删除
//
// DELETE /:operIds
func (s *SysLogOperateController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	operIds := c.Param("operIds")
	if operIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 处理字符转id数组后去重
	ids := strings.Split(operIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows := s.SysLogOperateService.DeleteSysLogOperateByIds(uniqueIDs)
	if rows > 0 {
		msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
		c.JSON(200, result.OkMsg(msg))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 操作日志清空
//
// DELETE /clean
func (s *SysLogOperateController) Clean(c *gin.Context) {
	err := s.SysLogOperateService.CleanSysLogOperate()
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, result.Ok(nil))
}

// 导出操作日志
//
// POST /export
func (s *SysLogOperateController) Export(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	querys := ctx.BodyJSONMap(c)
	data := s.SysLogOperateService.SelectSysLogOperatePage(querys)
	if data["total"].(int64) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.SysLogOperate)

	// 闭包函数处理多语言
	converI18n := func(language string, arr *[]model.SysLogOperate) {
		for i := range *arr {
			(*arr)[i].Title = i18n.TKey(language, (*arr)[i].Title)
			(*arr)[i].OperLocation = i18n.TKey(language, (*arr)[i].OperLocation)
		}
	}
	converI18n(language, &rows)

	// 导出文件名称
	fileName := fmt.Sprintf("sys_log_operate_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "log.operate.export.id"),
		"B1": i18n.TKey(language, "log.operate.export.title"),
		"C1": i18n.TKey(language, "log.operate.export.businessType"),
		"D1": i18n.TKey(language, "log.operate.export.method"),
		"E1": i18n.TKey(language, "log.operate.export.requestMethod"),
		"F1": i18n.TKey(language, "log.operate.export.operatorType"),
		"G1": i18n.TKey(language, "log.operate.export.operName"),
		"H1": i18n.TKey(language, "log.operate.export.deptName"),
		"I1": i18n.TKey(language, "log.operate.export.url"),
		"J1": i18n.TKey(language, "log.operate.export.ip"),
		"K1": i18n.TKey(language, "log.operate.export.location"),
		"L1": i18n.TKey(language, "log.operate.export.param"),
		"M1": i18n.TKey(language, "log.operate.export.msg"),
		"N1": i18n.TKey(language, "log.operate.export.status"),
		"O1": i18n.TKey(language, "log.operate.export.costTime"),
		"P1": i18n.TKey(language, "log.operate.export.operTime"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 业务类型
		businessType := ""
		// 操作类别
		operatorType := ""
		// 状态
		statusValue := i18n.TKey(language, "dictData.fail")
		if row.Status == "1" {
			statusValue = i18n.TKey(language, "dictData.success")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.OperID,
			"B" + idx: row.Title,
			"C" + idx: businessType,
			"D" + idx: row.Method,
			"E" + idx: row.RequestMethod,
			"F" + idx: operatorType,
			"G" + idx: row.OperName,
			"H" + idx: row.DeptName,
			"I" + idx: row.OperURL,
			"J" + idx: row.OperIP,
			"K" + idx: row.OperLocation,
			"L" + idx: row.OperParam,
			"M" + idx: row.OperMsg,
			"N" + idx: statusValue,
			"O" + idx: row.CostTime,
			"P" + idx: date.ParseDateToStr(row.OperTime, date.YYYY_MM_DD_HH_MM_SS),
		})
	}

	// 导出数据表格
	saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "")
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}
