package partner

import (
	"fmt"

	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
)

const (
	WaybillFeeErrCodeCourierNotOpen      = 1  //配送门店没有启用
	WaybillFeeErrCodeCourierNotSupported = 2  //配送门店不被系统支持
	WaybillFeeErrCodeCourierForbidden    = 3  //配送门店内部禁用
	WaybillFeeErrCodeCourierOthers       = 10 //其它错误
)

type WaybillFeeInfo struct {
	ErrCode        int            `json:"errCode"`
	ErrStr         string         `json:"errStr"`
	RefDeliveryFee int64          `json:"refDeliveryFee"` // 无用，待删除
	RefAddFee      int64          `json:"refAddFee"`      // 无用，待删除
	DeliveryFee    int64          `json:"deliveryFee"`
	TimeoutSecond  int            `json:"timeoutSecond"` // 系统会自动发运单的倒计时
	Waybill        *model.Waybill `json:"waybill"`
}

type CreateWaybillPolicyFunc func(refDeliveryFee, refAddFee, deliveryFee int64) (errStr string)

type IDeliveryPlatformHandler interface {
	GetVendorID() int

	CreateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (vendorStoreID string, status int, err error)
	GetStore(ctx *jxcontext.Context, storeID int, vendorStoreID string) (storeDetail *dao.StoreDetail2, err error)
	IsErrStoreNotExist(err error) bool
	IsErrStoreExist(err error) bool

	CreateWaybill(order *model.GoodsOrder, maxDeliveryFee int64) (bill *model.Waybill, err error)
	CancelWaybill(bill *model.Waybill, cancelReasonID int, cancelReason string) (err error)
	GetWaybillFee(order *model.GoodsOrder) (deliveryFeeInfo *WaybillFeeInfo, err error)
	//投诉骑手
	ComplaintRider(bill *model.Waybill, resonID int, resonContent string) (err error)
}

type IDeliveryUpdateStoreHandler interface {
	UpdateStore(ctx *jxcontext.Context, storeDetail *dao.StoreDetail2) (err error)
}

type DeliveryPlatformHandlerInfo struct {
	Handler           IDeliveryPlatformHandler
	Use4CreateWaybill bool
}

var (
	DeliveryPlatformHandlers map[int]*DeliveryPlatformHandlerInfo
	UseableDeliveryVendorIDs []int
)

func init() {
	DeliveryPlatformHandlers = make(map[int]*DeliveryPlatformHandlerInfo)
}

func RegisterDeliveryPlatform(handler IDeliveryPlatformHandler, isUse4CreateWaybill bool) {
	vendorID := handler.GetVendorID()
	if !(model.IsDeliveryVendorExist(vendorID)) {
		panic(fmt.Sprintf("delivery vendor:%d is illegal", vendorID))
	}
	if _, ok := DeliveryPlatformHandlers[vendorID]; ok {
		panic(fmt.Sprintf("delivery vendor:%d, already exists", vendorID))
	}
	DeliveryPlatformHandlers[vendorID] = &DeliveryPlatformHandlerInfo{
		Handler:           handler,
		Use4CreateWaybill: isUse4CreateWaybill,
	}
	UseableDeliveryVendorIDs = append(UseableDeliveryVendorIDs, vendorID)
}

func GetDeliveryPlatformFromVendorID(vendorID int) *DeliveryPlatformHandlerInfo {
	return DeliveryPlatformHandlers[vendorID]
}
