package controller

import (
	"fmt"
	"time"

	"be.ems/src/framework/constants"
	"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"
)

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

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

// 告警列表
//
// GET /list
//
//	@Tags			ne_data/alarm
//	@Accept			json
//	@Produce		json
//	@Param			neType			query		string	false	"NE Type"	Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
//	@Param			neId			query		string	false	"NE ID The actual record is the network element RmUid"
//	@Param			neName			query		string	false	"NE Name"
//	@Param			pvFlag			query		string	false	"PV Flag"	Enums(PNF,VNF)
//	@Param			alarmCode		query		string	false	"alarm status code"
//	@Param			alarmType		query		string	false	"Alarm type Communication alarms=1, Equipment alarms=2, Processing faults=3, Environmental alarms=4, Quality of service alarms=5"	Enums(1,2,3,4,5)
//	@Param			alarmStatus		query		string	false	"Alarm status Clear Active"																									Enums(0,1)
//	@Param			origSeverity	query		string	false	"Alarm Type 1: Critical, 2: Major, 3: Minor, 4: Warning"																			Enums(1,2,3,4)
//	@Param			sortField		query		string	false	"Sort fields, fill in result fields"																								default(event_time)
//	@Param			sortOrder		query		string	false	"Sort by ascending or descending order, asc desc"																					default(asc)
//	@Param			pageNum			query		number	true	"pageNum"																															default(1)
//	@Param			pageSize		query		number	true	"pageSize"																															default(10)
//	@Success		200				{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Alarm List
//	@Description	Alarm List
//	@Router			/neData/alarm/list [get]
func (s AlarmController) List(c *gin.Context) {
	var query model.AlarmQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	// 查询数据
	rows, total := s.alarmService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// 告警删除
//
// DELETE /:id
func (s AlarmController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := c.Param("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.alarmService.DeleteByIds(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))
}

// 告警清除
//
// PUT /clear
func (s AlarmController) Clear(c *gin.Context) {
	var body struct {
		Ids []int64 `json:"ids" binding:"required"`
	}
	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
	}

	clearUser := reqctx.LoginUserToUserName(c)
	rows, err := s.alarmService.ClearByIds(body.Ids, clearUser, constants.ALARM_CLEAR_TYPE_MANUAL_CLEAR)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, resp.OkData(rows))
}

// 告警确认
//
// PUT /ack
func (s AlarmController) Ack(c *gin.Context) {
	var body struct {
		Ids      []int64 `json:"ids" binding:"required"`
		AckState bool    `json:"ackState" binding:"omitempty"`
	}
	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
	}

	ackUser := reqctx.LoginUserToUserName(c)
	rows, err := s.alarmService.AckByIds(body.Ids, ackUser, constants.ALARM_ACK_STATE_ACK)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, resp.OkData(rows))
}

// 告警级别数量
//
// GET /count/severity
func (s AlarmController) CountSeverity(c *gin.Context) {
	var query struct {
		AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"required,oneof=Clear Active"` // 告警状态
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	data := s.alarmService.CountSeverity(query.AlarmStatus)
	c.JSON(200, resp.OkData(data))
}

// 告警类别数量
//
// GET /count/type
func (s AlarmController) CountType(c *gin.Context) {
	var query struct {
		AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"required,oneof=Clear Active"` // 告警状态
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	data := s.alarmService.CountType(query.AlarmStatus)
	c.JSON(200, resp.OkData(data))
}

// 告警状态前几排名
//
// GET /count/ne
func (s AlarmController) CountNe(c *gin.Context) {
	var query struct {
		AlarmStatus string `json:"alarmStatus" form:"alarmStatus" binding:"required,oneof=Clear Active"` // 告警状态
		Top         int    `json:"top" form:"top" binding:"required"`                                    // 前几
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	data := s.alarmService.CountNe(query.AlarmStatus, query.Top)
	c.JSON(200, resp.OkData(data))
}

// 告警列表导出
//
// GET /export
//
//	@Tags			ne_data/alarm
//	@Accept			json
//	@Produce		json
//	@Param			neType			query		string	false	"NE Type"	Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
//	@Param			neId			query		string	false	"NE ID The actual record is the network element RmUid"
//	@Param			neName			query		string	false	"NE Name"
//	@Param			pvFlag			query		string	false	"PV Flag"	Enums(PNF,VNF)
//	@Param			alarmCode		query		string	false	"alarm status code"
//	@Param			alarmType		query		string	false	"Alarm type Communication alarms=1, Equipment alarms=2, Processing faults=3, Environmental alarms=4, Quality of service alarms=5"	Enums(1,2,3,4,5)
//	@Param			alarmStatus		query		string	false	"Alarm status 0:clear, 1:active"																									Enums(0,1)
//	@Param			origSeverity	query		string	false	"Alarm Type 1: Critical, 2: Major, 3: Minor, 4: Warning"																			Enums(1,2,3,4)
//	@Param			sortField		query		string	false	"Sort fields, fill in result fields"																								default(event_time)
//	@Param			sortOrder		query		string	false	"Sort by ascending or descending order, asc desc"																					default(asc)
//	@Param			pageNum			query		number	true	"pageNum"																															default(1)
//	@Param			pageSize		query		number	true	"pageSize"																															default(10)
//	@Success		200				{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Alarm List Export
//	@Description	Alarm List Export
//	@Router			/neData/alarm/export [get]
func (s AlarmController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var query model.AlarmQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	// 限制导出数据集
	if query.PageSize > 10000 {
		query.PageSize = 10000
	}
	// 查询数据
	rows, total := s.alarmService.FindByPage(query)
	if total == 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

	// 导出文件名称
	fileName := fmt.Sprintf("alarm_export_%d_%s_%d.xlsx", len(rows), query.AlarmStatus, time.Now().UnixMilli())
	// 导出数据表格
	saveFilePath, err := s.alarmService.ExportXlsx(rows, fileName, language, query.AlarmStatus)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}
