package phpjx

import (
	"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 NotifyOrderStatusChanged(order *model.GoodsOrder, status int) (err error) {
	orderMsg := *order
	orderMsg.Status = status
	if err = jxAPI.NotifyOrderStatusChanged(&orderMsg); err == nil {
		postFakeMsg(orderMsg.VendorOrderID, orderMsg.Status)
	}
	return err
}

type Data4Neworder struct {
	model.GoodsOrder
	Skus []*model.OrderSku `json:"skus"`
}

func OnOrderMsg(msg *CallbackMsg) (retVal, errCode string, err error) {
	jxutils.CallMsgHandler(func() {
		retVal, errCode, err = onOrderMsg(msg)
	}, jxutils.ComposeUniversalOrderID(msg.ThingID, model.VendorIDJX))
	return retVal, errCode, err
}

func onOrderMsg(msg *CallbackMsg) (retVal, errCode string, err error) {
	subMsgType := int(utils.Str2Int64WithDefault(msg.SubMsgType, 0))
	if subMsgType == model.OrderStatusNew || subMsgType == model.OrderStatusAdjust {
		var order *Data4Neworder
		if err = utils.UnmarshalUseNumber([]byte(msg.Data), &order); err == nil {
			if order.VendorStatus == "" {
				order.VendorStatus = utils.Int2Str(order.Status)
			}
			retVal, errCode, err = onOrderNew(msg, subMsgType, order)
		}
	} else {
		status := callbackMsg2Status(msg)
		err = partner.CurOrderManager.OnOrderStatusChanged("", status)
	}
	return retVal, errCode, err
}

func callbackMsg2Status(msg *CallbackMsg) *model.OrderStatus {
	orderStatus := &model.OrderStatus{
		VendorOrderID:    msg.ThingID,
		VendorID:         model.VendorIDJX,
		OrderType:        model.OrderTypeOrder,
		RefVendorOrderID: msg.ThingID,
		RefVendorID:      model.VendorIDJX,
		VendorStatus:     msg.SubMsgType,
		Status:           int(utils.Str2Int64WithDefault(msg.SubMsgType, 0)),
		StatusTime:       utils.Timestamp2Time(msg.Timestamp),
		Remark:           "",
	}
	return orderStatus
}

func onOrderNew(msg *CallbackMsg, subMsgType int, order *Data4Neworder) (retVal, errCode string, err error) {
	order.StoreID = int(utils.Str2Int64WithDefault(order.VendorStoreID, 0))
	if order.DeliveryType == "" {
		order.DeliveryType = model.OrderDeliveryTypeStoreSelf
	}
	order.GoodsOrder.Skus = order.Skus
	order.VendorID = model.VendorIDJX
	order.Flag = model.OrderFlagMaskTempJX
	for _, v := range order.GoodsOrder.Skus {
		v.SkuID = int(utils.Str2Int64WithDefault(v.VendorSkuID, 0))
	}
	jxutils.RefreshOrderSkuRelated(&order.GoodsOrder)
	orderStatus := model.Order2Status(&order.GoodsOrder)
	if subMsgType == model.OrderStatusNew {
		err = partner.CurOrderManager.OnOrderNew(&order.GoodsOrder, orderStatus)
	} else if subMsgType == model.OrderStatusAdjust {
		err = partner.CurOrderManager.OnOrderAdjust(&order.GoodsOrder, orderStatus)
	}
	return retVal, errCode, err
}
