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

// 实例化数据层 CDREventSMSC 结构体
var NewCDREventSMSC = &CDREventSMSC{
	cdrEventRepository: repository.NewCDREventSMSC,
}

// CDREventSMSC CDR会话事件SMSC 服务层处理
type CDREventSMSC struct {
	cdrEventRepository *repository.CDREventSMSC // CDR会话事件数据信息
}

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

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

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

// ExportXlsx 导出数据到 xlsx 文件
func (r CDREventSMSC) ExportXlsx(rows []model.CDREventSMSC, fileName, language string) (string, error) {
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ID",
		"B1": "Record Behavior",
		"C1": "Service Type",
		"D1": "Caller",
		"E1": "Called",
		"F1": "Result",
		"G1": "Time",
	}
	// 读取字典数据 CDR 原因码
	dictCDRCauseCode := sysService.NewSysDictData.SelectDictDataByType("cdr_cause_code")
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 解析 JSON 字符串为 map
		var cdrJSON map[string]interface{}
		err := json.Unmarshal([]byte(row.CDRJSONStr), &cdrJSON)
		if err != nil {
			logger.Warnf("CDRExport Error parsing JSON: %s", err.Error())
			continue
		}
		// 记录类型
		recordType := ""
		if v, ok := cdrJSON["recordType"]; ok && v != nil {
			recordType = v.(string)
		}
		// 服务类型
		serviceType := ""
		if v, ok := cdrJSON["serviceType"]; ok && v != nil {
			serviceType = v.(string)
		}
		// 被叫
		called := ""
		if v, ok := cdrJSON["calledParty"]; ok && v != nil {
			called = v.(string)
		}
		// 主叫
		caller := ""
		if v, ok := cdrJSON["callerParty"]; ok && v != nil {
			caller = v.(string)
		}
		// 呼叫结果 0失败，1成功
		callResult := "Fail"
		if v, ok := cdrJSON["result"]; ok && v != nil {
			resultVal := parse.Number(v)
			if resultVal == 1 {
				callResult = "Success"
			}
		}
		// 结果原因
		if v, ok := cdrJSON["cause"]; ok && v != nil && callResult == "Fail" {
			cause := fmt.Sprint(v)
			for _, v := range dictCDRCauseCode {
				if cause == v.DictValue {
					callResult = fmt.Sprintf("%s, %s", callResult, i18n.TKey(language, v.DictLabel))
					break
				}
			}
		}
		// 取时间
		timeStr := ""
		if v, ok := cdrJSON["updateTime"]; ok && v != nil {
			if releaseTime := parse.Number(v); releaseTime > 0 {
				timeStr = date.ParseDateToStr(releaseTime, date.YYYY_MM_DDTHH_MM_SSZ)
			} else {
				timeStr = v.(string)
			}
		}

		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.ID,
			"B" + idx: recordType,
			"C" + idx: serviceType,
			"D" + idx: caller,
			"E" + idx: called,
			"F" + idx: callResult,
			"G" + idx: timeStr,
		})
	}

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