package core

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/utils/status"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/repository/result"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

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

type ScreenPageTaskLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	taskStatus *status.TaskStatus
}

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

func (l *ScreenPageTaskLogic) ScreenPageTask(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")

	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())
	}

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

	return res, nil
}
