package ebai

import (
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
	"time"

	"git.rosy.net.cn/baseapi/platformapi/ebaiapi"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals/api"
)

const (
	timeout4WaybillCancel = 10 * time.Minute // 饿百发送运单取消消息10分钟后，如果没有转自送，就要取消订单，且不再发送订单取消消息
)

var (
	VendorWaybillStatus2StatusMap = map[string]int{
		ebaiapi.WaybillStatusNew:             model.WaybillStatusUnknown,
		ebaiapi.WaybillStatusRequestDelivery: model.WaybillStatusUnknown,
		ebaiapi.WaybillStatusWait4Courier:    model.WaybillStatusNew,
		ebaiapi.WaybillStatusCourierAccepted: model.WaybillStatusAccepted,
		ebaiapi.WaybillStatusCourierPickedup: model.WaybillStatusDelivering,
		ebaiapi.WaybillStatusDeliveryCancled: model.WaybillStatusCanceled,
		ebaiapi.WaybillStatusFinished:        model.WaybillStatusDelivered,
		// ebaiapi.WaybillStatusExceptional:      model.WaybillStatusCanceled, // 饿百的配送异常不应该当成取消来处理，比如：1568651453228834871
		ebaiapi.WaybillStatusSelfDelivery:     model.WaybillStatusUnknown,
		ebaiapi.WaybillStatusDontDeliver:      model.WaybillStatusCanceled,
		ebaiapi.WaybillStatusDeliveryRejected: model.WaybillStatusCanceled,
		ebaiapi.WaybillStatusCourierArrived:   model.WaybillStatusCourierArrived,
	}
)

func (p *PurchaseHandler) GetWaybillStatusFromVendorStatus(vendorStatus string) int {
	if status, ok := VendorWaybillStatus2StatusMap[vendorStatus]; ok {
		return status
	}
	return model.WaybillStatusUnknown
}

func (c *PurchaseHandler) onWaybillMsg(msg *ebaiapi.CallbackMsg) (retVal *ebaiapi.CallbackResponse) {
	order := c.callbackMsg2Waybill(msg)
	if order.Status == model.WaybillStatusNew || order.Status == model.WaybillStatusAccepted { // 饿百新运单事件要查询快递员信息，因为可能事件错序
		if result, err := api.EbaiAPI.OrderDeliveryGet(order.VendorOrderID); err != nil {
			return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, err, order.VendorOrderID)
		} else {
			order.CourierName = utils.Interface2String(result["name"])
			order.CourierMobile = utils.Interface2String(result["phone"])

		}
		//if order.Status == model.WaybillStatusNew {
		//	order2, _ := partner.CurOrderManager.LoadOrder(order.VendorOrderID, order.WaybillVendorID)
		//	if order2 != nil {
		//		if order2.Status == model.OrderStatusWaitAccepted {
		//			order2.Status = model.OrderStatusNew
		//			scheduler.CurrentScheduler.OnOrderNew(order2, false, false)
		//		}
		//	}
		//}
	} else if order.Status == model.WaybillStatusCanceled {
		utils.AfterFuncWithRecover(timeout4WaybillCancel, func() {
			if localOrder, err2 := partner.CurOrderManager.LoadOrder(order.VendorOrderID, model.VendorIDEBAI); err2 == nil {
				if localOrder.Status < model.OrderStatusEndBegin {
					c.trySyncCancelStatus(order.VendorOrderID)
				}
			}
		})
	} else if order.VendorStatus == ebaiapi.WaybillStatusSelfDelivery {
		result1, err1 := api.EbaiAPI.OrderGet(order.VendorOrderID)
		if err1 == nil {
			address := utils.Interface2String(result1["user"].(map[string]interface{})["address"])
			localOrder, _ := partner.CurOrderManager.LoadOrder(order.VendorOrderID, model.VendorIDEBAI)
			localOrder.ConsigneeAddress = address
			dao.UpdateEntity(dao.GetDB(), localOrder, "ConsigneeAddress")
		} else {
			globals.SugarLogger.Debugf("饿了么转自送解密用户配送地址,查询平台订单时错误:%v", err1)
		}

	}
	return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, partner.CurOrderManager.OnWaybillStatusChanged(order), order.VendorStatus)
}

func (c *PurchaseHandler) callbackMsg2Waybill(msg *ebaiapi.CallbackMsg) (retVal *model.Waybill) {
	vendorStatus := utils.Int64ToStr(utils.MustInterface2Int64(msg.Body["status"]))
	orderID := GetOrderIDFromMsg(msg)
	retVal = &model.Waybill{
		VendorOrderID:   orderID,
		OrderVendorID:   model.VendorIDEBAI,
		VendorWaybillID: orderID,
		WaybillVendorID: model.VendorIDEBAI,
		Status:          c.GetWaybillStatusFromVendorStatus(vendorStatus),
		VendorStatus:    vendorStatus,
		StatusTime:      utils.Timestamp2Time(msg.Timestamp),
		VendorOrgCode:   msg.Source,
	}
	return retVal
}
