package ims_user

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

	"be.ems/src/framework/constants/uploadsubpath"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/resp"
	"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"
)

// 实例化控制层 Controller 结构体
var NewController = &Controller{
	imsUserService: NewVoLTEService,
	neInfoService:  neService.NewNeInfo,
}

// IMS用户信息 控制层处理
//
// @Description IMS用户信息 控制层处理
type Controller struct {
	imsUserService *Service          // IMS User信息服务
	neInfoService  *neService.NeInfo // 网元信息服务
}

func (s *Controller) 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.imsUserService.ResetData(neId)
	c.JSON(200, result.OkData(data))
}

func (s *Controller) 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.imsUserService.SelectPage(querys)
	c.JSON(200, result.Ok(data))
}

func (s *Controller) Info(c *gin.Context) {
	language := ctx.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.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 imsuser:imsi=%s,msisdn=%s,volte=%s", imsi, msisdn, volte)
	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 IMS user data"))
		return
	}

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

func (s *Controller) 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 IMSUser
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || (len(body.IMSI) < IMSI_MAX_LENGTH && body.Tag == TAG_VoLTE) {
		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 imsuser:imsi=%s,", body.IMSI)
	cmd += s.imsUserService.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.imsUserService.Insert(neId, body)
	}
	c.JSON(200, result.OkData(data))
}

func (s *Controller) 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 IMSUser
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || (len(body.IMSI) < IMSI_MAX_LENGTH && body.Tag == TAG_VoLTE) {
		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 imsuser:start_imsi=%s,start_msisdn=%s,sub_num=%s,", body.IMSI, body.MSISDN, num)
	cmd += s.imsUserService.ParseCommandParams(body)
	// 去除msisdn参数，避免重复
	omemsisdn := fmt.Sprintf(",msisdn=%s,", body.MSISDN)
	cmd = strings.Replace(cmd, omemsisdn, ",", 1)
	data, err := telnet.ConvertToStr(telnetClient, cmd)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

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

func (s *Controller) 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 IMSUser
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || (len(body.IMSI) < IMSI_MAX_LENGTH && body.Tag == TAG_VoLTE) {
		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 imsuser:imsi=%s,", body.IMSI)
	cmd += s.imsUserService.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.imsUserService.Insert(neId, body)
	}
	c.JSON(200, result.OkData(data))
}

func (s *Controller) Remove(c *gin.Context) {
	language := ctx.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.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()

	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.imsUserService.Delete(neId, imArr[0])
		}
		resultData[im] = data
	}

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

func (s *Controller) Removes(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	neId := c.Param("neId")
	imsi := c.Param("imsi")
	num := c.Param("num")
	volte := c.Query("volte")
	if neId == "" || imsi == "" || 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.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 := ""
	if volte == "0" {
		cmd = fmt.Sprintf("bde imsuser:start_msisdn=%s,sub_num=%s,volte=0", imsi, num)
	}
	if volte == "1" {
		cmd = fmt.Sprintf("bde imsuser:start_imsi=%s,sub_num=%s,volte=1", imsi, 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.imsUserService.LoadData(neId, imsi, num)
	}
	c.JSON(200, result.OkData(data))
}

func (s *Controller) 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.imsUserService.SelectPage(querys)
	if parse.Number(data["total"]) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]IMSUser)

	// rows := s.imsUserService.SelectList(IMSUser{NeId: neId})
	if len(rows) <= 0 {
		// 导出数据记录为空
		c.JSON(200, result.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(uploadsubpath.EXPORT), fileName)

	if fileType == "csv" {
		// 转换数据
		data := [][]string{}
		data = append(data, []string{"IMSI", "MSISDN", "Tag", "VNI"})
		for _, v := range rows {
			data = append(data, []string{v.IMSI, v.MSISDN, v.Tag, v.VNI})
		}
		// 输出到文件
		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.IMSI, v.MSISDN, v.Tag, v.VNI})
		}
		// 输出到文件
		if err := file.WriterFileTXTLine(data, ",", filePath); err != nil {
			c.JSON(200, result.ErrMsg(err.Error()))
			return
		}
	}

	c.FileAttachment(filePath, fileName)
}

func (s *Controller) 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 imsuser: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.imsUserService.InsertData(neInfo.NeId, "csv", data)
		}
		if strings.HasSuffix(body.UploadPath, ".txt") {
			data := file.ReadFileTXTLine(",", localFilePath)
			go s.imsUserService.InsertData(neInfo.NeId, "txt", data)
		}
	}
	c.JSON(200, result.OkMsg(data))
}
