package adapters

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"

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

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

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

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

func (l *GetAdapterRelationLogic) GetAdapterRelation(req *types.AdapterRelationQueryReq) (resp *types.PageResult, err error) {
	resp = &types.PageResult{}
	var list []types.AdapterInfo
	db := l.svcCtx.DbEngin.Model(&types.AdapterInfo{}).Table("t_adapter")

	if req.Name != "" {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Nickname != "" {
		db = db.Where("nickname LIKE ?", "%"+req.Nickname+"%")
	}
	if req.Type != "" {
		db = db.Where("type = ?", req.Type)
	}
	if req.Version != "" {
		db = db.Where("version = ?", req.Version)
	}

	err = db.Where("deleted_at is null").Order("create_time desc").Find(&list).Error

	if err != nil {
		return resp, err
	}

	rlist := make([]*types.ClusterRelationInfo, 0)
	for _, v := range list {
		cr := &types.ClusterRelationInfo{}
		utils.Convert(&v, &cr)
		clusters := make([]*types.ClusterInfo, 0)
		l.svcCtx.DbEngin.Raw("select * from t_cluster where `deleted_at` IS NULL and adapter_id = ? ORDER BY create_time Desc", v.Id).Scan(&clusters)
		for _, c := range clusters {
			cr = &types.ClusterRelationInfo{}
			utils.Convert(&v, &cr)
			cr.CId = c.Id
			cr.CAdapterId = c.AdapterId
			cr.CName = c.Name
			cr.CNickname = c.Nickname
			cr.CDescription = c.Description
			cr.CServer = c.Server
			cr.CMonitorServer = c.MonitorServer
			cr.CUsername = c.Username
			cr.CPassword = c.Password
			cr.CToken = c.Token
			cr.CAk = c.Ak
			cr.CSk = c.Sk
			cr.CRegion = c.Region
			cr.CProjectId = c.ProjectId
			cr.CVersion = c.Version
			cr.CLabel = c.Label
			cr.COwnerId = c.OwnerId
			cr.CAuthType = c.AuthType
			cr.CRegionDict = c.RegionDict
			cr.CProducerDict = c.ProducerDict
			cr.CCreateTime = c.CreateTime
			rlist = append(rlist, cr)
		}
		if len(clusters) == 0 {
			rlist = append(rlist, cr)
		}
	}
	resp.List = rlist
	return resp, nil
}
