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"
	neFetchlink "be.ems/src/modules/network_element/fetch_link"
	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"
)

// 实例化控制层 IMSController 结构体
var NewIMS = &IMSController{
	neInfoService:   neService.NewNeInfo,
	cdrEventService: neDataService.NewCDREventIMS,
}

// 网元IMS
//
// PATH /ims
type IMSController struct {
	neInfoService   *neService.NeInfo          // 网元信息服务
	cdrEventService *neDataService.CDREventIMS // CDR会话事件服务
}

// CDR会话列表
//
// GET /cdr/list
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neType		query		string	true	"NE Type only IMS"	Enums(IMS)
//	@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/ims/cdr/list [get]
func (s *IMSController) CDRList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.CDREventIMSQuery
	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/ims
//	@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/ims/cdr/{cdrIds} [delete]
func (s *IMSController) 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/ims
//	@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/ims/cdr/export [post]
func (s *IMSController) CDRExport(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	var querys model.CDREventIMSQuery
	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.CDREventIMS)

	// 导出文件名称
	fileName := fmt.Sprintf("ims_cdr_event_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ID",
		"B1": "Record Behavior",
		"C1": "Type",
		"D1": "Caller",
		"E1": "Called",
		"F1": "Duration",
		"G1": "Result",
		"H1": "Time",
		"I1": "Tenant Name", // for multi-tenancy
	}
	// 读取字典数据 CDR SIP响应代码类别类型
	dictCDRSipCode := sysService.NewSysDictData.SelectDictDataByType("cdr_sip_code")
	// 读取字典数据 CDR 呼叫类型
	dictCDRCallType := sysService.NewSysDictData.SelectDictDataByType("cdr_call_type")
	// 从第二行开始的数据
	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)
		}
		// 呼叫类型
		callType := "sms"
		callTypeLable := "SMS"
		if v, ok := cdrJSON["callType"]; ok && v != nil {
			callType = v.(string)
			for _, v := range dictCDRCallType {
				if callType == v.DictValue {
					callTypeLable = i18n.TKey(language, v.DictLabel)
					break
				}
			}
		}
		// 被叫
		called := ""
		if v, ok := cdrJSON["calledParty"]; ok && v != nil {
			called = v.(string)
		}
		// 主叫
		caller := ""
		if v, ok := cdrJSON["callerParty"]; ok && v != nil {
			caller = v.(string)
		}
		// 时长
		duration := "-"
		if v, ok := cdrJSON["callDuration"]; ok && v != nil && callType != "sms" {
			duration = fmt.Sprint(parse.Number(v))
		}
		// 呼叫结果 非短信都有code作为结果 sms短信都ok
		callResult := "Success"
		if v, ok := cdrJSON["cause"]; ok && v != nil && callType != "sms" {
			cause := fmt.Sprint(v)
			for _, v := range dictCDRSipCode {
				if cause == v.DictValue {
					callResult = i18n.TKey(language, v.DictLabel)
					break
				}
			}
		}
		// 取时间
		timeStr := ""
		if v, ok := cdrJSON["releaseTime"]; ok && v != nil {
			if releaseTime := parse.Number(v); releaseTime > 0 {
				timeStr = date.ParseDateToStr(releaseTime, date.YYYY_MM_DDTHH_MM_SSZ)
			} 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: callTypeLable,
			"D" + idx: caller,
			"E" + idx: called,
			"F" + idx: duration,
			"G" + idx: callResult,
			"H" + idx: timeStr,
			"I" + idx: tenantName,
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}

// 在线会话用户数量
//
// GET /session/num
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Number of online session users
//	@Description	Number of online session users
//	@Router			/neData/ims/session/num [get]
func (s *IMSController) UeSessionNum(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var query struct {
		NeId string `form:"neId" binding:"required"`
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 查询网元信息
	neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("IMS", query.NeId)
	if neInfo.NeId != query.NeId || neInfo.IP == "" {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}

	// 网元直连
	num, err := neFetchlink.IMSUeSessionNum(neInfo)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	c.JSON(200, result.OkData(num))
}

// 在线会话用户列表信息
//
// GET /session/list
//
//	@Tags			network_data/ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	query		string	true	"NE ID"	default(001)
//	@Param			imsi	query		string	false	"imsi"
//	@Param			msisdn	query		string	false	"msisdn"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Online session user list information
//	@Description	Online session user list information
//	@Router			/neData/ims/session/list [get]
func (s *IMSController) UeSessionList(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var query struct {
		NeId   string `form:"neId" binding:"required"`
		IMSI   string `form:"imsi"`
		MSISDN string `form:"msisdn"`
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 查询网元信息
	neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID("IMS", query.NeId)
	if neInfo.NeId != query.NeId || neInfo.IP == "" {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}

	// 网元直连
	data, err := neFetchlink.IMSUeSessionList(neInfo, map[string]string{
		"imsi":   query.IMSI,
		"msisdn": query.MSISDN,
	})
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	c.JSON(200, result.OkData(data))
}
