package controller

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"

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

// 实例化控制层 NBStateController 结构体
var NewNBState = &NBStateController{
	neInfoService:  neService.NewNeInfo,
	nbStateService: neDataService.NewNBState,
}

// 基站状态历史记录 AMF/MME
//
// PATH /nb-state
type NBStateController struct {
	neInfoService  *neService.NeInfo      // 网元信息服务
	nbStateService *neDataService.NBState // 基站状态服务
}

// 历史记录列表
//
// GET /list
//
//	@Tags			ne_data/amf,ne_data/mme
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type only AMF/MME"					Enums(AMF,MME)	default(AMF)
//	@Param			neId		query		string	true	"NE ID"									default(001)
//	@Param			pageNum		query		number	true	"pageNum"								default(1)
//	@Param			pageSize	query		number	true	"pageSize"								default(10)
//	@Param			startTime	query		number	false	"Start time (timestamped milliseconds)"	default(1729162507596)
//	@Param			endTime		query		number	false	"End time (timestamped milliseconds)"	default(1729164187611)
//	@Param			sortField	query		string	false	"Sort fields, fill in result fields"	Enums(id,create_time)	default(id)
//	@Param			sortOrder	query		string	false	"Sort by ascending or descending order"	Enums(asc,desc)			default(asc)
//	@Success		200			{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Base Station Status List
//	@Description	Base Station Status List
//	@Router			/nb-state/list [get]
func (s NBStateController) List(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query model.NBStateQuery
	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
	}

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

	// 查询数据
	rows, total := s.nbStateService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// 历史记录列表导出
//
// GET /export
//
//	@Tags			ne_data/amf,ne_data/mme
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Base Station Status List Export
//	@Description	Base Station Status List Export
//	@Router			/nb-state/export [get]
func (s NBStateController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var querys model.NBStateQuery
	if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	// 限制导出数据集
	if querys.PageSize > 10000 {
		querys.PageSize = 10000
	}
	// 查询网元信息 rmUID
	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
	rows, total := s.nbStateService.FindByPage(querys)
	if total == 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

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

	c.FileAttachment(saveFilePath, fileName)
}
