package core

import (
	"context"
	"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/repository/result"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils/timeutils"
	"time"

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

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

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

func (l *PageListTaskLogic) PageListTask(req *types.PageTaskReq) (resp *types.PageResult, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	resp = &types.PageResult{}
	var list []*types.TaskModel
	db := l.svcCtx.DbEngin.Model(&types.TaskModel{}).Table("task")

	db = db.Where("deleted_at is null")
	if req.Name != "" {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}

	//count total
	var total int64
	err = db.Count(&total).Error
	db.Limit(limit).Offset(offset)

	if err != nil {
		return resp, err
	}
	err = db.Order("created_time desc").Find(&list).Error
	if err != nil {
		return nil, result.NewDefaultError(err.Error())
	}

	// 更新智算任务状态
	go status.UpdateTaskStatus(l.svcCtx, list)
	go status.UpdateAiTaskStatus(l.svcCtx, list)

	for _, model := range list {
		if model.StartTime != "" && model.EndTime == "" {
			startTime := timeutils.TimeStringToGoTime(model.StartTime)
			model.RunningTime = int64(time.Now().Sub(startTime).Seconds())
		}
		if model.StartTime != "" && model.EndTime != "" {
			startTime := timeutils.TimeStringToGoTime(model.StartTime)
			endTime := timeutils.TimeStringToGoTime(model.EndTime)
			model.RunningTime = int64(endTime.Sub(startTime).Seconds())
		}
	}
	resp.List = &list
	resp.PageSize = req.PageSize
	resp.PageNum = req.PageNum
	resp.Total = total

	return
}
