package controller

import (
	"nms_nbi/src/framework/i18n"
	"nms_nbi/src/framework/utils/ctx"
	"nms_nbi/src/framework/vo/result"
	chartService "nms_nbi/src/modules/chart/service"

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

// 实例化控制层 ChartGraphController 结构体
var NewChartGraph = &ChartGraphController{
	chartGraphService: chartService.NewChartGraphImpl,
}

// G6关系图
//
// PATH /graph
type ChartGraphController struct {
	// G6关系图数据表服务
	chartGraphService chartService.IChartGraph
}

// 获取关系图组名
//
// GET /groups
func (s *ChartGraphController) GroupNames(c *gin.Context) {
	data := s.chartGraphService.SelectGroup()
	c.JSON(200, result.OkData(data))
}

// 获取关系图数据
//
// GET /
func (s *ChartGraphController) Load(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys struct {
		Group string `form:"group" binding:"required"`
		Type  string `form:"type" binding:"omitempty,oneof=node edge combo"`
	}
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	data := s.chartGraphService.LoadData(querys.Group, querys.Type)
	c.JSON(200, result.OkData(data))
}

// 保存关系图数据
//
// POST /
func (s *ChartGraphController) Save(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		Group string `json:"group" binding:"required"`
		Data  struct {
			Nodes  []map[string]any `json:"nodes" binding:"required"`
			Edges  []map[string]any `json:"edges" binding:"required"`
			Combos []map[string]any `json:"combos" binding:"required"`
		} `json:"data" binding:"required"`
	}
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	data := map[string]any{
		"nodes":  body.Data.Nodes,
		"edges":  body.Data.Edges,
		"combos": body.Data.Combos,
	}
	saveNum := s.chartGraphService.SaveData(body.Group, data)
	if saveNum > 0 {
		c.JSON(200, result.Ok(nil))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 删除关系图数据
//
// DELETE /:group
func (s *ChartGraphController) Delete(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	group := c.Param("group")
	if group == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	deleteNum := s.chartGraphService.DeleteGroup(group)
	if deleteNum > 0 {
		c.JSON(200, result.Ok(nil))
		return
	}
	c.JSON(200, result.Err(nil))
}
