package service

import (
	"encoding/json"
	"fmt"
	"path/filepath"

	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	neFetchlink "be.ems/src/modules/ne/fetch_link"
	neModel "be.ems/src/modules/ne/model"
	neService "be.ems/src/modules/ne/service"
	"be.ems/src/modules/trace/model"
	"be.ems/src/modules/trace/repository"
)

// 实例化数据层 TraceTaskHlr 结构体
var NewTraceTaskHlr = &TraceTaskHlr{
	traceTaskHlrRepository: repository.NewTraceTaskHlr,
	neInfoService:          neService.NewNeInfo,
}

// TraceTaskHlr 跟踪_任务给HRL网元 服务层处理
type TraceTaskHlr struct {
	traceTaskHlrRepository *repository.TraceTaskHlr // 跟踪_任务给HRL网元数据信息
	neInfoService          *neService.NeInfo        // 网元信息服务
}

// FindByPage 根据条件分页查询
func (r *TraceTaskHlr) FindByPage(querys model.TraceTaskHlrQuery) ([]model.TraceTaskHlr, int64) {
	return r.traceTaskHlrRepository.SelectByPage(querys)
}

// FindById 通过ID查询
func (r *TraceTaskHlr) FindById(id int64) model.TraceTaskHlr {
	tasks := r.traceTaskHlrRepository.SelectByIds([]int64{id})
	if len(tasks) > 0 {
		return tasks[0]
	}
	return model.TraceTaskHlr{}
}

// Insert 新增信息
func (r *TraceTaskHlr) Insert(task model.TraceTaskHlr) int64 {
	return r.traceTaskHlrRepository.Insert(task)
}

// Update 修改信息
func (r *TraceTaskHlr) Update(task model.TraceTaskHlr) int64 {
	return r.traceTaskHlrRepository.Update(task)
}

// DeleteByIds 批量删除信息
func (r *TraceTaskHlr) DeleteByIds(ids []int64) (int64, error) {
	// 检查是否存在
	rows := r.traceTaskHlrRepository.SelectByIds(ids)
	if len(rows) <= 0 {
		return 0, fmt.Errorf("not data")
	}

	if len(rows) == len(ids) {
		// 停止任务
		neInfos := r.neInfoService.Find(neModel.NeInfo{NeType: "UDM"}, false, false)
		for _, r := range rows {
			if r.Status == "0" {
				continue
			}
			for _, v := range neInfos {
				neFetchlink.HLRTraceStop(v, map[string]any{
					"traceIDArray": []string{r.TraceId},
				})
			}
		}
		num := r.traceTaskHlrRepository.DeleteByIds(ids)
		return num, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}

// Start 创建任务
func (r *TraceTaskHlr) Start(task model.TraceTaskHlr) (int64, error) {
	hlrList := []map[string]any{}
	traceId := r.traceTaskHlrRepository.LastID() + 1 // 生成任务ID < 65535
	data := map[string]any{
		"traceID": traceId,
		"imsi":    task.IMSI,
		"msisdn":  task.MSISDN,
	}
	if task.StartTime > task.EndTime {
		return 0, fmt.Errorf("startTime must less than endTime")
	}
	if task.StartTime > 0 {
		data["startTime"] = date.ParseDateToStr(task.StartTime, date.YYYY_MM_DDTHH_MM_SSZ)
	}
	if task.StartTime > 0 {
		data["endTime"] = date.ParseDateToStr(task.EndTime, date.YYYY_MM_DDTHH_MM_SSZ)
	}

	// 发送创建任务
	neInfos := r.neInfoService.Find(neModel.NeInfo{NeType: "UDM"}, false, false)
	for _, neInfo := range neInfos {
		hlrItem := map[string]any{
			"neType": neInfo.NeType,
			"neId":   neInfo.NeId,
			"msg":    "",
		}
		msg, err := neFetchlink.HLRTraceStart(neInfo, data)
		if err != nil {
			hlrItem["err"] = err.Error()
		} else {
			hlrItem["err"] = msg
		}
		hlrList = append(hlrList, hlrItem)
	}

	msg, _ := json.Marshal(hlrList)
	task.Msg = string(msg)
	task.Status = "1"
	task.TraceId = fmt.Sprint(traceId)
	id := r.traceTaskHlrRepository.Insert(task)
	if id <= 0 {
		return 0, fmt.Errorf("start task fail")
	}
	return id, nil
}

// Stop 停止任务
func (r *TraceTaskHlr) Stop(task model.TraceTaskHlr) error {
	hlrList := []map[string]any{}
	// 发送停止任务
	neInfos := r.neInfoService.Find(neModel.NeInfo{NeType: "UDM"}, false, false)
	for _, neInfo := range neInfos {
		hlrItem := map[string]any{
			"neType": neInfo.NeType,
			"neId":   neInfo.NeId,
			"msg":    "",
		}
		msg, err := neFetchlink.HLRTraceStop(neInfo, map[string]any{
			"traceIDArray": []string{task.TraceId},
		})
		if err != nil {
			hlrItem["err"] = err.Error()
		} else {
			hlrItem["err"] = msg
		}
		hlrList = append(hlrList, hlrItem)
	}

	msg, _ := json.Marshal(hlrList)
	task.Msg = string(msg)
	task.Status = "0"
	rows := r.traceTaskHlrRepository.Update(task)
	if rows <= 0 {
		return fmt.Errorf("stop task fail")
	}
	return nil
}

// File 任务文件
func (r *TraceTaskHlr) File(traceId, dirPath string) ([]map[string]any, error) {
	hlrList := []map[string]any{}
	// 查询所有匹配的网元类型
	neInfos := r.neInfoService.Find(neModel.NeInfo{NeType: "UDM"}, false, false)
	if len(neInfos) == 0 {
		return nil, fmt.Errorf("not found network element")
	}

	// 遍历多个网元主机获取文件
	for _, neInfo := range neInfos {
		hlrItem := map[string]any{
			"neType": neInfo.NeType,
			"neId":   neInfo.NeId,
			"neName": neInfo.NeName,
			"err":    "",
		}

		// // 网元主机的SSH客户端
		// sshClient, err := r.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
		// if err != nil {
		// 	hlrItem["err"] = "ssh link fail"
		// 	hlrList = append(hlrList, hlrItem)
		// 	continue
		// }
		// defer sshClient.Close()

		// 获取文件列表
		fileName := fmt.Sprintf("%s_%s", neInfo.NeName, traceId)
		rows, err := file.FileList(filepath.ToSlash(dirPath), fileName)
		if err != nil {
			hlrItem["err"] = "file not found"
			hlrList = append(hlrList, hlrItem)
			continue
		}

		// 遍历组装
		for _, v := range rows {
			if v.FileType == "file" {
				hlrItem["fileName"] = v.FileName
				hlrItem["filePath"] = filepath.ToSlash(filepath.Join(dirPath, v.FileName))
				hlrList = append(hlrList, hlrItem)
			}
		}
	}
	return hlrList, nil
}
