package controller

import (
	"fmt"
	"strings"
	"time"

	mmlclient "nms_nbi/lib/core/mml_client"
	"nms_nbi/src/framework/constants/uploadsubpath"
	"nms_nbi/src/framework/i18n"
	"nms_nbi/src/framework/utils/ctx"
	"nms_nbi/src/framework/utils/file"
	"nms_nbi/src/framework/utils/parse"
	"nms_nbi/src/framework/utils/ssh"
	"nms_nbi/src/framework/vo/result"
	"nms_nbi/src/modules/network_element/model"
	neService "nms_nbi/src/modules/network_element/service"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 实例化控制层 UDMAuthController 结构体
var NewUDMAuth = &UDMAuthController{
	udmAuthService: neService.NewUDMAuthImpl,
	neInfoService:  neService.NewNeInfoImpl,
}

// UDM鉴权用户请求
//
// PATH /udm/auth
type UDMAuthController struct {
	// UDM鉴权信息服务
	udmAuthService neService.IUDMAuth
	// 网元信息服务
	neInfoService neService.INeInfo
}

// UDM鉴权用户-获取全部保存数据库
//
// POST /resetData/:neId
func (s *UDMAuthController) ResetData(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	if neId == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	neId = ""
	data := s.udmAuthService.Save(neId)
	c.JSON(200, result.OkData(data))
}

// UDM鉴权用户
//
// GET /list
func (s *UDMAuthController) List(c *gin.Context) {
	querys := ctx.QueryMap(c)
	querys["neId"] = ""
	data := s.udmAuthService.Page(querys)
	c.JSON(200, result.Ok(data))
}

// UDM鉴权用户-信息
//
// GET /:neId/:imsi
func (s *UDMAuthController) Info(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi := c.Param("imsi")
	if neId == "" || imsi == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	msg := fmt.Sprintf("dsp authdat:imsi=%s", imsi)

	// 发送MML
	data, err := mmlclient.MMLSendMsgToMap(neInfo.IP, msg)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	if len(data) == 0 {
		c.JSON(200, result.ErrMsg("No Auth Data"))
		return
	}

	// 查询数据库是否存在并存入
	neId = ""
	var userInfo model.UDMAuth
	list := s.udmAuthService.List(model.UDMAuth{NeID: neId, Imsi: imsi})
	if len(list) > 0 {
		userInfo = list[0]
		// 返回查询的用户信息
		userInfo.Amf = data["amf"]
		userInfo.AlgoIndex = data["algo"]
		userInfo.Opc = data["opc"]
		userInfo.Ki = data["ki"]
	} else {
		userInfo := model.UDMAuth{
			Imsi:      imsi,
			Amf:       data["amf"],
			AlgoIndex: data["algo"],
			Opc:       data["opc"],
			Ki:        data["ki"],
		}
		s.udmAuthService.Insert(neId, userInfo)
	}
	c.JSON(200, result.OkData(userInfo))
}

// UDM鉴权用户-增加
//
// POST /:neId
func (s *UDMAuthController) Add(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	if neId == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	var body model.UDMAuth
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.Imsi == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	msg := fmt.Sprintf("add authdat:imsi=%s,ki=%s,amf=%s,algo=%s,opc=%s", body.Imsi, body.Ki, body.Amf, body.AlgoIndex, body.Opc)

	// 发送MML
	data, err := mmlclient.MMLSendMsgToString(neInfo.IP, msg)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		neId = ""
		s.udmAuthService.Insert(neId, body)
	}
	c.JSON(200, result.OkData(data))
}

// UDM鉴权用户-批量添加
//
// POST /:neId/:num
func (s *UDMAuthController) Adds(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	num := c.Param("num")
	if neId == "" || num == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	var body model.UDMAuth
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.Imsi == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	msg := fmt.Sprintf("baa authdat:start_imsi=%s,sub_num=%s,ki=%s,amf=%s,algo=%s,opc=%s", body.Imsi, num, body.Ki, body.Amf, body.AlgoIndex, body.Opc)

	// 发送MML
	data, err := mmlclient.MMLSendMsgToString(neInfo.IP, msg)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		neId = ""
		s.udmAuthService.Inserts(neId, body, num)
	}
	c.JSON(200, result.OkData(data))
}

// UDM鉴权用户-修改
//
// PUT /:neId
func (s *UDMAuthController) Edit(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	if neId == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	var body model.UDMAuth
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.Imsi == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	msg := fmt.Sprintf("mod authdata:imsi=%s", body.Imsi)
	// 修改的参数名称
	if body.Ki != "" {
		msg += fmt.Sprintf(",ki=%s", body.Ki)
	}
	if body.Amf != "" {
		msg += fmt.Sprintf(",amf=%s", body.Amf)
	}
	if body.AlgoIndex != "" {
		msg += fmt.Sprintf(",algo=%s", body.AlgoIndex)
	}
	if body.Opc != "" {
		msg += fmt.Sprintf(",opc=%s", body.Opc)
	}

	// 发送MML
	data, err := mmlclient.MMLSendMsgToString(neInfo.IP, msg)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		neId = ""
		s.udmAuthService.Update(neId, body)
	}
	c.JSON(200, result.OkData(data))
}

// UDM鉴权用户-删除
//
// DELETE /:neId/:imsi
func (s *UDMAuthController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi := c.Param("imsi")
	if neId == "" || imsi == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 处理字符转id数组后去重
	imsiArr := strings.Split(imsi, ",")
	uniqueIDs := parse.RemoveDuplicates(imsiArr)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}

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

	resultData := map[string]string{}
	for _, imsi := range uniqueIDs {
		msg := fmt.Sprintf("del authdat:imsi=%s", imsi)

		// 发送MML
		data, err := mmlclient.MMLSendMsgToString(neInfo.IP, msg)
		if err != nil {
			resultData[imsi] = err.Error()
		}
		// 命令ok时
		if strings.Contains(data, "ok") {
			neId = ""
			s.udmAuthService.Delete(neId, imsi)
			resultData[imsi] = data
		}
	}

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

// UDM鉴权用户-批量删除
//
// DELETE /:neId/:imsi/:num
func (s *UDMAuthController) Removes(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi := c.Param("imsi")
	num := c.Param("num")
	if neId == "" || imsi == "" || num == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	msg := fmt.Sprintf("bde authdat:start_imsi=%s,sub_num=%s", imsi, num)

	// 发送MML
	data, err := mmlclient.MMLSendMsgToString(neInfo.IP, msg)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		neId = ""
		s.udmAuthService.Deletes(neId, imsi, num)
	}
	c.JSON(200, result.OkData(data))
}

// UDM鉴权用户-导出
//
// POST /export
func (s *UDMAuthController) Export(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		NeId string `json:"neId" binding:"required"`
		Type string `json:"type" binding:"required"`
	}
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	if !(body.Type == "csv" || body.Type == "txt") {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserAuthFileFormat")))
		return
	}

	neId := ""
	list := s.udmAuthService.List(model.UDMAuth{NeID: neId})
	// 文件名
	fileName := fmt.Sprintf("OMC_AUTH_USER_EXPORT_%s_%d.%s", neId, time.Now().UnixMilli(), body.Type)
	filePath := fmt.Sprintf("%s/%s", file.ParseUploadFileDir(uploadsubpath.EXPORT), fileName)

	if body.Type == "csv" {
		// 转换数据
		data := [][]string{}
		data = append(data, []string{"imsi", "ki", "algo", "amf", "opc"})
		for _, v := range list {
			data = append(data, []string{v.Imsi, v.Ki, v.AlgoIndex, v.Amf, v.Opc})
		}
		// 输出到文件
		err := file.WriterFileCSV(data, filePath)
		if err != nil {
			c.JSON(200, result.ErrMsg(err.Error()))
			return
		}
	}

	if body.Type == "txt" {
		// 转换数据
		data := [][]string{}
		for _, v := range list {
			data = append(data, []string{v.Imsi, v.Ki, v.AlgoIndex, v.Amf, v.Opc})
		}
		// 输出到文件
		err = file.WriterFileTXT(data, ",", filePath)
		if err != nil {
			c.JSON(200, result.ErrMsg(err.Error()))
			return
		}
	}

	c.FileAttachment(filePath, fileName)
}

// UDM鉴权用户-导入
//
// POST /import
func (s *UDMAuthController) Import(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.PostForm("neId")
	if neId == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	formFile, err := c.FormFile("file")
	if err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 获取文件名
	if !(strings.HasSuffix(formFile.Filename, ".csv") || strings.HasSuffix(formFile.Filename, ".txt")) {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserAuthFileFormat")))
		return
	}
	// 上传文件转存
	upFilePath, err := file.TransferUploadFile(formFile, uploadsubpath.IMPORT, nil)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

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

	// 本地文件
	localPath := file.ParseUploadFilePath(upFilePath)
	nePath := "/tmp" //config.Get("mml.upload").(string)
	// 复制到远程
	err = ssh.FileSCPLocalToNe(neInfo.IP, localPath, nePath)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	fileName := localPath[strings.LastIndex(localPath, "/")+1:]
	msg := fmt.Sprintf("import authdat:path=%s", fmt.Sprintf("%s/%s", nePath, fileName))

	// 发送MML
	data, err := mmlclient.MMLSendMsgToString(neInfo.IP, msg)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		if strings.HasSuffix(fileName, ".csv") {
			data := file.ReadFileCSV(localPath)
			neId = ""
			go s.udmAuthService.InsertCSV(neId, data)
		}
		if strings.HasSuffix(fileName, ".txt") {
			data := file.ReadFileTXT(",", localPath)
			neId = ""
			go s.udmAuthService.InsertTxt(neId, data)
		}
	}
	c.JSON(200, result.OkMsg(data))
}
