package summary

import (
	"context"
	"errors"

	"bsm/full/module/ec/order/internal/logic/common"
	"bsm/full/module/ec/order/internal/models"
	pb "bsm/full/module/ec/order/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"gorm.io/gorm"
)

// 根据不同的类型获取我的订单列表
func List(ctx context.Context, in *pb.SummaryListRequest) (reply *pb.SummaryListReply, err error) {
	// parse authorization meta.
	auth, err := service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	var (
		page              = 1
		size              = 50
		payType     int32 = 0 // 支付方式
		orderStatus int32 = 0 // 订单状态
		cnt         int64 = 0
	)

	if in.PayType != 0 {
		payType = in.PayType
	}
	if in.OrderStatus != 0 {
		orderStatus = in.OrderStatus
	}
	if in.GetPageNo() > 0 {
		page = int(in.PageNo)
	}
	if in.GetPageSize() > 0 {
		size = int(in.PageSize)
	}

	orderList := make([]*models.OrderSummary, 0)
	tx := models.DBService.Model(&models.OrderSummary{}).Preload("OrderDetails").Where("passport_identity = ?", auth.Identity)
	if payType != 0 {
		tx = tx.Where("pay_type  = ?", payType)

	}
	if orderStatus != 0 {
		tx = tx.Where("status = ?", orderStatus)
	}

	err = tx.Order("created_at desc").Count(&cnt).Limit(size).Offset((page - 1) * size).Find(&orderList).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errcode.ErrRecordNotFound
		}
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	data := common.ListModelToReply(orderList)

	return &pb.SummaryListReply{
		Count: int32(cnt),
		Data:  data,
	}, nil
}
