package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"
)

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

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

func (l *GetExchangeOrderListLogic) GetExchangeOrderList(in *plant.ExchangeOrderListReq) (*plant.ExchangeOrderListResp, error) {
	var orders []plantModel.ExchangeOrder
	var total int64
	db := l.svcCtx.DB.Model(&plantModel.ExchangeOrder{})
	if in.UserId != "" {
		db = db.Where("user_id = ?", in.UserId)
	}
	if in.Status > 0 {
		db = db.Where("status = ?", in.Status)
	}
	db.Count(&total)
	page, size := in.Current, in.PageSize
	if page < 1 {
		page = 1
	}
	if size < 1 {
		size = 10
	}
	db.Offset(int((page - 1) * size)).Limit(int(size)).Order("created_at desc").Find(&orders)
	list := make([]*plant.ExchangeOrderInfo, 0, len(orders))
	for _, o := range orders {
		list = append(list, exchangeOrderInfo(o))
	}
	return &plant.ExchangeOrderListResp{List: list, Total: total}, nil
}
