package controller

import (
	"fmt"
	"strings"
	"time"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/vo/result"
	"be.ems/src/modules/network_data/model"
	neDataService "be.ems/src/modules/network_data/service"
	neService "be.ems/src/modules/network_element/service"
	"github.com/gin-gonic/gin"
)

// 实例化控制层 SGWCController 结构体
var NewSGWC = &SGWCController{
	neInfoService:      neService.NewNeInfo,
	cdrEventService:    neDataService.NewCDREventSGWC,
	udmUserInfoService: neDataService.NewUDMUserInfo,
}

// 网元SGWC
//
// PATH /sgwc
type SGWCController struct {
	neInfoService      *neService.NeInfo           // 网元信息服务
	cdrEventService    *neDataService.CDREventSGWC // CDR会话事件服务
	udmUserInfoService *neDataService.UDMUserInfo  // UDM用户信息服务
}

// CDR会话列表
//
// GET /cdr/list
//
//	@Tags			network_data/sgwc
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type only SGWC"	Enums(SGWC)
//	@Param			neId		query		string	true	"NE ID"				default(001)
//	@Param			imsi		query		string	false	"imsi"
//	@Param			msisdn		query		string	false	"msisdn"
//	@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		CDR Session List
//	@Description	CDR Session List
//	@Router			/neData/sgwc/cdr/list [get]
func (s *SGWCController) CDRList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.CDREventSGWCQuery
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 查询网元信息 rmUID
	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

	// 查询数据
	rows, total := s.cdrEventService.SelectPage(querys)
	c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total}))
}

// CDR会话删除
//
// DELETE /cdr/:cdrIds
//
//	@Tags			network_data/sgwc
//	@Accept			json
//	@Produce		json
//	@Param			cdrIds	path		string	true	"list data id, multiple separated by a , sign"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		CDR Session Delete
//	@Description	CDR Session Delete
//	@Router			/neData/sgwc/cdr/{cdrIds} [delete]
func (s *SGWCController) 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))
}

// CDR会话列表导出
//
// POST /cdr/export
//
//	@Tags			network_data/sgwc
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		CDR Session List Export
//	@Description	CDR Session List Export
//	@Router			/neData/sgwc/cdr/export [post]
func (s *SGWCController) CDRExport(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var querys model.CDREventSGWCQuery
	if err := c.ShouldBindBodyWithJSON(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 限制导出数据集
	if querys.PageSize > 10000 {
		querys.PageSize = 10000
	}
	// 查询网元信息 rmUID
	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
	rows, total := s.cdrEventService.SelectPage(querys)
	if total == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

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

	c.FileAttachment(saveFilePath, fileName)
}
