/*

 Copyright (c) [2023] [pcm]
 [pcm-coordinator] is licensed under Mulan PSL v2.
 You can use this software according to the terms and conditions of the Mulan PSL v2.
 You may obtain a copy of Mulan PSL v2 at:
          http://license.coscl.org.cn/MulanPSL2
 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 See the Mulan PSL v2 for more details.

*/

package pcmcorelogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gitlink.org.cn/JointCloud/pcm-coordinator/rpc/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/rpc/pcmCore"
	"gorm.io/gorm"
)

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

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

// InfoList p端根据id查询任务列表
func (l *InfoListLogic) InfoList(in *pcmCore.InfoListReq) (*pcmCore.InfoListResp, error) {
	result := pcmCore.InfoListResp{}
	// 查询p端类型
	var kind string
	l.svcCtx.DbEngin.Raw("select type as kind from sc_participant_phy_info where id = ?", in.ParticipantId).Scan(&kind)
	// 查询云智超中的数据列表
	switch kind {
	case constants.HPC:
		var hpcModelList []models.Hpc
		findModelList(in.ParticipantId, l.svcCtx.DbEngin, &hpcModelList)
		utils.Convert(hpcModelList, &result.HpcInfoList)
	case constants.CLOUD, constants.SEALOS:
		var cloudModelList []models.Cloud
		findModelList(in.ParticipantId, l.svcCtx.DbEngin, &cloudModelList)
		utils.Convert(cloudModelList, &result.CloudInfoList)
	case constants.AI:
		var aiModelList []models.Ai
		findModelList(in.ParticipantId, l.svcCtx.DbEngin, &aiModelList)
		utils.Convert(aiModelList, &result.AiInfoList)
	}
	return &result, nil
}

func findModelList(participantId int64, dbEngin *gorm.DB, data interface{}) error {
	tx := dbEngin.Where("participant_id = ? AND status NOT IN ?", participantId, []string{"Deleted", "Succeeded", "Completed", "Failed"}).Find(data)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}
