package controller

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

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/generate"
	"be.ems/src/framework/utils/parse"
	neService "be.ems/src/modules/ne/service"
	"be.ems/src/modules/trace/model"
	traceService "be.ems/src/modules/trace/service"

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

// 实例化控制层 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) {
	var query model.TraceTaskHlrQuery
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	rows, total := s.traceTaskHlrService.FindByPage(query)
	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// 跟踪任务删除
//
// DELETE /:id
func (s *TraceTaskHlrController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	id := c.Param("id")
	if id == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: id is empty"))
		return
	}

	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
	// 转换成int64数组类型
	ids := make([]int64, 0)
	for _, v := range uniqueIDs {
		ids = append(ids, parse.Number(v))
	}

	rows, err := s.traceTaskHlrService.DeleteByIds(ids)
	if err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, resp.OkMsg(msg))
}

// 跟踪任务创建
//
// POST /start
func (s *TraceTaskHlrController) Start(c *gin.Context) {
	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.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 == "" && body.MSISDN == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "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:  reqctx.LoginUserToUserName(c),
	}
	id, err := s.traceTaskHlrService.Start(task)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, resp.OkData(id))
}

// 跟踪任务停止
//
// POST /stop
func (s *TraceTaskHlrController) Stop(c *gin.Context) {
	var body struct {
		ID string `json:"id" binding:"required"` // 任务ID
	}
	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
	}

	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicatesToArray(body.ID, ",")
	// 转换成int64数组类型
	ids := make([]int64, 0)
	for _, v := range uniqueIDs {
		ids = append(ids, parse.Number(v))
	}

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

		task.UpdateBy = reqctx.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, resp.OkData(errArr))
}

// 跟踪任务文件
//
// POST /file
func (s *TraceTaskHlrController) File(c *gin.Context) {
	var body struct {
		ID  int64  `json:"id" binding:"required"`  // 任务ID
		Dir string `json:"dir" 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
	}

	task := s.traceTaskHlrService.FindById(body.ID)
	if task.ID == 0 || task.ID != body.ID {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "task not found"))
		return
	}

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

// 跟踪任务文件从网元到本地
//
// GET /filePull
func (s *TraceTaskHlrController) FilePull(c *gin.Context) {
	language := reqctx.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 {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	// 查询网元获取IP
	neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
	if neInfo.NeId != querys.NeID || neInfo.IP == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, 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()

	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 := file.CopyFile(nePath, localFilePath); err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

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