package ai

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/utils/status"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"time"
)

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

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

func (l *GetCenterTaskListLogic) GetCenterTaskList() (resp *types.CenterTaskListResp, err error) {
	resp = &types.CenterTaskListResp{}

	adapterList, err := l.svcCtx.Scheduler.AiStorages.GetAdaptersByType("1")
	if err != nil {
		return nil, err
	}

	go status.UpdateTrainingTaskStatus(l.svcCtx, adapterList)

	for _, adapter := range adapterList {
		taskList, err := l.svcCtx.Scheduler.AiStorages.GetAiTasksByAdapterId(adapter.Id)
		if err != nil {
			continue
		}
		if len(taskList) == 0 {
			continue
		}
		for _, task := range taskList {
			var elapsed time.Duration
			switch task.Status {
			case constants.Completed:
				end, err := time.ParseInLocation(constants.Layout, task.EndTime, time.Local)
				if err != nil {
					elapsed = time.Duration(0)
				}
				start, err := time.ParseInLocation(constants.Layout, task.StartTime, time.Local)
				if err != nil {
					elapsed = time.Duration(0)
				}
				elapsed = end.Sub(start)
			case constants.Running:
				elapsed = time.Now().Sub(task.CommitTime)
			default:
				elapsed = 0
			}

			t := &types.AiTask{
				Name:        task.Name,
				Status:      task.Status,
				Cluster:     task.ClusterName,
				Card:        task.Card,
				TimeElapsed: int32(elapsed.Seconds()),
			}
			resp.List = append(resp.List, t)
		}
	}

	return resp, nil
}
