package controller

import (
	"fmt"
	"time"

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

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

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

// 网元IMS
//
// PATH /ims
type IMSController struct {
	neInfoService    *neService.NeInfo        // 网元信息服务
	cdrEventService  *neDataService.CDREvent  // CDR会话事件服务
	kpiReportService *neDataService.KpiReport // 统计信息服务
}

// CDR会话列表
//
// GET /cdr/list
//
//	@Tags			ne_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type only IMS"	Enums(IMS)
//	@Param			neId		query		string	true	"NE ID"				default(001)
//	@Param			callerParty	query		string	false	"callerParty"
//	@Param			calledParty	query		string	false	"calledParty"
//	@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/ims/cdr/list [get]
func (s *IMSController) CDRList(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	query := reqctx.QueryMap(c)
	// 分页检查
	pageNum := parse.Number(query["pageNum"])
	pageSize := parse.Number(query["pageSize"])
	if pageNum == 0 || pageSize == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: pageNum or pageSize not is empty"))
		return
	}
	// 查询网元信息 rmUID
	neInfo := s.neInfoService.FindByNeTypeAndNeID(query["neType"], query["neId"])
	if neInfo.NeType == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	query["rmUID"] = neInfo.RmUID
	rows, total := s.cdrEventService.FindByPage(neInfo.NeType, query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// CDR会话删除
//
// DELETE /cdr/:id
//
//	@Tags			ne_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			id	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/ims/cdr/{id} [delete]
func (s *IMSController) CDRRemove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := c.Param("id")
	if id == "" {
		c.JSON(422, resp.CodeMsg(442002, "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.cdrEventService.DeleteByIds("IMS", 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))
}

// CDR会话列表导出
//
// GET /cdr/export
//
//	@Tags			ne_data/ims
//	@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/ims/cdr/export [get]
func (s *IMSController) CDRExport(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	query := reqctx.QueryMap(c)
	// 分页检查
	pageNum := parse.Number(query["pageNum"])
	pageSize := parse.Number(query["pageSize"])
	if pageNum == 0 || pageSize == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: pageNum or pageSize not is empty"))
		return
	}
	// 查询网元信息 rmUID
	neInfo := s.neInfoService.FindByNeTypeAndNeID(query["neType"], query["neId"])
	if neInfo.NeType == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	query["rmUID"] = neInfo.RmUID
	rows, total := s.cdrEventService.FindByPage(neInfo.NeType, query)
	if total == 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

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

	c.FileAttachment(saveFilePath, fileName)
}

// 在线会话用户数量
//
// GET /session/num
//
//	@Tags			ne_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Number of online session users
//	@Description	Number of online session users
//	@Router			/neData/ims/session/num [get]
func (s *IMSController) UeSessionNum(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Query("neId")
	if neId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId is empty"))
		return
	}

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

	// 网元直连
	num, err := neFetchlink.IMSUeSessionNum(neInfo)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	c.JSON(200, resp.OkData(num))
}

// 在线会话用户列表信息
//
// GET /session/list
//
//	@Tags			ne_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			imsi	query		string	false	"imsi"
//	@Param			msisdn	query		string	false	"msisdn"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Online session user list information
//	@Description	Online session user list information
//	@Router			/neData/ims/session/list [get]
func (s *IMSController) UeSessionList(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		NeId   string `form:"neId" binding:"required"`
		IMSI   string `form:"imsi"`
		MSISDN string `form:"msisdn"`
	}
	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
	}

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

	// 网元直连
	data, err := neFetchlink.IMSUeSessionList(neInfo, map[string]string{
		"imsi":   query.IMSI,
		"msisdn": query.MSISDN,
	})
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	c.JSON(200, resp.OkData(data))
}

// KPI 忙时统计
//
// GET /kpi/busy-hour
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			timestamp	query		int64	false	"timestamp"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Busy hour statistics
//	@Description	Busy hour statistics
//	@Router			/neData/ims/kpi/busy-hour [get]
func (s IMSController) KPIBusyHour(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		NeID      string `form:"neId" binding:"required"`
		Timestamp int64  `form:"timestamp" 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
	}
	if query.Timestamp < 1e12 || query.Timestamp > 1e13 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "timestamp format is ms"))
		return
	}

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

	data := s.kpiReportService.IMSBusyHour(neInfo.RmUID, query.Timestamp)
	c.JSON(200, resp.OkData(data))
}

// KPI 忙时统计 周
//
// GET /kpi/busy-week
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			timestamp	query		int64	false	"timestamp"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Busy week statistics
//	@Description	Busy week statistics
//	@Router			/neData/ims/kpi/busy-week [get]
func (s IMSController) KPIBusyWeek(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		NeID      string `form:"neId" binding:"required"`
		WeekStart int64  `form:"weekStart" binding:"required"` // 时间戳毫秒 年月日
		WeekEnd   int64  `form:"weekEnd" 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
	}
	if query.WeekStart < 1e12 || query.WeekStart > 1e13 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "weekStart format is ms"))
		return
	}
	if query.WeekEnd < 1e12 || query.WeekEnd > 1e13 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "weekEnd format is ms"))
		return
	}
	if query.WeekEnd < query.WeekStart || query.WeekEnd == query.WeekStart {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "weekEnd must be greater than weekStart and not equal to weekStart"))
		return
	}
	// 计算周差
	weekDiff := query.WeekEnd - query.WeekStart
	// 周差是否7天
	if weekDiff-7*24*60*60*1000 != -1000 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "weekEnd must be 7 days after weekStart"))
		return
	}

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

	data := s.kpiReportService.IMSBusyWeek(neInfo.RmUID, query.WeekStart, query.WeekEnd)
	c.JSON(200, resp.OkData(data))
}

// CDR MOS
//
// GET /cdr/mos-hour
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			timestamp	query		int64	false	"timestamp"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		MOS hour statistics
//	@Description	MOS hour statistics
//	@Router			/neData/ims/cdr/mos-hour [get]
func (s IMSController) CDRMOSHour(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		NeID      string `form:"neId" binding:"required"`
		Timestamp int64  `form:"timestamp" 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
	}
	if query.Timestamp < 1e12 || query.Timestamp > 1e13 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "timestamp format is ms"))
		return
	}

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

	data := s.cdrEventService.IMSCDRMOSHour(neInfo.RmUID, query.Timestamp)
	c.JSON(200, resp.OkData(data))
}

// CDR Call Connection Time
//
// GET /cdr/cct-hour
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			timestamp	query		int64	false	"timestamp"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		MOS hour statistics
//	@Description	MOS hour statistics
//	@Router			/neData/ims/cdr/cct-hour [get]
func (s IMSController) CDRCCTHour(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		NeID      string `form:"neId" binding:"required"`
		Timestamp int64  `form:"timestamp" 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
	}
	if query.Timestamp < 1e12 || query.Timestamp > 1e13 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "timestamp format is ms"))
		return
	}

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

	data := s.cdrEventService.IMSCDRCCTHour(neInfo.RmUID, query.Timestamp)
	c.JSON(200, resp.OkData(data))
}
