package controller

import (
	"strings"

	"nms_nbi/src/framework/i18n"
	"nms_nbi/src/framework/utils/ctx"
	"nms_nbi/src/framework/utils/parse"
	"nms_nbi/src/framework/vo/result"
	"nms_nbi/src/modules/network_data/model"
	neDataService "nms_nbi/src/modules/network_data/service"
	neService "nms_nbi/src/modules/network_element/service"

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

// 实例化控制层 IMSController 结构体
var NewIMSController = &IMSController{
	neInfoService:   neService.NewNeInfoImpl,
	cdrEventService: neDataService.NewCDREventImpl,
}

// 网元IMS
//
// PATH /ims
type IMSController struct {
	// 网元信息服务
	neInfoService neService.INeInfo
	// CDR会话事件服务
	cdrEventService neDataService.ICDREvent
}

// CDR会话列表
//
// GET /cdr/list
func (s *IMSController) CDRList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.CDREventQuery
	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.cdrEventService.SelectPage(querys)
	c.JSON(200, result.Ok(data))
}

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