package service

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

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/network_data/model"
	"be.ems/src/modules/network_data/repository"
	sysService "be.ems/src/modules/system/service"
)

// 实例化数据层 UEEventMME 结构体
var NewUEEventMME = &UEEventMME{
	ueEventRepository: repository.NewUEEventMME,
}

// UEEventMME UE会话事件MME 服务层处理
type UEEventMME struct {
	ueEventRepository *repository.UEEventMME // UE会话事件数据信息
}

// SelectPage 根据条件分页查询
func (r *UEEventMME) SelectPage(querys model.UEEventMMEQuery) ([]model.UEEventMME, int64) {
	return r.ueEventRepository.SelectByPage(querys)
}

// DeleteByIds 批量删除信息
func (r *UEEventMME) DeleteByIds(ueIds []string) (int64, error) {
	// 检查是否存在
	ids := r.ueEventRepository.SelectByIds(ueIds)
	if len(ids) <= 0 {
		return 0, fmt.Errorf("no data")
	}

	if len(ids) == len(ueIds) {
		rows := r.ueEventRepository.DeleteByIds(ueIds)
		return rows, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}

// ExportXlsx 导出数据到 xlsx 文件
func (r UEEventMME) ExportXlsx(rows []model.UEEventMME, fileName, language string) (string, error) {
	// 第一行表头标题
	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 := 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_DDTHH_MM_SSZ)
		}

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

	// 导出数据表格
	return file.WriteSheet(headerCells, dataCells, fileName, "")

}
