package controller

import (
	"fmt"
	"strconv"
	"time"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/system/model"
	"be.ems/src/modules/system/service"

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

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

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

// 操作日志列表
//
// GET /list
//
//	@Tags			system/log/operate
//	@Accept			json
//	@Produce		json
//	@Param			title		query		string	false	"title"
//	@Param			pageNum		query		number	true	"pageNum"	default(1)
//	@Param			pageSize	query		number	true	"pageSize"	default(10)
//	@Success		200			{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		System Operation Log List
//	@Description	System Operation Log List
//	@Router			/system/log/operate/list [get]
func (s *SysLogOperateController) List(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	query := reqctx.QueryMap(c)
	// 多语言值转key查询
	if v, ok := query["title"]; ok && v != "" {
		query["title"] = i18n.TFindKeyPrefix(language, "log.operate.title", v)
	}
	// 分页检查
	pageNum := parse.Number(query["pageNum"])
	pageSize := parse.Number(query["pageSize"])
	if pageNum == 0 || pageSize == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: pageNum or pageSize not is empty"))
		return
	}

	dataScopeSQL := reqctx.LoginUserToDataScopeSQL(c, "sys_user", "sys_user")
	rows, total := s.sysLogOperateService.FindByPage(query, dataScopeSQL)

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

	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// Clean 操作日志清空
//
// DELETE /clean
func (s SysLogOperateController) Clean(c *gin.Context) {
	rows := s.sysLogOperateService.Clean()
	c.JSON(200, resp.OkData(rows))
}

// Export 导出操作日志
//
// GET /export
func (s SysLogOperateController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	query := reqctx.QueryMap(c)
	// 分页检查
	pageNum := parse.Number(query["pageNum"])
	pageSize := parse.Number(query["pageSize"])
	if pageNum == 0 || pageSize == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: pageNum or pageSize not is empty"))
		return
	}
	dataScopeSQL := reqctx.LoginUserToDataScopeSQL(c, "sys_user", "sys_user")
	rows, total := s.sysLogOperateService.FindByPage(query, dataScopeSQL)
	if total == 0 {
		// c.JSON(200, resp.CodeMsg(40016, "export data record as empty"))
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

	// 闭包函数处理多语言
	converI18n := func(language string, arr *[]model.SysLogOperate) {
		for i := range *arr {
			(*arr)[i].Title = i18n.TKey(language, (*arr)[i].Title)
			(*arr)[i].OperaLocation = i18n.TKey(language, (*arr)[i].OperaLocation)
		}
	}
	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.operName"),
		"E1": i18n.TKey(language, "log.operate.export.method"),
		"F1": i18n.TKey(language, "log.operate.export.ip"),
		"G1": i18n.TKey(language, "log.operate.export.status"),
		"H1": i18n.TKey(language, "log.operate.export.operTime"),
		"I1": i18n.TKey(language, "log.operate.export.costTime"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 业务类型
		businessType := ""
		switch row.BusinessType {
		case "0":
			// 业务操作类型-其它
			businessType = i18n.TKey(language, "dictData.operType.other")
		case "1":
			// 业务操作类型-新增
			businessType = i18n.TKey(language, "dictData.operType.add")
		case "2":
			// 业务操作类型-修改
			businessType = i18n.TKey(language, "dictData.operType.edit")
		case "3":
			// 业务操作类型-删除
			businessType = i18n.TKey(language, "dictData.operType.delete")
		case "4":
			// 业务操作类型-授权
			businessType = i18n.TKey(language, "dictData.operType.auth")
		case "5":
			// 业务操作类型-导出
			businessType = i18n.TKey(language, "dictData.operType.export")
		case "6":
			// 业务操作类型-导入
			businessType = i18n.TKey(language, "dictData.operType.import")
		case "7":
			// 业务操作类型-强退
			businessType = i18n.TKey(language, "dictData.operType.forced quit")
		case "8":
			// 业务操作类型-清空数据
			businessType = i18n.TKey(language, "dictData.operType.clear")
		}

		// 状态
		statusValue := i18n.TKey(language, "dictData.fail")
		if row.StatusFlag == "1" {
			statusValue = i18n.TKey(language, "dictData.success")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.ID,
			"B" + idx: row.Title,
			"C" + idx: businessType,
			"D" + idx: row.OperaBy,
			"E" + idx: row.OperaUrlMethod,
			"F" + idx: row.OperaIp,
			"G" + idx: statusValue,
			"H" + idx: date.ParseDateToStr(row.OperaTime, date.YYYY_MM_DDTHH_MM_SSZ),
			"I" + idx: row.CostTime,
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}
