package logic

import (
	"context"

	"github.com/zeromicro/go-zero/core/logx"
	"sundynix-micro-go/app/file/model"
	"sundynix-micro-go/app/file/rpc/file"
	"sundynix-micro-go/app/file/rpc/internal/svc"
)

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

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

// 获取文件列表
func (l *GetFileListLogic) GetFileList(in *file.GetFileListReq) (*file.GetFileListResp, error) {
	var list []model.SundynixOss
	var total int64

	db := l.svcCtx.DB.Model(&model.SundynixOss{})
	if in.Name != "" {
		db = db.Where("name LIKE ?", "%"+in.Name+"%")
	}

	db.Count(&total)

	if in.Current > 0 && in.PageSize > 0 {
		offset := (in.Current - 1) * in.PageSize
		db = db.Offset(int(offset)).Limit(int(in.PageSize))
	}

	if err := db.Find(&list).Error; err != nil {
		return nil, err
	}

	var respList []*file.FileInfo
	for _, item := range list {
		respList = append(respList, &file.FileInfo{
			Id:        item.ID,
			Name:      item.Name,
			Url:       item.Url,
			Tag:       item.Tag,
			Key:       item.Key,
			Suffix:    item.Suffix,
			Md5:       item.MD5,
			CreatedAt: item.CreatedAt.Unix(),
		})
	}

	return &file.GetFileListResp{
		List:  respList,
		Total: total,
	}, nil
}
