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/ne_data/model"
	"be.ems/src/modules/ne_data/repository"
	sysService "be.ems/src/modules/system/service"
	"github.com/tsmask/go-oam"
)

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

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

// FindByPage 根据条件分页查询
func (r UEEvent) FindByPage(neType string, query map[string]string) ([]model.UEEvent, int64) {
	return r.ueEventRepository.SelectByPage(neType, query)
}

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

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

// Insert 新增信息
func (r UEEvent) Insert(param model.UEEvent) int64 {
	return r.ueEventRepository.Insert(param)
}

// ExportAMF 导出数据到 xlsx 文件
func (r UEEvent) ExportAMF(rows []model.UEEvent, fileName, language string) (string, error) {
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ID",
		"B1": "IMSI",
		"C1": "Event Type",
		"D1": "Result",
		"E1": "Time",
	}
	// 读取字典数据 UE 事件类型
	dictUEEventType := sysService.NewSysDictData.FindByType("ue_event_type")
	// 读取字典数据 UE 事件认证代码类型
	dictUEAauthCode := sysService.NewSysDictData.FindByType("ue_auth_code")
	// 读取字典数据 UE 事件CM状态
	dictUEEventCmState := sysService.NewSysDictData.FindByType("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.DataValue {
				eventType = i18n.TKey(language, v.DataLabel)
				break
			}
		}
		// 取结果
		eventResult := ""
		// 取时间
		timeStr := ""
		if row.EventType == oam.UENB_TYPE_AUTH {
			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.DataValue {
						eventResult = i18n.TKey(language, v.DataLabel)
						break
					}
				}
			}
		}
		if row.EventType == oam.UENB_TYPE_DETACH {
			if v, ok := eventJSON["detachTime"]; ok && v != nil {
				timeStr = v.(string)
			}
			eventResult = "Success"
		}
		if row.EventType == oam.UENB_TYPE_CM {
			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.DataValue {
						eventResult = i18n.TKey(language, v.DataLabel)
						break
					}
				}
			}
		}

		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, "")
}

// ExportMME 导出数据到 xlsx 文件
func (r UEEvent) ExportMME(rows []model.UEEvent, fileName, language string) (string, error) {
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ID",
		"B1": "IMSI",
		"C1": "Event Type",
		"D1": "Result",
		"E1": "Time",
	}
	// 读取字典数据 UE 事件类型
	dictUEEventType := sysService.NewSysDictData.FindByType("ue_event_type")
	// 读取字典数据 UE 事件认证代码类型
	dictUEAauthCode := sysService.NewSysDictData.FindByType("ue_auth_code")
	// 读取字典数据 UE 事件CM状态
	dictUEEventCmState := sysService.NewSysDictData.FindByType("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.DataValue {
				eventType = i18n.TKey(language, v.DataLabel)
				break
			}
		}
		// 取结果
		eventResult := ""
		if v, ok := eventJSON["result"]; ok && v != nil {
			eventResult = v.(string)
			if row.EventType == oam.UENB_TYPE_AUTH {
				for _, v := range dictUEAauthCode {
					if eventResult == v.DataValue {
						eventResult = i18n.TKey(language, v.DataLabel)
						break
					}
				}
			}
			if row.EventType == oam.UENB_TYPE_CM {
				for _, v := range dictUEEventCmState {
					if eventResult == v.DataValue {
						eventResult = i18n.TKey(language, v.DataLabel)
						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, "")

}
