package controller

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	"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"
	neFetchlink "be.ems/src/modules/network_element/fetch_link"
	neService "be.ems/src/modules/network_element/service"
	sysService "be.ems/src/modules/system/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 实例化控制层 MMEController 结构体
var NewMME = &MMEController{
	neInfoService:  neService.NewNeInfo,
	ueEventService: neDataService.NewUEEventMME,
}

// 网元MME
//
// PATH /mme
type MMEController struct {
	neInfoService  *neService.NeInfo         // 网元信息服务
	ueEventService *neDataService.UEEventMME // UE会话事件服务
}

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

	// 查询网元获取IP
	// 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

	// for multi-tenancy
	querys.UserName = ctx.LoginUserToUserName(c)
	// 查询数据
	data := s.ueEventService.SelectPageMT(querys)
	c.JSON(200, result.Ok(data))
}

// UE会话删除
//
// DELETE /ue/:ueIds
//
//	@Tags			network_data/mme
//	@Accept			json
//	@Produce		json
//	@Param			ueIds	path		string	true	"list data id, multiple separated by a , sign"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UE Session Deletion
//	@Description	UE Session Deletion
//	@Router			/neData/mme/ue/{ueIds} [delete]
func (s *MMEController) UERemove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	ueIds := c.Param("ueIds")
	if ueIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(ueIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows, err := s.ueEventService.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))
}

// UE会话列表导出
//
// POST /ue/export
//
//	@Tags			network_data/mme
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UE Session List Export
//	@Description	UE Session List Export
//	@Router			/neData/mme/ue/export [post]
func (s *MMEController) UEExport(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var querys model.UEEventMMEQuery
	if err := c.ShouldBindBodyWith(&querys, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// for multi-tenancy
	querys.UserName = ctx.LoginUserToUserName(c)

	// 限制导出数据集
	if querys.PageSize > 10000 {
		querys.PageSize = 10000
	}
	data := s.ueEventService.SelectPageMT(querys)
	if parse.Number(data["total"]) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.UEEventMME)

	// 导出文件名称
	fileName := fmt.Sprintf("mme_ue_event_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ID",
		"B1": "IMSI",
		"C1": "Event Type",
		"D1": "Result",
		"E1": "Time",
		"F1": "Tenant Name",
	}
	// 读取字典数据 UE 事件类型
	dictUEEventType := sysService.NewSysDictData.SelectDictDataByType("ue_event_type")
	// 读取字典数据 UE 事件认证代码类型
	dictUEAauthCode := sysService.NewSysDictData.SelectDictDataByType("ue_auth_code")
	// 读取字典数据 UE 事件CM状态
	dictUEEventCmState := sysService.NewSysDictData.SelectDictDataByType("ue_event_cm_state")
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 解析 JSON 字符串为 map
		var eventJSON map[string]interface{}
		err := json.Unmarshal([]byte(row.EventJSONStr), &eventJSON)
		if err != nil {
			logger.Warnf("UEExport Error parsing JSON: %s", err.Error())
			continue
		}

		// 取IMSI
		imsi := ""
		if v, ok := eventJSON["imsi"]; ok && v != nil {
			imsi = v.(string)
		}
		// 取类型
		eventType := row.EventType
		for _, v := range dictUEEventType {
			if row.EventType == v.DictValue {
				eventType = i18n.TKey(language, v.DictLabel)
				break
			}
		}
		// 取结果
		eventResult := ""
		if v, ok := eventJSON["result"]; ok && v != nil {
			eventResult = v.(string)
			if row.EventType == "auth-result" {
				for _, v := range dictUEAauthCode {
					if eventResult == v.DictValue {
						eventResult = i18n.TKey(language, v.DictLabel)
						break
					}
				}
			}
			if row.EventType == "cm-state" {
				for _, v := range dictUEEventCmState {
					if eventResult == v.DictValue {
						eventResult = i18n.TKey(language, v.DictLabel)
						break
					}
				}
			}
		}
		// 取时间
		timeStr := ""
		if v, ok := eventJSON["timestamp"]; ok && v != nil {
			rowTime := parse.Number(v)
			timeStr = date.ParseDateToStr(rowTime, date.YYYY_MM_DD_HH_MM_SS_GMT_TZ)
		}
		// for multi-tenant, get tenant name
		tenantName := row.TenantName

		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.ID,
			"B" + idx: imsi,
			"C" + idx: eventType,
			"D" + idx: eventResult,
			"E" + idx: timeStr,
			"F" + idx: tenantName,
		})
	}

	// 导出数据表格
	saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "")
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}

// 接入基站信息列表
//
// GET /nb/list
//
//	@Tags			network_data/mme
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			id		query		string	false	"Base Station ID"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Access Base Station Information List
//	@Description	Access Base Station Information List
//	@Router			/neData/mme/nb/list [get]
func (s *MMEController) NbInfoList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var query struct {
		NeId string `form:"neId" binding:"required"`
		NbId string `form:"nbId"`
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	// 网元直连
	data, err := neFetchlink.MMENbInfoList(neInfo, map[string]string{
		"nbId": query.NbId,
	})
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

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

// 接入基站状态信息列表
//
// GET /nb/list-cfg
//
//	@Tags			network_data/mme
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Access to the base station status information list
//	@Description	Access to the base station status information list
//	@Router			/neData/mme/nb/list-cfg [get]
func (s *MMEController) NbStateList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var query struct {
		NeId string `form:"neId" binding:"required"`
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

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

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