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/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"
	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"
)

// 实例化控制层 AMFController 结构体
var NewAMF = &AMFController{
	neInfoService:  neService.NewNeInfo,
	ueEventService: neDataService.NewUEEventAMF,
}

// 网元AMF
//
// PATH /amf
type AMFController struct {
	neInfoService  *neService.NeInfo         // 网元信息服务
	ueEventService *neDataService.UEEventAMF // UE会话事件服务
}

// UE会话列表
//
// GET /ue/list
func (s *AMFController) UEList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.UEEventAMFQuery
	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

	// 查询数据
	data := s.ueEventService.SelectPage(querys)
	c.JSON(200, result.Ok(data))
}

// UE会话删除
//
// DELETE /ue/:ueIds
func (s *AMFController) 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
func (s *AMFController) UEExport(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var querys model.UEEventAMFQuery
	if err := c.ShouldBindBodyWith(&querys, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 限制导出数据集
	if querys.PageSize > 10000 {
		querys.PageSize = 10000
	}
	data := s.ueEventService.SelectPage(querys)
	if parse.Number(data["total"]) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.UEEventAMF)

	// 导出文件名称
	fileName := fmt.Sprintf("amf_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",
	}
	// 读取字典数据 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 := ""
		for _, v := range dictUEEventType {
			if row.EventType == v.DictValue {
				eventType = i18n.TKey(language, v.DictLabel)
				break
			}
		}
		// 取结果
		eventResult := ""
		// 取时间
		timeStr := ""
		if row.EventType == "auth-result" {
			if v, ok := eventJSON["authTime"]; ok && v != nil {
				timeStr = v.(string)
			}
			if v, ok := eventJSON["authCode"]; ok && v != nil {
				eventResult = v.(string)
				for _, v := range dictUEAauthCode {
					if eventResult == v.DictValue {
						eventResult = i18n.TKey(language, v.DictLabel)
						break
					}
				}
			}
		}
		if row.EventType == "detach" {
			if v, ok := eventJSON["detachTime"]; ok && v != nil {
				timeStr = v.(string)
			}
			eventResult = "Success"
		}
		if row.EventType == "cm-state" {
			if v, ok := eventJSON["changeTime"]; ok && v != nil {
				timeStr = v.(string)
			}
			if v, ok := eventJSON["status"]; ok && v != nil {
				eventResult = fmt.Sprint(v)
				for _, v := range dictUEEventCmState {
					if eventResult == v.DictValue {
						eventResult = i18n.TKey(language, v.DictLabel)
						break
					}
				}
			}
		}

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

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

	c.FileAttachment(saveFilePath, fileName)
}
