package core

import (
	"context"
	"fmt"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"math/rand"
	"time"

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

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

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

func (l *CommitVmTaskLogic) CommitVmTask(req *types.CommitVmTaskReq) (resp *types.CommitVmTaskResp, err error) {
	// todo: add your logic here and delete this line
	//Building the main task structure
	taskModel := models.Task{
		Status:     constants.Saved,
		Name:       req.Name,
		CommitTime: time.Now(),
	}
	// Save task data to database
	tx := l.svcCtx.DbEngin.Create(&taskModel)
	if tx.Error != nil {
		return nil, tx.Error
	}

	for _, CreateMulServer := range req.CreateMulServer {
		fmt.Println("", req.CreateMulServer)
		var clusterIds []int64
		l.svcCtx.DbEngin.Raw("SELECT id FROM `t_cluster` where adapter_id = ? and label = ?", req.AdapterId, req.ClusterType).Scan(&clusterIds)

		if len(clusterIds) == 0 || clusterIds == nil {
			return nil, nil
		}

		vmInfo := models.TaskVm{
			TaskId:    taskModel.Id,
			ClusterId: clusterIds[rand.Intn(len(clusterIds))],
			Name:      taskModel.Name,
			Status:    "Saved",
			StartTime: time.Now().String(),
			MinCount:  CreateMulServer.Min_count,
			ImageRef:  CreateMulServer.ImageRef,
			FlavorRef: CreateMulServer.FlavorRef,
			Uuid:      CreateMulServer.Uuid,
			Platform:  CreateMulServer.Platform,
		}

		tx = l.svcCtx.DbEngin.Create(&vmInfo)
		if tx.Error != nil {
			return nil, tx.Error
		}
		resp = &types.CommitVmTaskResp{
			Code:   200,
			Msg:    "success",
			TaskId: taskModel.Id,
		}
	}

	return resp, nil
}
