package controller

import (
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/parse"
	traceService "be.ems/src/modules/trace/service"

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

// 实例化控制层 TraceDataController 结构体
var NewTraceData = &TraceDataController{
	traceDataService: traceService.NewTraceData,
}

// 跟踪任务数据
//
// PATH /data
type TraceDataController struct {
	traceDataService *traceService.TraceData // 跟踪_数据信息服务
}

// 跟踪任务数据列表
//
// GET /list
func (s *TraceDataController) List(c *gin.Context) {
	query := reqctx.QueryMap(c)
	rows, total := s.traceDataService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// 跟踪任务数据信息
//
// GET /:id
func (s *TraceDataController) Info(c *gin.Context) {
	id := parse.Number(c.Param("id"))
	if id <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}

	data := s.traceDataService.FindById(id)
	if data.ID == id {
		c.JSON(200, resp.OkData(data))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 跟踪任务数据删除
//
// DELETE /:id
func (s *TraceDataController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := c.Param("id")
	if id == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}

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

	rows, err := s.traceDataService.DeleteByIds(ids)
	if err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, resp.OkMsg(msg))
}
