package core

import (
	"context"
	"github.com/ghodss/yaml"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/mqs"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/response"
	"strings"
	"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 CommitTaskLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *CommitTaskLogic) CommitTask(req *types.CommitTaskReq) error {
	//req.YamlList转换为json
	var yamlStr []string
	for _, s := range req.YamlList {
		j2, err := yaml.YAMLToJSON([]byte(s))
		if err != nil {
			logx.Errorf("Failed to convert yaml to JSON, err: %v", err)
			return err
		}
		yamlStr = append(yamlStr, string(j2))
	}
	result := strings.Join(yamlStr, ",")
	taskModel := models.Task{
		Status:     constants.Saved,
		Name:       req.Name,
		CommitTime: time.Now(),
		NsID:       req.NsID,
		YamlString: "[" + result + "]",
	}
	// 保存任务数据到数据库
	tx := l.svcCtx.DbEngin.Create(&taskModel)
	if tx.Error != nil {
		return tx.Error
	}
	task := response.TaskInfo{
		TaskId:      taskModel.Id,
		MatchLabels: req.MatchLabels,
		NsID:        req.NsID,
		Metadata:    req.YamlList,
		Replicas:    req.Replicas,
	}
	mqs.InsQueue.Beta.Add(&task)
	return nil
}
