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/monitor/model"
	"be.ems/src/modules/monitor/service"
	systemService "be.ems/src/modules/system/service"

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

// 实例化控制层 SysJobLogController 结构体
var NewSysJobLog = &SysJobLogController{
	sysJobService:      service.NewSysJob,
	sysJobLogService:   service.NewSysJobLog,
	sysDictDataService: systemService.NewSysDictData,
}

// 调度任务日志信息
//
// PATH /monitor/job/log
type SysJobLogController struct {
	sysJobService      *service.SysJob            // 调度任务服务
	sysJobLogService   *service.SysJobLog         // 调度任务日志服务
	sysDictDataService *systemService.SysDictData // 字典数据服务
}

// 调度任务日志列表
//
// GET /list
func (s *SysJobLogController) List(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询参数转换map
	query := reqctx.QueryMap(c)
	// 任务ID优先级更高
	if jobIdStr := c.Query("jobId"); jobIdStr != "" {
		if jobId := parse.Number(jobIdStr); jobId > 0 {
			job := s.sysJobService.FindById(jobId)
			query["jobName"] = job.JobName
			query["jobGroup"] = job.JobGroup
		}
	}
	// 多语言值转key查询
	if v, ok := query["jobName"]; ok && v != "" {
		query["jobName"] = i18n.TFindKeyPrefix(language, "job", v)
	}

	rows, total := s.sysJobLogService.FindByPage(query)

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

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

// 调度任务日志信息
//
// GET /:logId
func (s *SysJobLogController) Info(c *gin.Context) {
	logId := parse.Number(c.Param("logId"))
	if logId <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: logId is empty"))
		return
	}

	jobLogInfo := s.sysJobLogService.FindById(logId)
	if jobLogInfo.LogId == logId {
		c.JSON(200, resp.OkData(jobLogInfo))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 调度任务日志删除
//
// DELETE /:logId
func (s *SysJobLogController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	logId := c.Param("logId")
	if logId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: logId is empty"))
		return
	}

	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicatesToArray(logId, ",")
	// 转换成int64数组类型
	ids := make([]int64, 0)
	for _, v := range uniqueIDs {
		ids = append(ids, parse.Number(v))
	}

	rows := s.sysJobLogService.DeleteByIds(ids)
	if rows > 0 {
		// 删除成功：%d
		msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
		c.JSON(200, resp.OkMsg(msg))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 调度任务日志清空
//
// DELETE /clean
func (s *SysJobLogController) Clean(c *gin.Context) {
	rows := s.sysJobLogService.Clean()
	c.JSON(200, resp.OkData(rows))
}

// Export 导出调度任务日志信息
//
// GET /export
func (s *SysJobLogController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	query := reqctx.QueryMap(c)
	if jobIdStr := c.Query("jobId"); jobIdStr != "" {
		if jobId := parse.Number(jobIdStr); jobId > 0 {
			job := s.sysJobService.FindById(jobId)
			query["jobName"] = job.JobName
			query["jobGroup"] = job.JobGroup
		}
	}
	rows, total := s.sysJobLogService.FindByPage(query)
	if total == 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

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

	// 导出文件名称
	fileName := fmt.Sprintf("jobLog_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "job.export.jobLogID"),
		"B1": i18n.TKey(language, "job.export.jobName"),
		"C1": i18n.TKey(language, "job.export.jobGroupName"),
		"D1": i18n.TKey(language, "job.export.invokeTarget"),
		// "E1": i18n.TKey(language, "job.export.targetParams"),
		// "F1": i18n.TKey(language, "job.export.jobID"),
		"E1": i18n.TKey(language, "job.export.jobLogStatus"),
		"F1": i18n.TKey(language, "job.export.jobLogTime"),
		"G1": i18n.TKey(language, "log.operate.export.costTime"),
	}
	// 读取任务组名字典数据
	dictSysJobGroup := s.sysDictDataService.FindByType("sys_job_group")
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 任务组名
		sysJobGroup := ""
		for _, v := range dictSysJobGroup {
			if row.JobGroup == v.DataValue {
				sysJobGroup = i18n.TKey(language, v.DataLabel)
				break
			}
		}
		// 状态
		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.LogId,
			"B" + idx: row.JobName,
			"C" + idx: sysJobGroup,
			"D" + idx: row.InvokeTarget,
			// "E" + idx: row.TargetParams,
			// "F" + idx: row.JobMsg,
			"E" + idx: statusValue,
			"F" + idx: date.ParseDateToStr(row.CreateTime, date.YYYY_MM_DD_HH_MM_SS),
			"G" + 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)
}
