package jd

import (
	"git.rosy.net.cn/baseapi/platformapi/jdapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
)

func (c *PurchaseHandler) OnWaybillMsg(vendorOrgCode string, msg *jdapi.CallbackDeliveryStatusMsg) (retVal *jdapi.CallbackResponse) {
	jxutils.CallMsgHandler(func() {
		retVal = c.onWaybillMsg(vendorOrgCode, msg)
	}, jxutils.ComposeUniversalOrderID(msg.OrderID, model.VendorIDJD))
	return retVal
}

func (c *PurchaseHandler) onWaybillMsg(vendorOrgCode string, msg *jdapi.CallbackDeliveryStatusMsg) (retVal *jdapi.CallbackResponse) {
	order := c.callbackMsg2Waybill(msg)
	switch msg.DeliveryStatus {
	case jdapi.DeliveryStatusWait4Grap:
		order.Status = model.WaybillStatusNew
	case jdapi.DeliveryStatusAccepted, jdapi.DeliveryStatusCourierChaged: // 将更换配送员也当成接单消息
		// todo 性能问题，暂时取消调用
		// if result, err := getAPI(vendorOrgCode).QuerySingleOrder(msg.OrderID); err == nil {
		// 	// 默认配送费=订单应付运费(orderReceivableFreight)
		// 	//订单应付运费为未优惠前应付运费(满免优惠，运费优惠券，VIP免基础运费，用户小费)ps：用户小费是用户给配送员的小费
		// 	order.DesiredFee = utils.Interface2Int64WithDefault(result["orderReceivableFreight"], 0) +
		// 		utils.Interface2Int64WithDefault(result["merchantPaymentDistanceFreightMoney"], 0) +
		// 		utils.Interface2Int64WithDefault(result["tips"], 0)
		// }
		order.Status = model.WaybillStatusAccepted
	case jdapi.DeliveryStatusCourierCanceled:
		order.Status = model.WaybillStatusAcceptCanceled
	case jdapi.DeliveryStatusCourierArrived:
		order.Status = model.WaybillStatusCourierArrived
	case jdapi.DeliveryStatusFailedGetGoodsWaiting:
		order.Status = model.WaybillStatusApplyFailedGetGoods
	case jdapi.DeliveryStatusFailedGetGoodsRejected:
		order.Status = model.WaybillStatusRefuseFailedGetGoods
	case jdapi.DeliveryStatusFailedGetGoods:
		order.Status = model.WaybillStatusAgreeFailedGetGoods
	case jdapi.DeliveryStatusGotGoods:
		order.Status = model.WaybillStatusDelivering
	case jdapi.DeliveryStatusFailedDelivery:
		order.Status = model.WaybillStatusDeliverFailed
	case jdapi.DeliveryStatusFinished:
		order.Status = model.WaybillStatusDelivered
	default:
		order.Status = model.WaybillStatusUnknown
	}
	return jdapi.Err2CallbackResponse(partner.CurOrderManager.OnWaybillStatusChanged(order), order.VendorStatus)
}

func (c *PurchaseHandler) callbackMsg2Waybill(msg *jdapi.CallbackDeliveryStatusMsg) (retVal *model.Waybill) {
	retVal = &model.Waybill{
		VendorOrderID:   msg.OrderID,
		OrderVendorID:   model.VendorIDJD,
		VendorWaybillID: msg.OrderID,
		WaybillVendorID: model.VendorIDJD,
		CourierName:     msg.DeliveryManName,
		CourierMobile:   msg.DeliveryManPhone,
		VendorStatus:    msg.DeliveryStatus,
		StatusTime:      utils.Str2Time(msg.DeliveryStatusTime),
		Remark:          msg.Remark,

		VendorOrgCode: AppKey2OrgCode(msg.AppKey),
	}
	return retVal
}
