package controller

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/generate"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/vo/result"
	neService "be.ems/src/modules/network_element/service"
	"be.ems/src/modules/trace/model"
	traceService "be.ems/src/modules/trace/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 实例化控制层 TraceTaskHlrController 结构体
var NewTraceTaskHlr = &TraceTaskHlrController{
	neInfoService:       neService.NewNeInfo,
	traceTaskHlrService: traceService.NewTraceTaskHlr,
}

// 跟踪任务网元HLR
//
// PATH /task/hlr
type TraceTaskHlrController struct {
	neInfoService       *neService.NeInfo          // 网元信息服务
	traceTaskHlrService *traceService.TraceTaskHlr // 跟踪_任务给HRL网元信息服务
}

// 跟踪任务列表
//
// GET /list
func (s *TraceTaskHlrController) List(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys model.TraceTaskHlrQuery
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 查询数据
	data := s.traceTaskHlrService.SelectPage(querys)
	c.JSON(200, result.Ok(data))
}

// 跟踪任务删除
//
// DELETE /:ids
func (s *TraceTaskHlrController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	rowIds := c.Param("ids")
	if rowIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(rowIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows, err := s.traceTaskHlrService.DeleteByIds(uniqueIDs)
	if err != nil {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, result.OkMsg(msg))
}

// 跟踪任务创建
//
// POST /start
func (s *TraceTaskHlrController) Start(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		IMSI      string `json:"imsi"`      // IMSI
		MSISDN    string `json:"msisdn"`    // MSISDN
		StartTime int64  `json:"startTime"` // 开始时间
		EndTime   int64  `json:"endTime"`   // 结束时间
		Remark    string `json:"remark"`    // 备注说明
	}
	if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	if body.IMSI == "" && body.MSISDN == "" {
		c.JSON(400, result.CodeMsg(400, "imsi amd msisdn is empty"))
		return
	}

	task := model.TraceTaskHlr{
		IMSI:      body.IMSI,
		MSISDN:    body.MSISDN,
		StartTime: body.StartTime,
		EndTime:   body.EndTime,
		Remark:    body.Remark,
		CreateBy:  ctx.LoginUserToUserName(c),
	}
	id, err := s.traceTaskHlrService.Start(task)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, result.OkData(id))
}

// 跟踪任务停止
//
// POST /stop
func (s *TraceTaskHlrController) Stop(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		ID string `json:"id" binding:"required"` // 任务ID
	}
	if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

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

	errArr := []map[string]any{}
	for _, id := range uniqueIDs {
		task := s.traceTaskHlrService.SelectById(id)
		if task.ID != id || task.ID == "" {
			errArr = append(errArr, map[string]any{"id": id, "err": "task not found"})
			continue
		}

		task.UpdateBy = ctx.LoginUserToUserName(c)
		err := s.traceTaskHlrService.Stop(task)
		if err != nil {
			errArr = append(errArr, map[string]any{"id": id, "err": err.Error()})
			continue
		}
	}
	c.JSON(200, result.OkData(errArr))
}

// 跟踪任务文件
//
// POST /file
func (s *TraceTaskHlrController) File(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		ID  string `json:"id" binding:"required"`  // 任务ID
		Dir string `json:"dir" binding:"required"` // 网元文件目录
	}
	if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	task := s.traceTaskHlrService.SelectById(body.ID)
	if task.ID != body.ID || task.ID == "" {
		c.JSON(200, result.CodeMsg(400, "task not found"))
		return
	}

	list, err := s.traceTaskHlrService.File(task.TraceId, body.Dir)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, result.OkData(list))
}

// 跟踪任务文件从网元到本地
//
// GET /filePull
func (s *TraceTaskHlrController) FilePull(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var querys struct {
		NeType   string `form:"neType" binding:"required"`
		NeID     string `form:"neId" binding:"required"`
		Path     string `form:"path" binding:"required"`
		FileName string `form:"fileName" binding:"required"`
		DelTemp  bool   `form:"delTemp"` // 删除本地临时文件
	}
	if err := c.ShouldBindQuery(&querys); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
	if neInfo.NeId != querys.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()

	nePath := filepath.ToSlash(filepath.Join(querys.Path, querys.FileName))
	fileName := generate.Code(6) + "_" + querys.FileName
	localFilePath := filepath.Join("/tmp/omc/pull", fileName)
	if runtime.GOOS == "windows" {
		localFilePath = fmt.Sprintf("C:%s", localFilePath)
	}
	// 复制到本地
	if err = sftpClient.CopyFileRemoteToLocal(nePath, localFilePath); err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}

	defer func() {
		if querys.DelTemp {
			_ = os.Remove(localFilePath)
		}
	}()
	c.FileAttachment(localFilePath, fileName)
}
