package elm

import (
	"fmt"

	"git.rosy.net.cn/baseapi/platformapi/elmapi"
	"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"
	"git.rosy.net.cn/jx-callback/globals/api"
)

func (c *PurchaseHandler) OnWaybillStatusMsg(msg *elmapi.CallbackWaybillStatusMsg) (retVal *elmapi.CallbackResponse) {
	jxutils.CallMsgHandler(func() {
		retVal = c.onWaybillStatusMsg(msg)
	}, jxutils.ComposeUniversalOrderID(msg.OrderID, model.VendorIDELM))
	return retVal
}

func (c *PurchaseHandler) onWaybillStatusMsg(msg *elmapi.CallbackWaybillStatusMsg) (retVal *elmapi.CallbackResponse) {
	order := c.callbackMsg2Waybill(msg)
	if msg.MsgType == elmapi.MsgTypeWaybillWait4Courier { //MsgTypeWaybillWait4Courier事件与JD的新运单事件的时间机制更相似
		order.Status = model.WaybillStatusNew
	} else if msg.MsgType == elmapi.MsgTypeWaybillPickingUp {
		if result, err := api.ElmAPI.GetOrder(msg.OrderID); err == nil {
			order.DesiredFee = jxutils.StandardPrice2Int(utils.Interface2Float64WithDefault(result["deliverFee"], 0.0) +
				utils.Interface2Float64WithDefault(result["vipDeliveryFeeDiscount"], 0.0))
		}
		order.Status = model.WaybillStatusAccepted
	} else if msg.MsgType == elmapi.MsgTypeWaybillCourierArrived {
		order.Status = model.WaybillStatusCourierArrived
	} else if msg.MsgType == elmapi.MsgTypeWaybillDelivering {
		order.Status = model.WaybillStatusDelivering
	} else if msg.MsgType == elmapi.MsgTypeWaybillDelivered {
		order.Status = model.WaybillStatusDelivered
	} else if msg.MsgType >= elmapi.MsgTypeWaybillCanceledByMerchant && msg.MsgType <= elmapi.MsgTypeWaybillCanceledBySystem {
		order.Status = model.WaybillStatusCanceled
	} else if msg.MsgType >= elmapi.MsgTypeWaybillFailedCallLate &&
		msg.MsgType <= elmapi.MsgTypeRejectedSystemError &&
		msg.MsgType != elmapi.MsgTypeDeiverBySelf {
		order.Status = model.WaybillStatusFailed
	} else {
		// MsgTypeWaybillWait4DeliveryVendor
		// MsgTypeDeiverBySelf
		order.Status = model.WaybillStatusUnknown
	}
	return elmapi.Err2CallbackResponse(partner.CurOrderManager.OnWaybillStatusChanged(order), order.VendorStatus)
}

func (c *PurchaseHandler) callbackMsg2Waybill(msg *elmapi.CallbackWaybillStatusMsg) (retVal *model.Waybill) {
	retVal = &model.Waybill{
		VendorOrderID:   msg.OrderID,
		OrderVendorID:   model.VendorIDELM,
		VendorWaybillID: msg.OrderID,
		WaybillVendorID: model.VendorIDELM,
		CourierName:     msg.Name,
		CourierMobile:   msg.Phone,
		VendorStatus:    c.composeState(msg.State, msg.SubState, msg.MsgType),
		StatusTime:      utils.Timestamp2Time(msg.UpdateAt / 1000),
	}
	return retVal
}

func (c *PurchaseHandler) composeState(state, subState string, msgType int) string {
	return fmt.Sprintf("%s-%d", state, msgType)
}
