package controller

import (
	"fmt"
	"strconv"
	"strings"

	"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"
)

// 实例化控制层 KPICController 结构体
var NewKPIC = &KPICController{
	neInfoService:     neService.NewNeInfo,
	kpicReportService: neDataService.NewKpiCReport,
}

// 性能统计
//
// PATH /kpic
type KPICController struct {
	neInfoService     *neService.NeInfo         // 网元信息服务
	kpicReportService *neDataService.KpiCReport // 指标统计服务
}

// 获取统计数据
//
// 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/kpic/data [get]
func (s KPICController) KPIData(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var querys model.KPICQuery
	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.kpicReportService.FindData(querys)
	c.JSON(200, resp.OkData(kpiData))
}

// 自定义标题列表
//
// GET /title/list
func (s KPICController) ListTitle(c *gin.Context) {
	query := reqctx.QueryMap(c)
	if v, ok := query["status"]; ok && v == "" {
		query["status"] = "1"
	}
	rows, total := s.kpicReportService.TitleFindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}

// 自定义标题新增
//
// POST /title
func (s KPICController) AddTitle(c *gin.Context) {
	var body model.KpiCTitle
	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.kpicReportService.TitleFind(model.KpiCTitle{
		NeType: body.NeType,
		KpiId:  body.KpiId,
	})
	if len(kpicTitles) > 0 {
		for _, v := range kpicTitles {
			if v.Status == "2" {
				c.JSON(200, resp.ErrMsg("custom indicator already exist"))
				return
			}
		}
	}

	// 生成自定义指标ID
	if body.KpiId == "" {
		body.KpiId = fmt.Sprintf("%s.C.01", strings.ToUpper(body.NeType))
	} else {
		// 网元类型最后指标ID
		lastKpiId := s.kpicReportService.TitleLastKPIId(body.NeType)
		if lastKpiId != "" {
			// title like AMF.C.01 截断 .C. 并获取后面的数字部分
			parts := strings.Split(lastKpiId, ".C.")
			if len(parts) == 2 {
				numStr := parts[1]
				if num, err := strconv.Atoi(numStr); err == nil {
					num++ // 数字加 1
					// 转换为前面补零的 2 位字符串
					body.KpiId = fmt.Sprintf("%s.C.%02d", strings.ToUpper(body.NeType), num)
				}
			}
		}
	}

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

// 自定义标题修改
//
// PUT /title
func (s KPICController) EditTitle(c *gin.Context) {
	var body model.KpiCTitle
	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.kpicReportService.TitleUpdate(body)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 自定义标题删除
//
// DELETE /title
func (s KPICController) 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.kpicReportService.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))
}
