package controller

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

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/vo/result"
	"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{
	sysJobLogService:   service.NewSysJobLog,
	sysDictDataService: systemService.NewSysDictData,
}

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

// 调度任务日志列表
//
// GET /list
func (s *SysJobLogController) List(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询参数转换map
	querys := ctx.QueryMap(c)
	// 任务ID优先级更高
	if v, ok := querys["jobId"]; ok && v != nil {
		jobInfo := service.NewSysJob.SelectJobById(v.(string))
		querys["jobName"] = jobInfo.JobName
		querys["jobGroup"] = jobInfo.JobGroup
	}
	// 多语言值转key查询
	if v, ok := querys["jobName"]; ok && v != "" {
		querys["jobName"] = i18n.TFindKeyPrefix(language, "job", v.(string))
	}

	data := s.sysJobLogService.SelectJobLogPage(querys)
	rows := data["rows"].([]model.SysJobLog)

	// 闭包函数处理多语言
	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, result.Ok(data))
}

// 调度任务日志信息
//
// GET /:jobLogId
func (s *SysJobLogController) Info(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	jobLogId := c.Param("jobLogId")
	if jobLogId == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	data := s.sysJobLogService.SelectJobLogById(jobLogId)
	if data.JobLogID == jobLogId {
		c.JSON(200, result.OkData(data))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 调度任务日志删除
//
// DELETE /:jobLogIds
func (s *SysJobLogController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	jobLogIds := c.Param("jobLogIds")
	if jobLogIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 处理字符转id数组后去重
	ids := strings.Split(jobLogIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows := s.sysJobLogService.DeleteJobLogByIds(uniqueIDs)
	if rows > 0 {
		// 删除成功：%d
		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 *SysJobLogController) Clean(c *gin.Context) {
	err := s.sysJobLogService.CleanJobLog()
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, result.Ok(nil))
}

// 导出调度任务日志信息
//
// POST /export
func (s *SysJobLogController) Export(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	querys := ctx.BodyJSONMap(c)
	querys["pageNum"] = 1
	querys["pageSize"] = 10000
	data := s.sysJobLogService.SelectJobLogPage(querys)
	if parse.Number(data["total"]) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.SysJobLog)

	// rows := s.sysJobLogService.SelectJobLogList(model.SysJobLog{})
	if len(rows) <= 0 {
		// 导出数据记录为空
		c.JSON(200, result.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.SelectDictDataByType("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.DictValue {
				sysJobGroup = i18n.TKey(language, v.DictLabel)
				break
			}
		}
		// 状态
		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.JobLogID,
			"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, result.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}
