package summary

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"
	"git.apinb.com/bsm-sdk/core/service"
)

// 取消订单
func Cancel(ctx context.Context, in *pb.CancelRequest) (reply *pb.OrderStatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	var (
		summary = new(models.OrderSummary)
	)

	err = impl.DBService.Where("order_no = ?", in.OrderNo).First(&summary).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	if summary.Status == 1 {
		values := &models.OrderSummary{
			CouponIdentity: "",
			CouponAmount:   0.00,
		}
		values.Status = -1

		err := impl.DBService.Where("order_no = ?", in.OrderNo).Updates(values).Error

		if err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}

		err = impl.DBService.Model(&models.OrderCoupon{}).Where("identity=?", summary.CouponIdentity).Update("status", 2).Error
		if err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}
	}

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

}
