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"
	neService "be.ems/src/modules/ne/service"
	neDataService "be.ems/src/modules/ne_data/service"

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

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

// 网元SMSC
//
// PATH /smsc
type SMSCController struct {
	neInfoService   *neService.NeInfo       // 网元信息服务
	cdrEventService *neDataService.CDREvent // CDR会话事件服务
}

// CDR会话列表
//
// GET /cdr/list
//
//	@Tags			ne_data/smsc
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type only SMSC"	Enums(SMSC)
//	@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/smsc/cdr/list [get]
func (s *SMSCController) 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/smsc
//	@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/smsc/cdr/{id} [delete]
func (s *SMSCController) CDRRemove(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.cdrEventService.DeleteByIds("SMSC", 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/smsc
//	@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/smsc/cdr/export [get]
func (s *SMSCController) 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("smsc_cdr_event_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 导出数据表格
	saveFilePath, err := s.cdrEventService.ExportSMSC(rows, fileName, language)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}
