package adapters

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strconv"

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

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

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

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

func (l *UpdateClusterLogic) UpdateCluster(req *types.ClusterCreateReq) (resp *types.ClusterResp, err error) {
	cluster := &types.ClusterInfo{}
	result := l.svcCtx.DbEngin.Table("t_cluster").First(&cluster, req.Id)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("cluster does not exist")
	}
	utils.Convert(req, &cluster)
	// 获取集群经纬度
	//location, err := GeoMap(req.RegionName)
	//if err != nil {
	//	return nil, err
	//}
	//cluster.Location = location
	l.svcCtx.DbEngin.Table("t_cluster").Model(&cluster).Updates(&cluster)
	// 更新资源价格表
	clusterId, err := strconv.ParseInt(req.Id, 10, 64)
	if err != nil {
		return nil, err
	}
	resourceCost := &types.ResourceCost{
		ResourceID:   clusterId,
		Price:        req.Price,
		ResourceType: constants.CLUSTER,
		CostType:     req.CostType,
	}
	dbResult := l.svcCtx.DbEngin.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "resource_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"price", "cost_type"}),
	}).Create(&resourceCost)

	if dbResult.Error != nil {
		return nil, dbResult.Error
	}
	return
}
