package controller

import (
	"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/network_data/model"
	neDataService "be.ems/src/modules/network_data/service"
	neService "be.ems/src/modules/network_element/service"

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

// 实例化控制层 AlarmController 结构体
var NewAlarmController = &AlarmController{
	neInfoService: neService.NewNeInfoImpl,
	alarmService:  neDataService.NewAlarmImpl,
}

// 告警数据
//
// PATH /alarm
type AlarmController struct {
	// 网元信息服务
	neInfoService neService.INeInfo
	// 告警信息服务
	alarmService neDataService.IAlarm
}

// 告警列表
//
// GET /list
func (s *AlarmController) List(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.AlarmQuery
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
	if neInfo.NeId != querys.NeID || neInfo.IP == "" {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	querys.RmUID = neInfo.RmUID

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

// 告警删除
//
// DELETE /:alarmIds
func (s *AlarmController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	alarmIds := c.Param("alarmIds")
	if alarmIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(alarmIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows, err := s.alarmService.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))
}
