package core

import (
	"context"
	"github.com/pkg/errors"
	clientCore "gitlink.org.cn/JointCloud/pcm-coordinator/client"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"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 AsynCommitAiTaskLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 异步提交智算任务
func NewAsynCommitAiTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AsynCommitAiTaskLogic {
	return &AsynCommitAiTaskLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AsynCommitAiTaskLogic) AsynCommitAiTask(req *types.AsynCommitAiTaskReq) (resp *types.AsynCommitAiTaskResp, err error) {
	// todo: add your logic here and delete this line
	resp = &types.AsynCommitAiTaskResp{}
	var adapterName string
	var clusterName string
	var adapterId int64

	//TODO adapter
	//adapterId, _ := strconv.ParseUint(req.AdapterIds[0], 10, 64)
	//taskAiAsynchronous := models.TaskAiAsynchronous{}

	// 构建主任务结构体
	taskModel := models.Task{
		Name:            req.Name,
		Description:     "ai asynchronous task",
		CommitTime:      time.Now(),
		Status:          "Saved",
		AdapterTypeDict: "1",
	}
	// 保存任务数据到数据库
	tx := l.svcCtx.DbEngin.Create(&taskModel)
	if tx.Error != nil {
		return nil, tx.Error
	}

	l.svcCtx.DbEngin.Raw("SELECT name 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")
	}

	AiAsynchronousInfo := models.TaskAiAsynchronous{
		TaskId:      taskModel.Id,
		AdapterId:   adapterId,
		AdapterName: adapterName,
		ClusterId:   req.ClusterId,
		ClusterName: clusterName,
		Name:        "trainJob" + utils.RandomString(10),
		StartTime:   time.Now().String(),
		Status:      "Saved",
		ImageId:     req.ImageId,
		Command:     req.Command,
		FlavorId:    req.FlavorId,
	}
	tx = l.svcCtx.DbEngin.Create(&AiAsynchronousInfo)
	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.AsynCommitAiTaskResp{
		Code:   200,
		Msg:    "success",
		TaskId: taskModel.Id,
	}
	return resp, nil
}
