package mgt

import (
	"context"
	"errors"

	"bsm/full/module/ec/order/internal/impl"
	"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 OrderListByStore(ctx context.Context, in *pb.OrderListByStoreRequest) (reply *pb.OrderListByStoreReply, err error) {
	// parse authorization meta.
	RoleValve := &service.ParseOptions{RoleValue: "Mall_Admin"}
	if in.GetAgency() != "" {
		RoleValve = nil
	}
	auth, err := service.ParseMetaCtx(ctx, RoleValve)
	if err != nil {
		return nil, err
	}

	if auth.Owner == nil {
		return nil, errcode.ErrPermissionDenied
	}

	var (
		page                = 1
		size                = 50
		payType       int32 = 0
		cnt           int64 = 0
		storeIdentity string
	)

	if in.GetPayType() != 0 {
		payType = in.PayType
	}

	if in.GetPageNo() > 0 {
		page = int(in.PageNo)
	}
	if in.GetPageSize() > 0 {
		size = int(in.PageSize)
	}
	if in.GetAgency() != "" {
		storeIdentity = in.GetStoreIdentity()
	} else {
		ownerStore := auth.Owner.(map[string]any)
		storeIdentity = ownerStore["store_identity"].(string)
	}

	orderList := make([]*models.OrderSummary, 0)
	tx := impl.DBService.Model(&models.OrderSummary{}).Where("store_identity = ?", storeIdentity).Where("partner_id = ?", auth.ID).Preload("OrderDetails")
	// 根据状态查询订单
	if in.GetStatus() != 0 {
		tx = tx.Where("status = ?", in.GetStatus())
	}
	// 根据支付类型查询订单
	if payType != 0 {
		tx = tx.Where("pay_type  = ?", payType)

	}
	// 根据订单状态查询订单
	if len(in.GetOrderStatus()) != 0 {
		tx = tx.Where("status in ?", in.GetOrderStatus())
	}
	if in.GetKeyword() != "" {
		tx = tx.Where("order_no like ?", "%"+in.GetKeyword()+"%")
	}
	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.OrderListByStoreReply{
		Count: int32(cnt),
		Data:  data,
	}, nil
}
