package admin_query

import (
	"context"
	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"
	"tydata-server/app/main/model"
	"tydata-server/common/globalkey"
	"tydata-server/common/xerr"

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

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

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

func (l *AdminGetQueryCleanupLogListLogic) AdminGetQueryCleanupLogList(req *types.AdminGetQueryCleanupLogListReq) (resp *types.AdminGetQueryCleanupLogListResp, err error) {
	// 构建查询条件
	builder := l.svcCtx.QueryCleanupLogModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.Status > 0 {
		builder = builder.Where("status = ?", req.Status)
	}
	if req.StartTime != "" {
		builder = builder.Where("cleanup_time >= ?", req.StartTime)
	}
	if req.EndTime != "" {
		builder = builder.Where("cleanup_time <= ?", req.EndTime)
	}

	// 并发获取总数和列表
	var total int64
	var logs []*model.QueryCleanupLog
	err = mr.Finish(func() error {
		var err error
		total, err = l.svcCtx.QueryCleanupLogModel.FindCount(l.ctx, builder, "id")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理日志总数失败 err: %v", err)
		}
		return nil
	}, func() error {
		var err error
		logs, err = l.svcCtx.QueryCleanupLogModel.FindPageListByPage(l.ctx, builder, req.Page, req.PageSize, "id DESC")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询清理日志列表失败 err: %v", err)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	// 构建响应
	resp = &types.AdminGetQueryCleanupLogListResp{
		Total: total,
		Items: make([]types.QueryCleanupLogItem, 0, len(logs)),
	}

	for _, log := range logs {
		item := types.QueryCleanupLogItem{
			Id:            log.Id,
			CleanupTime:   log.CleanupTime.Format("2006-01-02 15:04:05"),
			CleanupBefore: log.CleanupBefore.Format("2006-01-02 15:04:05"),
			Status:        log.Status,
			AffectedRows:  log.AffectedRows,
			ErrorMsg:      log.ErrorMsg.String,
			Remark:        log.Remark.String,
			CreateTime:    log.CreateTime.Format("2006-01-02 15:04:05"),
		}
		resp.Items = append(resp.Items, item)
	}

	return resp, nil
}
