package hpc

import (
	"context"
	"github.com/go-resty/resty/v2"
	"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-hpc/slurm"

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

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

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

func (l *JobInfoLogic) JobInfo(req *types.JobInfoReq) (resp *types.JobInfoResp, err error) {
	resp = &types.JobInfoResp{}
	var clusterInfo *types.ClusterInfo
	tx := l.svcCtx.DbEngin.Raw("select * from t_cluster where id = ?", req.ClusterId).Scan(&clusterInfo)
	if tx.Error != nil {
		return nil, tx.Error
	}
	// 查询p端调用地址
	var adapterAddress string
	l.svcCtx.DbEngin.Raw("SELECT server FROM `t_adapter` where id = ?", clusterInfo.AdapterId).Scan(&adapterAddress)
	var jobResp slurm.GetJobResp
	httpClient := resty.New().R()
	_, err = httpClient.SetHeader("Content-Type", "application/json").
		SetQueryParams(map[string]string{
			"jobId":    req.JobId,
			"server":   clusterInfo.Server,
			"version":  clusterInfo.Version,
			"token":    clusterInfo.Token,
			"username": clusterInfo.Username,
		}).
		SetResult(&jobResp).
		Get(adapterAddress + "/api/v1/job/info")
	if err != nil {
		return nil, err
	}
	if len(jobResp.Errors) != 0 {
		return nil, errors.Errorf(jobResp.Errors[0].Description)
	}
	resp.JobId = jobResp.Jobs[0].JobId
	resp.JobState = jobResp.Jobs[0].JobState
	resp.CurrentWorkingDirectory = jobResp.Jobs[0].CurrentWorkingDirectory
	return resp, nil
}
