package controller

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

	"be.ems/features/ue/model"
	"be.ems/features/ue/service"
	"be.ems/src/framework/constants/uploadsubpath"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/telnet"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/vo/result"
	neService "be.ems/src/modules/network_element/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 实例化控制层 VoIPAuthController 结构体
var NewVoIPAuthController = &VoIPAuthController{
	voipAuthService: service.NewVoIPAuthService,
	neInfoService:   neService.NewNeInfo,
}

// IMS用户信息 控制层处理
//
// @Description IMS用户信息 控制层处理
type VoIPAuthController struct {
	voipAuthService *service.VoIPAuthService // VoIP Auth信息服务
	neInfoService   *neService.NeInfo        // 网元信息服务
}

func (s *VoIPAuthController) 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
	}

	data := s.voipAuthService.ResetData(neId)
	c.JSON(200, result.OkData(data))
}

func (s *VoIPAuthController) List(c *gin.Context) {
	querys := ctx.QueryMap(c)
	// querys["userName"] = ctx.LoginUserToUserName(c)
	// 判断租户角色
	loginUser, _ := ctx.LoginUser(c)
	if len(loginUser.User.Roles) > 0 {
		for _, v := range loginUser.User.Roles {
			if v.RoleKey == "tenant" {
				querys["tenantName"] = loginUser.User.UserName
				break
			}
		}
	}
	data := s.voipAuthService.SelectPage(querys)
	c.JSON(200, result.Ok(data))
}

func (s *VoIPAuthController) Info(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	userName := c.Param("userName")
	if neId == "" || userName == "" {
		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
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, result.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, result.ErrMsg(err.Error()))
		return
	}

	if len(data) == 0 {
		c.JSON(200, result.ErrMsg("Not found VoIP Auth data"))
		return
	}

	// 解析返回的数据
	u := s.voipAuthService.ParseInfo(userName, neId, data)
	s.voipAuthService.Insert(neId, u)
	c.JSON(200, result.OkData(u))
}

func (s *VoIPAuthController) 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.VoIPAuth
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		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
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 发送MML
	cmd := fmt.Sprintf("add voip:username=%s,", body.UserName)
	cmd += s.voipAuthService.ParseCommandParams(body)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

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

func (s *VoIPAuthController) 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.VoIPAuth
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		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
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 发送MML
	cmd := fmt.Sprintf("baa voip:start_username=%s,sub_num=%s,", body.UserName, num)
	cmd += s.voipAuthService.ParseCommandParams(body)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	// 命令ok时
	if strings.Contains(data, "ok") {
		s.voipAuthService.LoadData(neId, body.UserName, num)
	}
	c.JSON(200, result.OkData(data))
}

func (s *VoIPAuthController) 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.VoIPAuth
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		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
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

	// 发送MML
	cmd := fmt.Sprintf("mod voip:username=%s,", body.UserName)
	cmd += s.voipAuthService.ParseCommandParams(body)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

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

func (s *VoIPAuthController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	userName := c.Param("userName")
	if neId == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 处理字符转id数组后去重
	userNameArr := strings.Split(userName, ",")
	uniqueIDs := parse.RemoveDuplicates(userNameArr)
	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
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	defer telnetClient.Close()

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

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

func (s *VoIPAuthController) Removes(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	userName := c.Param("userName")
	num := c.Param("num")
	if neId == "" || 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
	}
	// 网元主机的Telnet客户端
	telnetClient, err := s.neInfoService.NeRunTelnetClient("UDM", neId, 1)
	if err != nil {
		c.JSON(200, result.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, result.ErrMsg(err.Error()))
		return
	}

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

func (s *VoIPAuthController) Export(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	querys := ctx.BodyJSONMap(c)
	neId := querys["neId"].(string)
	fileType := querys["type"].(string)
	if neId == "" || fileType == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	if !(fileType == "csv" || fileType == "txt") {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "ne.udm.errImportUserSubFileFormat")))
		return
	}

	// 判断租户角色
	loginUser, _ := ctx.LoginUser(c)
	if len(loginUser.User.Roles) > 0 {
		for _, v := range loginUser.User.Roles {
			if v.RoleKey == "tenant" {
				querys["tenantName"] = loginUser.User.UserName
				break
			}
		}
	}

	querys["pageNum"] = 1
	querys["pageSize"] = 10000
	data := s.voipAuthService.SelectPage(querys)
	if parse.Number(data["total"]) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.VoIPAuth)

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

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

	if fileType == "csv" {
		// 转换数据
		data := [][]string{}
		data = append(data, []string{"UserName", "Password"})
		for _, v := range rows {
			data = append(data, []string{v.UserName, v.Password})
		}
		// 输出到文件
		if err := file.WriterFileCSV(data, filePath); err != nil {
			c.JSON(200, result.ErrMsg(err.Error()))
			return
		}
	}

	if fileType == "txt" {
		// 转换数据
		data := [][]string{}
		for _, v := range rows {
			data = append(data, []string{v.UserName, v.Password})
		}
		// 输出到文件
		if err := file.WriterFileTXTLine(data, ",", filePath); err != nil {
			c.JSON(200, result.ErrMsg(err.Error()))
			return
		}
	}

	c.FileAttachment(filePath, fileName)
}

func (s *VoIPAuthController) Import(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		NeId       string `json:"neId" binding:"required"`
		UploadPath string `json:"uploadPath" binding:"required"`
	}
	if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

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

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

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

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

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

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