package vm

import (
	"context"
	"fmt"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/helper/xerr"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/repository/result"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gitlink.org.cn/JointCloud/pcm-openstack/openstack"
	"k8s.io/apimachinery/pkg/util/json"

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

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

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

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

// ServerLinks 表示服务器链接的结构体
type ServerLinks struct {
	Href string `json:"href"` // 注意：在JSON中，"href "有一个额外的空格，需要移除
	Rel  string `json:"rel"`
}

// SecurityGroup 表示安全组的结构体
type SecurityGroup struct {
	Name string `json:"name"`
}

// Server 表示服务器的结构体
type Server struct {
	ID              string          `json:"id"`
	Links           []ServerLinks   `json:"links"`
	OSDCFDiskConfig string          `json:"OS_DCF_diskConfig"`
	SecurityGroups  []SecurityGroup `json:"security_groups"`
	AdminPass       string          `json:"adminPass"`
}

// Response 表示整个响应的结构体
type Response struct {
	Server Server `json:"server"`
}

func (l *CreateMulServerLogic) CreateMulServer(req *types.CreateMulServerReq) (resp *types.CreateMulServerResp, err error) {
	// todo: add your logic here and delete this line
	CreateServerReq := &openstack.CreateServerReq{}
	var response Response
	fmt.Println("请求入参：", req)
	for _, server := range req.CreateMulServer {
		fmt.Println("入参参数：", server)
		err = copier.CopyWithOption(CreateServerReq, server, copier.Option{Converters: utils.Converters})
		CreateServerResp, err := l.svcCtx.OpenstackRpc.CreateServer(l.ctx, CreateServerReq)
		fmt.Println("返回结果：", CreateServerResp)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrMsg("Failed to create Server list"), "Failed to get db Server list err : %v ,req:%+v", err, req)
		}
		marshal, err := json.Marshal(&CreateServerResp)
		fmt.Println("返回结果b：", marshal)
		if err != nil {
			return nil, result.NewDefaultError(err.Error())
		}
		json.Unmarshal(marshal, &response)
	}
	err = copier.CopyWithOption(&resp, &response, copier.Option{Converters: utils.Converters})
	fmt.Println("返回结果c：", resp)
	return resp, err
}
