package controller

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

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/vo/result"
	"be.ems/src/modules/trace/model"
	traceService "be.ems/src/modules/trace/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 实例化控制层 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 := ctx.QueryMap(c)

	// 查询数据
	data := s.traceTaskService.SelectPage(query)
	c.JSON(200, result.Ok(data))
}

// 跟踪任务信息
//
// GET /:id
func (s *TraceTaskController) Info(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	id := c.Param("id")
	if id == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	data := s.traceTaskService.SelectById(id)
	if data.ID == id {
		c.JSON(200, result.OkData(data))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 跟踪任务新增
//
// POST /
func (s *TraceTaskController) Add(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body model.TraceTask
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.ID != "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

// 跟踪任务修改
//
// PUT /
func (s *TraceTaskController) Edit(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body model.TraceTask
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.ID == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 检查是否存在
	taskInfo := s.traceTaskService.SelectById(body.ID)
	if taskInfo.ID != body.ID {
		// 没有可访问任务信息数据！
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "task.noData")))
		return
	}

	body.UpdateBy = ctx.LoginUserToUserName(c)
	if err = s.traceTaskService.Update(body); err != nil {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, result.Ok(nil))
}

// 跟踪任务删除
//
// DELETE /:ids
func (s *TraceTaskController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	rowIds := c.Param("ids")
	if rowIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(rowIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows, err := s.traceTaskService.DeleteByIds(uniqueIDs)
	if err != nil {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, result.OkMsg(msg))
}

// 跟踪任务文件
//
// GET /filePull
func (s *TraceTaskController) FilePull(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys struct {
		TraceId string `form:"traceId" binding:"required"`
	}
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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