package core

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gorm.io/gorm"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type TaskDetailsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTaskDetailsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TaskDetailsLogic {
	return &TaskDetailsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TaskDetailsLogic) TaskDetails(req *types.FId) (resp *types.TaskDetailsResp, err error) {
	resp = &types.TaskDetailsResp{}
	task := &models.Task{}
	if errors.Is(l.svcCtx.DbEngin.Where("id", req.Id).First(&task).Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("记录不存在")
	}
	clusterIds := make([]string, 0)
	var cList []*types.ClusterInfo
	var subList []*types.SubTaskInfo
	switch task.AdapterTypeDict {
	case "0":
		l.svcCtx.DbEngin.Table("task_cloud").Where("task_id", task.Id).Scan(&subList)
		if len(subList) <= 0 {
			l.svcCtx.DbEngin.Table("task_vm").Where("task_id", task.Id).Find(&subList)
		}
	case "1":
		l.svcCtx.DbEngin.Table("task_ai").Where("task_id", task.Id).Scan(&subList)
		if len(subList) <= 0 {
			l.svcCtx.DbEngin.Table("task_ai_asynchronous").Where("task_id", task.Id).Scan(&subList)
		}
	case "2":
		l.svcCtx.DbEngin.Table("task_hpc").Where("task_id", task.Id).Scan(&subList)
		for _, hpc := range subList {
			var cluster types.ClusterInfo
			tx := l.svcCtx.DbEngin.Table("t_cluster").Where("id = ?", hpc.ClusterId).Scan(&cluster)
			if tx.Error != nil {

			}
			hpc.WorkDir = strings.TrimPrefix(hpc.WorkDir, cluster.WorkDir)
		}
	}
	for _, sub := range subList {
		clusterIds = append(clusterIds, sub.ClusterId)
	}
	err = l.svcCtx.DbEngin.Table("t_cluster").Where("id in ?", clusterIds).Scan(&cList).Error
	if err != nil {
		return resp, err
	}
	utils.Convert(&task, &resp)
	resp.ClusterInfos = cList
	resp.SubTaskInfos = subList
	return
}
