package hpc

import (
	"context"
	"errors"
	clientCore "gitlink.org.cn/JointCloud/pcm-coordinator/client"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"time"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

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

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

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

func (l *CommitHpcTaskLogic) CommitHpcTask(req *types.CommitHpcTaskReq) (resp *types.CommitHpcTaskResp, err error) {

	var clusterInfo types.ClusterInfo
	l.svcCtx.DbEngin.Raw("SELECT * FROM `t_cluster` where id = ? and label = ?", req.ClusterId, req.ClusterType).First(&clusterInfo)

	if len(clusterInfo.Id) == 0 {
		resp.Code = 400
		resp.Msg = "no cluster found"
		return resp, nil
	}

	// 构建主任务结构体
	taskModel := models.Task{
		Name:            req.Name,
		Description:     req.Description,
		CommitTime:      time.Now(),
		Status:          "Saved",
		AdapterTypeDict: "2",
	}

	// 保存任务数据到数据库
	tx := l.svcCtx.DbEngin.Create(&taskModel)
	if tx.Error != nil {
		return nil, tx.Error
	}

	var clusterName string
	var adapterId int64
	var adapterName string
	l.svcCtx.DbEngin.Raw("SELECT nickname FROM `t_cluster` where id = ?", req.ClusterId).Scan(&clusterName)
	l.svcCtx.DbEngin.Raw("SELECT adapter_id FROM `t_cluster` where id = ?", req.ClusterId).Scan(&adapterId)
	l.svcCtx.DbEngin.Raw("SELECT name FROM `t_adapter` where id = ?", adapterId).Scan(&adapterName)
	if len(adapterName) == 0 || adapterName == "" {
		return nil, errors.New("no corresponding adapter found")
	}

	hpcInfo := models.TaskHpc{
		TaskId:      taskModel.Id,
		AdapterId:   adapterId,
		AdapterName: adapterName,
		ClusterId:   req.ClusterId,
		ClusterName: clusterName,
		Name:        taskModel.Name,
		CmdScript:   req.CmdScript,
		StartTime:   time.Now().String(),
		CardCount:   req.CardCount,
		WorkDir:     req.WorkDir,
		WallTime:    req.WallTime,
		AppType:     req.AppType,
		AppName:     req.AppName,
		Queue:       req.Queue,
		SubmitType:  req.SubmitType,
		NNode:       req.NNode,
		Account:     clusterInfo.Username,
		StdInput:    req.StdInput,
		Partition:   req.Partition,
		Environment: clusterInfo.Environment,
		CreatedTime: time.Now(),
		UpdatedTime: time.Now(),
		Status:      "Saved",
	}
	hpcInfo.WorkDir = clusterInfo.WorkDir + "/" + req.WorkDir
	tx = l.svcCtx.DbEngin.Create(&hpcInfo)
	if tx.Error != nil {
		return nil, tx.Error
	}
	noticeInfo := clientCore.NoticeInfo{
		AdapterId:   adapterId,
		AdapterName: adapterName,
		ClusterId:   req.ClusterId,
		ClusterName: clusterName,
		NoticeType:  "create",
		TaskName:    req.Name,
		Incident:    "任务创建中",
	}
	result := l.svcCtx.DbEngin.Table("t_notice").Create(&noticeInfo)
	if result.Error != nil {
		logx.Errorf("Task creation failure, err: %v", result.Error)
	}
	resp = &types.CommitHpcTaskResp{
		Code:   200,
		Msg:    "success",
		TaskId: taskModel.Id,
	}
	return resp, nil
}
