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

// 实例化控制层 SMSCController 结构体
var NewSMSC = &SMSCController{
	neInfoService:   neService.NewNeInfo,
	cdrEventService: neDataService.NewCDREventSMSC,
}

// 网元SMSC
//
// PATH /smsc
type SMSCController struct {
	neInfoService   *neService.NeInfo           // 网元信息服务
	cdrEventService *neDataService.CDREventSMSC // CDR会话事件服务
}

// CDR会话列表
//
// GET /cdr/list
//
//	@Tags			network_data/smsc
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type only SMSC"	Enums(SMSC)
//	@Param			neId		query		string	true	"NE ID"				default(001)
//	@Param			callerParty	query		string	false	"callerParty"
//	@Param			calledParty	query		string	false	"calledParty"
//	@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		CDR Session List
//	@Description	CDR Session List
//	@Router			/neData/smsc/cdr/list [get]
func (s *SMSCController) CDRList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.CDREventSMSCQuery
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// for multi-tenancy
	querys.UserName = ctx.LoginUserToUserName(c)

	// 查询网元信息 rmUID
	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.cdrEventService.SelectPageMT(querys)
	c.JSON(200, result.Ok(data))
}

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

// CDR会话列表导出
//
// POST /cdr/export
//
//	@Tags			network_data/smsc
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		CDR Session List Export
//	@Description	CDR Session List Export
//	@Router			/neData/smsc/cdr/export [post]
func (s *SMSCController) CDRExport(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var querys model.CDREventSMSCQuery
	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
	}
	// 查询网元信息 rmUID
	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.cdrEventService.SelectPageMT(querys)
	if parse.Number(data["total"]) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.CDREventSMSC)

	// 导出文件名称
	fileName := fmt.Sprintf("smsc_cdr_event_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ID",
		"B1": "Record Behavior",
		"C1": "Service Type",
		"D1": "Caller",
		"E1": "Called",
		"F1": "Result",
		"G1": "Time",
		"H1": "Tenant Name", // for multi-tenancy
	}
	// 读取字典数据 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_DD_HH_MM_SS_GMT_TZ)
			} else {
				timeStr = v.(string)
			}
		}
		// for multi-tenant, get tenant name
		tenantName := row.TenantName

		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,
			"H" + idx: tenantName,
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}
