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

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

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

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

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

	rows := data["rows"].([]model.SysJobLog)
	// 闭包函数处理多语言
	language := ctx.AcceptLanguage(c)
	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) {
	// 查询结果，根据查询条件结果，单页最大值限制
	querys := ctx.BodyJSONMap(c)
	data := s.sysJobLogService.SelectJobLogPage(querys)
	if data["total"].(int64) == 0 {
		c.JSON(200, result.ErrMsg("Export data record is empty"))
		return
	}
	rows := data["rows"].([]model.SysJobLog)

	// 闭包函数处理多语言
	language := ctx.AcceptLanguage(c)
	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"),
		"G1": i18n.TKey(language, "job.export.jobLogStatus"),
		"H1": i18n.TKey(language, "job.export.jobLogTime"),
	}
	// 读取任务组名字典数据
	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,
			"G" + idx: statusValue,
			"H" + idx: date.ParseDateToStr(row.CreateTime, 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)
}
