package controller

import (
	"fmt"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/parse"
	neService "be.ems/src/modules/ne/service"
	"be.ems/src/modules/ne_data/model"
	neDataService "be.ems/src/modules/ne_data/service"

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

// 实例化控制层 KPIController 结构体
var NewKPI = &KPIController{
	neInfoService:    neService.NewNeInfo,
	kpiReportService: neDataService.NewKpiReport,
}

// 性能统计
//
// PATH /kpi
type KPIController struct {
	neInfoService    *neService.NeInfo        // 网元信息服务
	kpiReportService *neDataService.KpiReport // 指标统计服务
}

// 获取统计数据
//
// GET /data
//
//	@Tags			ne_data/kpi
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type"								Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(AMF)
//	@Param			neId		query		string	true	"NE ID"									default(001)
//	@Param			beginTime	query		number	true	"begin time (timestamped milliseconds)"	default(1729162507596)
//	@Param			endTime		query		number	true	"end time (timestamped milliseconds)"	default(1729164187611)
//	@Param			interval	query		number	true	"interval"								Enums(5,10,15,30,60,300,600,900,1800,3600) default(60)
//	@Success		200			{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Access to statistical data
//	@Description	Access to statistical data
//	@Router			/neData/kpi/data [get]
func (s KPIController) KPIData(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var querys model.KPIQuery
	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
	}

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

	// 查询数据
	kpiData := s.kpiReportService.FindData(querys)
	c.JSON(200, resp.OkData(kpiData))
}

// 获取统计标题
//
// GET /title
//
//	@Tags			ne_data/kpi
//	@Accept			json
//	@Produce		json
//	@Param			neType	query		string	true	"NE Type"	Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(AMF)
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Get Statistical Headings
//	@Description	Get Statistical Headings
//	@Router			/neData/kpi/title [get]
func (s KPIController) KPITitle(c *gin.Context) {
	neType := c.Query("neType")
	if neType == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neType is empty"))
		return
	}
	kpiTitles := s.kpiReportService.FindTitle(neType)
	c.JSON(200, resp.OkData(kpiTitles))
}

// 统计标题列表
//
// GET /title/list
func (s KPIController) ListTitle(c *gin.Context) {
	query := reqctx.QueryMap(c)
	rows, total := s.kpiReportService.TitleFindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}

// 统计标题新增
//
// POST /title
func (s KPIController) AddTitle(c *gin.Context) {
	var body model.KpiTitle
	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
	}

	// 校验指标是否存在
	kpicTitles := s.kpiReportService.TitleFind(model.KpiTitle{
		NeType: body.NeType,
		KpiId:  body.KpiId,
	})
	if len(kpicTitles) > 0 {
		c.JSON(200, resp.ErrMsg("indicator already exist"))
		return
	}

	insertId := s.kpiReportService.TitleInsert(body)
	if insertId > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 统计标题修改
//
// PUT /title
func (s KPIController) EditTitle(c *gin.Context) {
	var body model.KpiTitle
	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
	}

	rows := s.kpiReportService.TitleUpdate(body)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 统计标题删除
//
// DELETE /title?id=1,2,3
func (s KPIController) RemoveTitle(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := c.Query("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.kpiReportService.TitleDeleteByIds(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))
}
