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

// 实例化控制层 UDMVOIPController 结构体
var NewUDMVOIP = &UDMVOIPController{
	udmVOIPService: neDataService.NewUDMVOIPUser,
	neInfoService:  neService.NewNeInfo,
}

// UDMVOIP用户
//
// PATH /udm/voip
type UDMVOIPController struct {
	udmVOIPService *neDataService.UDMVOIPUser // UDMVOIP信息服务
	neInfoService  *neService.NeInfo          // 网元信息服务
}

// UDMVOIP用户重载数据
//
// PUT /resetData/:neId
//
//	@Tags			ne_data/udm/voip
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VOIP User Data Refresh
//	@Description	UDM VOIP User Data List Refresh Synchronization Latest
//	@Router			/neData/udm/voip/resetData/{neId} [put]
func (s *UDMVOIPController) 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.udmVOIPService.ResetData(neId)
	c.JSON(200, resp.OkData(data))
}

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

// UDMVOIP用户信息
//
// GET /:neId/:username
//
//	@Tags			ne_data/udm/voip
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			value	path		string	true	"User Name"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VOIP User Information
//	@Description	UDM VOIP User Information
//	@Router			/neData/udm/voip/{neId}/{value} [get]
func (s *UDMVOIPController) Info(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	username := c.Param("username")
	if neId == "" || username == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId or username 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("dsp voip:username=%s", username)
	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 VOIP Data"))
		return
	}

	// 解析返回的数据
	u := s.udmVOIPService.ParseInfo(neId, data)
	if u.ID != "" {
		s.udmVOIPService.Insert(neId, u.UserName)
		c.JSON(200, resp.OkData(u))
		return
	}
	c.JSON(200, resp.ErrMsg("No VOIP Data"))
}

// UDMVOIP用户新增
//
// POST /:neId
//
//	@Tags			ne_data/udm/voip
//	@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 VOIP User Added
//	@Description	UDM VOIP User Added
//	@Router			/neData/udm/voip/{neId} [post]
func (s *UDMVOIPController) 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.UDMVOIPUser
	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.UserName == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: username 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("add voip:username=%s,password=%s", body.UserName, body.Password)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

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

// UDMVOIP用户批量新增
//
// POST /:neId/:num
//
//	@Tags			ne_data/udm/voip
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			value	path		number	true	"Number of releases, value includes start username"
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VOIP User Batch Add
//	@Description	UDM VOIP User Batch Add
//	@Router			/neData/udm/voip/{neId}/{value} [post]
func (s *UDMVOIPController) Adds(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	num := c.Param("num")
	if neId == "" || num == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId or num is empty"))
		return
	}

	var body model.UDMVOIPUser
	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.UserName == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: username 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 voip:sub_num=%s,start_username=%s,password=%s", num, body.UserName, body.Password)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

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

// UDMVOIP用户删除
//
// DELETE /:neId/:username
//
//	@Tags			ne_data/udm/voip
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			value	path		string	true	"User Name, multiple separated by a , sign"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VOIP User Deletion
//	@Description	UDM VOIP User Deletion
//	@Router			/neData/udm/voip/{neId}/{value} [delete]
func (s *UDMVOIPController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	username := c.Param("username")
	if neId == "" || username == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId or username is empty"))
		return
	}

	// 处理字符转id数组后去重
	usernameArr := strings.Split(username, ",")
	uniqueIDs := parse.RemoveDuplicates(usernameArr)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, resp.Err(nil))
		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()

	resultData := map[string]string{}
	for _, v := range uniqueIDs {
		// 发送MML
		cmd := fmt.Sprintf("del voip:username=%s", v)
		data, err := telnet.ConvertToStr(telnetClient, cmd)
		if err != nil {
			resultData[v] = err.Error()
			continue
		}
		// 命令ok时
		if strings.Contains(data, "ok") {
			s.udmVOIPService.Delete(v, neId)
		}
		resultData[v] = data
	}

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

// UDMVOIP用户批量删除
//
// DELETE /:neId/:username/:num
//
//	@Tags			ne_data/udm/voip
//	@Accept			json
//	@Produce		json
//	@Param			neId	path		string	true	"NE ID"	default(001)
//	@Param			username	path		string	true	"User Name"
//	@Param			num		path		number	true	"Number of releases, value includes start username"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VOIP User Batch Deletion
//	@Description	UDM VOIP User Batch Deletion
//	@Router			/neData/udm/voip/{neId}/{username}/{num} [delete]
func (s *UDMVOIPController) Removes(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	neId := c.Param("neId")
	username := c.Param("username")
	num := c.Param("num")
	if neId == "" || username == "" || num == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: neId/username/num 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("bde voip:start_username=%s,sub_num=%s", username, 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.udmVOIPService.LoadData(neId, username, num)
	}
	c.JSON(200, resp.OkData(data))
}

// UDMVOIP用户导出
//
// GET /export
//
//	@Tags			ne_data/udm/voip
//	@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			username		query		string	false	"User Name"
//	@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 VOIP User Export
//	@Description	UDM VOIP User Export
//	@Router			/neData/udm/voip/export [get]
func (s *UDMVOIPController) 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("file type error, only support csv,txt"))
		return
	}

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

	// rows := s.udmVOIPService.SelectList(model.UDMVOIPUser{NeId: neId})
	if len(rows) <= 0 {
		// 导出数据记录为空
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

	// 文件名
	fileName := fmt.Sprintf("udm_voip_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{"username", "password", "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.UserName, v.Password, 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.UserName, v.Password, createTime})
		}
		// 输出到文件
		if err := file.WriterFileTXTLine(data, ",", filePath); err != nil {
			c.JSON(200, resp.ErrMsg(err.Error()))
			return
		}
	}

	c.FileAttachment(filePath, fileName)
}

// UDMVOIP用户导入
//
// POST /import
//
//	@Tags			ne_data/udm/voip
//	@Accept			json
//	@Produce		json
//	@Param			data	body		object	true	"Request Param"
//	@Success		200		{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		UDM VOIP User Import
//	@Description	UDM VOIP User Import
//	@Router			/neData/udm/voip/import [post]
func (s *UDMVOIPController) 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 voip: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.udmVOIPService.InsertData(neInfo.NeId, "csv", data)
		}
		if strings.HasSuffix(body.UploadPath, ".txt") {
			data := file.ReadFileTXTLine(",", localFilePath)
			go s.udmVOIPService.InsertData(neInfo.NeId, "txt", data)
		}
	}
	c.JSON(200, resp.OkMsg(resultMsg))
}
