package controller

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

	"ems.agt/src/framework/utils/ctx"
	"ems.agt/src/framework/utils/date"
	"ems.agt/src/framework/utils/file"
	"ems.agt/src/framework/utils/parse"
	"ems.agt/src/framework/vo/result"
	"ems.agt/src/modules/monitor/model"
	"ems.agt/src/modules/monitor/service"
	systemService "ems.agt/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)
	list := s.sysJobLogService.SelectJobLogPage(querys)
	c.JSON(200, result.Ok(list))
}

// 调度任务日志信息
//
// GET /:jobLogId
func (s *SysJobLogController) Info(c *gin.Context) {
	jobLogId := c.Param("jobLogId")
	if jobLogId == "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		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) {
	jobLogIds := c.Param("jobLogIds")
	if jobLogIds == "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		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 := fmt.Sprintf("Deleted successfully: %d", 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)

	// 导出文件名称
	fileName := fmt.Sprintf("jobLog_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "JobLogID",
		"B1": "JobName",
		"C1": "JobGroupName",
		"D1": "InvokeTarget",
		"E1": "TargetParams",
		"F1": "JobMsg",
		"G1": "Status",
		"H1": "Time",
	}
	// 读取任务组名字典数据
	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 = v.DictLabel
				break
			}
		}
		// 状态
		statusValue := "Fail"
		if row.Status == "1" {
			statusValue = "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)
}
