package controller

import (
	"fmt"
	"path/filepath"
	"runtime"

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

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

// 实例化控制层 TraceTaskController 结构体
var NewTraceTask = &TraceTaskController{
	traceTaskService: traceService.NewTraceTask,
}

// 跟踪任务
//
// PATH /task
type TraceTaskController struct {
	// 跟踪_任务信息服务
	traceTaskService *traceService.TraceTask
}

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

// 跟踪任务信息
//
// GET /:id
func (s *TraceTaskController) 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.traceTaskService.FindById(id)
	if data.ID == id {
		c.JSON(200, resp.OkData(data))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 跟踪任务新增
//
// POST /
func (s *TraceTaskController) Add(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.TraceTask
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.ID > 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id not is empty"))
		return
	}

	body.CreateBy = reqctx.LoginUserToUserName(c)
	if err := s.traceTaskService.Insert(body); err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, resp.Ok(nil))
}

// 跟踪任务删除
//
// DELETE /:id
func (s *TraceTaskController) 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.traceTaskService.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))
}

// 跟踪任务文件
//
// GET /filePull
func (s *TraceTaskController) FilePull(c *gin.Context) {
	var querys struct {
		TraceId string `form:"traceId" binding:"required"`
	}
	if err := c.ShouldBindQuery(&querys); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	fileName := fmt.Sprintf("task_%s.pcap", querys.TraceId)
	localFilePath := filepath.Join("/usr/local/omc/trace", fileName)
	if runtime.GOOS == "windows" {
		localFilePath = fmt.Sprintf("C:%s", localFilePath)
	}
	c.FileAttachment(localFilePath, fileName)
}
