package controller

import (
	"fmt"
	"path/filepath"
	"strings"
	"time"

	"be.ems/src/framework/constants"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/telnet"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	neService "be.ems/src/modules/ne/service"
	"be.ems/src/modules/ne_data/model"
	neDataService "be.ems/src/modules/ne_data/service"

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

// 实例化控制层 UDMVolteIMSController 结构体
var NewUDMVolteIMS = &UDMVolteIMSController{
	udmVolteIMSService: neDataService.NewUDMVolteIMSUser,
	neInfoService:      neService.NewNeInfo,
}

// UDMVolteIMS用户
//
// PATH /udm/volte-ims
type UDMVolteIMSController struct {
	udmVolteIMSService *neDataService.UDMVolteIMSUser // UDMVolteIMS信息服务
	neInfoService      *neService.NeInfo              // 网元信息服务
}

// UDMVolteIMS用户重载数据
//
// PUT /resetData/:neId
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VolteIMS User Data Refresh
//	@Description	UDM Authenticated User Data List Refresh Synchronization Latest
//	@Router			/neData/udm/volte-ims/resetData/{neId} [put]
func (s *UDMVolteIMSController) ResetData(c *gin.Context) {
	neId := c.Param("neId")
	if neId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId is empty"))
		return
	}

	data := s.udmVolteIMSService.ResetData(neId)
	c.JSON(200, resp.OkData(data))
}

// UDMVolteIMS用户列表
//
// GET /list
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId		query		string	true	"NE ID"	default(001)
//	@Param			imsi		query		string	false	"IMSI"
//	@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		UDM VolteIMS User List
//	@Description	UDM VolteIMS User List
//	@Router			/neData/udm/volte-ims/list [get]
func (s *UDMVolteIMSController) List(c *gin.Context) {
	query := reqctx.QueryMap(c)
	rows, total := s.udmVolteIMSService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// UDMVolteIMS用户信息
//
// GET /:neId/:imsi
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			value	path		string	true	"IMSI"
//	@Param			msisdn		query		string	true	"MSISDN"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VolteIMS User Information
//	@Description	UDM VolteIMS User Information
//	@Router			/neData/udm/volte-ims/{neId}/{value} [get]
func (s *UDMVolteIMSController) Info(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi := c.Param("imsi")
	msisdn := c.Query("msisdn")
	volte := c.Query("volte")
	if neId == "" || imsi == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId or imsi is empty"))
		return
	}
	if msisdn == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: msisdn is required"))
		return
	}
	if volte == "" || !(volte == "0" || volte == "1") {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: volte is required"))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
	if neInfo.NeId != neId || neInfo.IP == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 发送MML
	cmd := fmt.Sprintf("dsp imsuser:imsi=%s,msisdn=%s,volte=%s", imsi, msisdn, volte)
	data, err := telnet.ConvertToMap(telnetClient, cmd)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	if len(data) == 0 {
		c.JSON(200, resp.ErrMsg("No Volte IMS Data"))
		return
	}

	// 解析返回的数据
	u := s.udmVolteIMSService.ParseInfo(neId, data)
	if u.ID != "" {
		s.udmVolteIMSService.InsertByIMSI(imsi, neId)
		c.JSON(200, resp.OkData(u))
		return
	}
	c.JSON(200, resp.ErrMsg("No Volte IMS Data"))
}

// UDMVolteIMS用户新增
//
// POST /:neId
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VolteIMS User Added
//	@Description	UDM VolteIMS User Added If VoIP tag=0, then MSISDN and IMSI need to be the same.
//	@Router			/neData/udm/volte-ims/{neId} [post]
func (s *UDMVolteIMSController) Add(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	if neId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId is empty"))
		return
	}

	var body model.UDMVolteIMSUser
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.IMSI == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: imsi is empty"))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
	if neInfo.NeId != neId || neInfo.IP == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 检查同IMSI下msisdn是否存在
	hasMsisdns := s.udmVolteIMSService.Find(model.UDMVolteIMSUser{IMSI: body.IMSI, MSISDN: body.MSISDN, NeId: neId})
	if len(hasMsisdns) > 0 {
		c.JSON(200, resp.ErrMsg("IMSI and MSISDN already exist"))
		return
	}

	// 发送MML
	cmd := fmt.Sprintf("add imsuser:imsi=%s,msisdn=%s,volte=%s,vni=%s", body.IMSI, body.MSISDN, body.Tag, body.VNI)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		s.udmVolteIMSService.InsertByIMSI(body.IMSI, neId)
	}
	c.JSON(200, resp.OkData(data))
}

// UDMVolteIMS用户批量新增
//
// POST /:neId/:num
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			value	path		number	true	"Number of releases, value includes start imsi"
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VolteIMS User Batch Add
//	@Description	UDM VolteIMS User Batch Add
//	@Router			/neData/udm/volte-ims/{neId}/{value} [post]
func (s *UDMVolteIMSController) Adds(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	num := c.Param("num")
	if neId == "" || num == "" {
		c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	var body model.UDMVolteIMSUser
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.IMSI == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: imsi is empty"))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
	if neInfo.NeId != neId || neInfo.IP == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 发送MML
	cmd := fmt.Sprintf("baa imsuser:sub_num=%s,start_imsi=%s,start_msisdn=%s,volte=%s,vni=%s", num, body.IMSI, body.MSISDN, body.Tag, body.VNI)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		s.udmVolteIMSService.LoadData(neId, body.IMSI, num)
	}
	c.JSON(200, resp.OkData(data))
}

// UDMVolteIMS用户删除
//
// DELETE /:neId/:imsi
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			value	path		string	true	"IMSI, multiple separated by a , sign"
//	@Param			msisdn		query		string	false	"MSISDN"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM Authenticated User Deletion
//	@Description	UDM Authenticated User Deletion
//	@Router			/neData/udm/volte-ims/{neId}/{value} [delete]
func (s *UDMVolteIMSController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi_msisdn := c.Param("imsi")
	volte := c.Query("volte")
	if neId == "" || imsi_msisdn == "" {
		c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	if volte == "" || !(volte == "0" || volte == "1") {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: volte is required"))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
	if neInfo.NeId != neId || neInfo.IP == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	imsiArr := strings.Split(imsi_msisdn, ",")
	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicates(imsiArr)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, resp.Err(nil))
		return
	}
	resultData := map[string]string{}
	for _, im := range uniqueIDs {
		imArr := strings.SplitN(im, "_", 2)
		if len(imArr) != 2 {
			resultData[im] = "format should be imsi_msisdn"
			continue
		}
		// 发送MML
		cmd := fmt.Sprintf("del imsuser:imsi=%s,msisdn=%s,volte=%s", imArr[0], imArr[1], volte)
		data, err := telnet.ConvertToStr(telnetClient, cmd)
		if err != nil {
			resultData[im] = err.Error()
			continue
		}
		// 命令ok时
		if strings.Contains(data, "ok") {
			s.udmVolteIMSService.Delete(imArr[0], neId)
		}
		resultData[im] = data
	}
	c.JSON(200, resp.OkData(resultData))
}

// UDMVolteIMS用户批量删除
//
// DELETE /:neId/:imsi/:num
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			imsi	path		string	true	"IMSI"
//	@Param			num		path		number	true	"Number of releases, value includes start imsi"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VolteIMS User Batch Deletion
//	@Description	UDM VolteIMS User Batch Deletion
//	@Router			/neData/udm/volte-ims/{neId}/{imsi}/{num} [delete]
func (s *UDMVolteIMSController) Removes(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi_msisdn := c.Param("imsi")
	num := c.Param("num")
	volte := c.Query("volte")
	if neId == "" || imsi_msisdn == "" || num == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId/imsi/num is empty"))
		return
	}
	if volte == "" || !(volte == "0" || volte == "1") {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: volte is required"))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.FindByNeTypeAndNeID("UDM", neId)
	if neInfo.NeId != neId || neInfo.IP == "" {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
		return
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	imArr := strings.SplitN(imsi_msisdn, "_", 2)
	if len(imArr) != 2 {
		c.JSON(200, resp.ErrMsg("format should be imsi_msisdn"))
		return
	}
	imsi := imArr[0]
	msisdn := imArr[1]

	// 发送MML
	cmd := ""
	if volte == "0" {
		cmd = fmt.Sprintf("bde imsuser:start_msisdn=%s,sub_num=%s,volte=0", msisdn, num)
	}
	if volte == "1" {
		cmd = fmt.Sprintf("bde imsuser:start_imsi=%s,start_msisdn=%s,sub_num=%s,volte=1", imsi, msisdn, num)
	}
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(data, "ok") {
		s.udmVolteIMSService.LoadData(neId, imsi, num)
	}
	c.JSON(200, resp.OkData(data))
}

// UDMVolteIMS用户导出
//
// GET /export
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			neId		query		string	true	"NE ID"		default(001)
//	@Param			type		query		string	true	"File Type"	Enums(csv,txt)	default(txt)
//	@Param			imsi		query		string	false	"IMSI"
//	@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		UDM Authenticated User Export
//	@Description	UDM Authenticated User Export
//	@Router			/neData/udm/volte-ims/export [get]
func (s *UDMVolteIMSController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	neId := c.Query("neId")
	fileType := c.Query("type")
	if neId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId is empty"))
		return
	}
	if !(fileType == "csv" || fileType == "txt") {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat")))
		return
	}

	query := reqctx.QueryMap(c)
	rows, total := s.udmVolteIMSService.FindByPage(query)
	if total == 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	if len(rows) <= 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

	// 文件名
	fileName := fmt.Sprintf("udm_volte_user_export_%s_%d.%s", neId, time.Now().UnixMilli(), fileType)
	filePath := filepath.Join(file.ParseUploadFileDir(constants.UPLOAD_EXPORT), fileName)

	if fileType == "csv" {
		// 转换数据
		data := [][]string{}
		data = append(data, []string{"IMSI", "MSISDN", "TAG", "VNI", "CreateTime"})
		for _, v := range rows {
			createTime := ""
			if v.CreateTime == 0 {
				createTime = time.Now().Format(time.RFC3339)
			} else {
				createTime = time.UnixMilli(v.CreateTime).Format(time.RFC3339)
			}
			data = append(data, []string{v.IMSI, v.MSISDN, v.Tag, v.VNI, createTime})
		}
		// 输出到文件
		if err := file.WriterFileCSV(data, filePath); err != nil {
			c.JSON(200, resp.ErrMsg(err.Error()))
			return
		}
	}

	if fileType == "txt" {
		// 转换数据
		data := [][]string{}
		for _, v := range rows {
			createTime := ""
			if v.CreateTime == 0 {
				createTime = time.Now().Format(time.RFC3339)
			} else {
				createTime = time.UnixMilli(v.CreateTime).Format(time.RFC3339)
			}
			data = append(data, []string{v.IMSI, v.MSISDN, v.Tag, v.VNI, createTime})
		}
		// 输出到文件
		if err := file.WriterFileTXTLine(data, ",", filePath); err != nil {
			c.JSON(200, resp.ErrMsg(err.Error()))
			return
		}
	}

	c.FileAttachment(filePath, fileName)
}

// UDMVolteIMS用户导入
//
// POST /import
//
//	@Tags			ne_data/udm/volte-ims
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM Authenticated User Import
//	@Description	UDM Authenticated User Import
//	@Router			/neData/udm/volte-ims/import [post]
func (s *UDMVolteIMSController) Import(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body struct {
		NeId       string `json:"neId" binding:"required"`       // 网元ID
		UploadPath string `json:"uploadPath" binding:"required"` // 上传文件路径
	}
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	// 判断文件名
	if !(strings.HasSuffix(body.UploadPath, ".csv") || strings.HasSuffix(body.UploadPath, ".txt")) {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserAuthFileFormat")))
		return
	}

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

	// 网元主机的SSH客户端
	// sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
	// if err != nil {
	// 	c.JSON(200, resp.ErrMsg(err.Error()))
	// 	return
	// }
	// defer sshClient.Close()
	// // 网元主机的SSH客户端进行文件传输
	// sftpClient, err := sshClient.NewClientSFTP()
	// if err != nil {
	// 	c.JSON(200, resp.ErrMsg(err.Error()))
	// 	return
	// }
	// defer sftpClient.Close()

	// 本地文件
	localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
	neFilePath := fmt.Sprintf("/tmp/%s", filepath.Base(localFilePath))
	// 复制到远程
	// if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
	// 	c.JSON(200, resp.ErrMsg("error uploading file"))
	// 	return
	// }
	if err := file.CopyFile(localFilePath, neFilePath); err != nil {
		c.JSON(200, resp.ErrMsg("error uploading file"))
		return
	}

	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient(neInfo.NeType, neInfo.NeId, 1)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 结果信息
	var resultMsg string
	var resultErr error

	// 发送MML
	cmd := fmt.Sprintf("import imsuser:path=%s", neFilePath)
	resultMsg, resultErr = telnet.ConvertToStr(telnetClient, cmd)
	if resultErr != nil {
		c.JSON(200, resp.ErrMsg(resultErr.Error()))
		return
	}

	// 命令ok时
	if strings.Contains(resultMsg, "ok") {
		if strings.HasSuffix(body.UploadPath, ".csv") {
			data := file.ReadFileCSV(localFilePath)
			go s.udmVolteIMSService.InsertData(neInfo.NeId, "csv", data)
		}
		if strings.HasSuffix(body.UploadPath, ".txt") {
			data := file.ReadFileTXTLine(",", localFilePath)
			go s.udmVolteIMSService.InsertData(neInfo.NeId, "txt", data)
		}
	}
	c.JSON(200, resp.OkMsg(resultMsg))
}
