package core

import (
	"context"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	clientCore "gitlink.org.cn/JointCloud/pcm-coordinator/client"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models/cloud"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gorm.io/gorm"
)

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

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

func (l *PullTaskInfoLogic) PullTaskInfo(req *clientCore.PullTaskInfoReq) (*clientCore.PullTaskInfoResp, error) {
	resp := clientCore.PullTaskInfoResp{}

	// check the kind of adapter
	var kind int32
	l.svcCtx.DbEngin.Raw("select type as kind from `t_adapter` where id = ?", req.AdapterId).Scan(&kind)
	// pull task list from database
	switch kind {
	case 2:
		var hpcModelList []models.TaskHpc
		err := findModelList(req.AdapterId, l.svcCtx.DbEngin, &hpcModelList)
		if err != nil {
			return nil, err
		}
		utils.Convert(hpcModelList, &resp.HpcInfoList)
		if len(resp.HpcInfoList) > 0 {
			for i, hpcInfo := range hpcModelList {
				err := copier.CopyWithOption(resp.HpcInfoList[i], hpcInfo, copier.Option{Converters: utils.Converters})
				if err != nil {
					return nil, err
				}
				var clusterType string
				l.svcCtx.DbEngin.Raw("SELECT label FROM `t_cluster` where id = ? ", hpcInfo.ClusterId).Scan(&clusterType)
				utils.Convert(hpcInfo.Environment, &resp.HpcInfoList[i].Environment)
				resp.HpcInfoList[i].ClusterType = clusterType
			}
		}
	case 0:
		var resourceType int32
		l.svcCtx.DbEngin.Raw("select resource_type as resourceType from `t_adapter` where id = ?", req.AdapterId).Scan(&resourceType)
		switch resourceType {
		case 01:
			var cloudModelList []cloud.TaskCloudModel
			err := findModelList(req.AdapterId, l.svcCtx.DbEngin, &cloudModelList)
			if err != nil {
				return nil, err
			}
			utils.Convert(cloudModelList, &resp.CloudInfoList)
		case 02:
			var vmModelList []models.TaskVm
			err := findModelList(req.AdapterId, l.svcCtx.DbEngin, &vmModelList)
			if err != nil {
				return nil, err
			}
			utils.Convert(vmModelList, &resp.VmInfoList)
		}

	case 1:
		var aiModelList []models.TaskAiAsynchronous
		err := findModelList(req.AdapterId, l.svcCtx.DbEngin, &aiModelList)
		if err != nil {
			return nil, err
		}
		utils.Convert(aiModelList, &resp.AiInfoList)
	}
	return &resp, nil
}

func findModelList(adapterId int64, dbEngin *gorm.DB, data interface{}) error {
	tx := dbEngin.Where("cluster_id in (select id from t_cluster where adapter_id = ?) AND status not in "+
		"('Deleted', 'Succeeded', 'COMPLETED', 'Completed', 'Failed','FAIL','statC','statE')", adapterId).Find(data)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}
