package mgt

import (
	"context"
	"time"

	"bsm/full/module/ec/order/internal/impl"
	"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"
	"gorm.io/gorm"
)

// 订单审批
func OrderApprove(ctx context.Context, in *pb.OrderIdentRequest) (reply *pb.OrderStatusReply, err error) {
	// 验证输入参数是否有效。
	if in.GetIdentity() == "" {
		return nil, errcode.ErrInvalidArgument
	}
	// 获取当前订单信息。
	var order models.OrderSummary
	if err := impl.DBService.Preload("OrderDetails").Where("identity=?", in.Identity).First(&order).Error; err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	// 根据订单审批状态更新订单状态：状态：-2：未通过，0：默认 1:申请退款 2:申请退货 3：申请退款退货 4：申请通过
	switch order.Approve {
	// 申请退款
	case 1:
		if in.GetApprove() == 4 {
			err = impl.DBService.Model(&models.OrderSummary{}).Where("identity=?", in.Identity).
				Updates(map[string]any{
					"approve": in.GetApprove(),
					"status":  7,
				}).Error
			if err != nil {
				printer.Error(err.Error())
				return nil, errcode.ErrDB
			}
		}
	// 申请退货
	case 2:
		if in.GetApprove() == 4 {
			impl.DBService.Transaction(func(tx *gorm.DB) error {
				err = tx.Model(&models.OrderSummary{}).Where("identity=?", in.Identity).
					Updates(map[string]any{
						"approve": in.GetApprove(),
						"status":  8,
					}).Error
				if err != nil {
					printer.Error(err.Error())
					return err
				}
				// 如果订单详情中的数量不为零，则更新产品规格的库存。
				for _, specs := range order.OrderDetails {
					if specs.Number != 0 {
						err = tx.Table("mall_product_spec").Where("product_identity = ?", specs.ProductIdentity).UpdateColumn("stock", gorm.Expr("stock + ?", specs.Number)).Error
						if err != nil {
							return err
						}
					}
				}
				return nil
			})
		}
	// 申请退款退货
	case 3:
		if in.GetApprove() == 4 {

			err = impl.DBService.Model(&models.OrderSummary{}).Where("identity=?", in.Identity).
				Updates(map[string]any{
					"approve": in.GetApprove(),
					"status":  6,
				}).Error
			if err != nil {
				printer.Error(err.Error())
				return nil, errcode.ErrDB
			}
		}
	}
	// 审批未通过
	if in.GetApprove() == -2 {
		if err := impl.DBService.Model(&models.OrderSummary{}).Where("identity=?", in.Identity).
			Update("approve", in.GetApprove()).Error; err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}

	}

	return &pb.OrderStatusReply{
		Code:     0,
		Message:  "OK",
		Identity: in.GetIdentity(),
		Timeseq:  time.Now().UnixNano(),
	}, nil

}
