package core

import (
	"context"
	"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,
		//taskStatus: status.NewTaskStatus(svcCtx.Scheduler.AiStorages, svcCtx.Scheduler.AiService.AiCollectorAdapterMap, &svcCtx.Config),
	}
}

func (l *PageListTaskLogic) PageListTask(req *types.PageTaskReq) (resp *types.PageResult, err error) {
	res := &types.PageResult{}
	// 检查请求参数的有效性
	if req.PageSize <= 0 || req.PageNum <= 0 {
		return nil, result.NewDefaultError("Invalid page size or page number")
	}

	limit := req.PageSize
	offset := req.PageSize * (req.PageNum - 1)
	var list []*types.TaskModel

	// 构建数据库查询
	db := l.svcCtx.DbEngin.Model(&types.TaskModel{}).Table("task")
	if req.UserName != "" && req.UserName != "admin" {
		db = db.Where("user_id = ?", req.UserId)
	}

	db = db.Where("deleted_at is null")
	if req.Name != "" {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Type != "" {
		db = db.Where("adapter_type_dict = ?", req.Type)
	}
	// 计算总数
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, result.NewDefaultError(err.Error())
	}

	// 查询任务列表
	if err := db.Limit(limit).Offset(offset).Order("created_time desc").Find(&list).Error; err != nil {
		return nil, result.NewDefaultError(err.Error())
	}

	// 更新智算任务状态
	go l.svcCtx.Scheduler.AiService.St.UpdateTaskStatus(list)
	go l.svcCtx.Scheduler.AiService.St.UpdateAiTaskStatus(list)

	// 计算每个任务的运行时间x
	for _, model := range list {
		model.RunningTime = calculateRunningTime(model.StartTime, model.EndTime)
	}

	// 填充响应数据
	res.List = &list
	res.PageSize = req.PageSize
	res.PageNum = req.PageNum
	res.Total = total

	return res, nil
}

// calculateRunningTime 计算任务的运行时间
func calculateRunningTime(startTimeStr, endTimeStr string) int64 {
	if startTimeStr == "" {
		return 0
	}
	startTime := timeutils.TimeStringToGoTime(startTimeStr)
	if endTimeStr == "" {
		return int64(time.Now().Sub(startTime).Seconds())
	}
	endTime := timeutils.TimeStringToGoTime(endTimeStr)
	return int64(endTime.Sub(startTime).Seconds())
}
