package summary

import (
	"context"

	"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 Confirm(ctx context.Context, in *pb.ConfirmRequest) (reply *pb.ConfirmReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	var (
		logisFee     int64 = 0
		couponAmount int64 = 0
		summary            = new(models.OrderSummary)
		coupon             = new(models.OrderCoupon)
	)

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

	if in.AddressIdentity != "" {
		/*
			err = impl.DBService.Where("id=?", in.AddressId).First(&address).Error
			if err == nil {
				summary.Address = address.Detail
				summary.County = address.Country
				summary.Province = address.Province
				summary.City = address.City
				summary.Area = address.Area
				summary.Contact = address.Contact
				summary.Phone = address.Phone
				logisFee = GetLogisticsFee(summary.TotalPrice, address.Province)
			}
		*/
	}
	if logisFee > 0 {
		summary.TotalPrice = summary.TotalPrice + logisFee
	}

	if in.CouponIdentity != "" {
		err = impl.DBService.Where("identity=?", in.CouponIdentity).First(&coupon).Error
		if err == nil {
			if coupon.Status == 2 {
				impl.DBService.Model(&models.OrderCoupon{}).Where("identity=?", in.CouponIdentity).Update("status", 3)
				couponAmount = coupon.Amount
			} else {
				printer.Error(err.Error())
				return nil, errcode.ErrUnavailable
			}
		} else {
			printer.Error(err.Error())
			return nil, errcode.ErrRecordNotFound
		}
	}

	if couponAmount > 0 {
		summary.TotalPrice = summary.TotalPrice + couponAmount
	}

	summary.Status = 1

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

	return &pb.ConfirmReply{
		TotalPrice: summary.TotalPrice,
	}, nil
}
