package jd

import (
	"math"

	"git.rosy.net.cn/baseapi/platformapi/jdapi"
	"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"
)

func (p *PurchaseHandler) OnFinancialMsg(msg *jdapi.CallbackOrderMsg) (retVal *jdapi.CallbackResponse) {
	utils.CallFuncAsync(func() {
		retVal = p.onFinancialMsg(msg)
	})
	return retVal
}

// 京东正向/退款订单类型处理--存储
func (p *PurchaseHandler) onFinancialMsg(msg *jdapi.CallbackOrderMsg) (retVal *jdapi.CallbackResponse) {
	var err error
	a := getAPI(AppKey2OrgCode(msg.AppKey))
	// if msg.StatusID == jdapi.OrderStatusPayFinishedSettle || msg.StatusID == jdapi.OrderStatusTipChanged || msg.StatusID == jdapi.OrderStatusSwitch2SelfSettle { // 如果是正向单
	if msg.StatusID == jdapi.OrderStatusPayFinishedSettle || msg.StatusID == jdapi.OrderStatusTipChanged || msg.StatusID == jdapi.OrderStatusAdjustSettle || msg.StatusID == jdapi.OrderStatusSwitch2SelfSettle { // 如果是正向单
		order, err2 := partner.CurOrderManager.LoadOrder(msg.BillID, model.VendorIDJD)
		if err = err2; err == nil {
			orderData, err2 := a.QuerySingleOrder(msg.BillID)
			if err = err2; err == nil {
				orderFinancial, err2 := CurPurchaseHandler.OrderDetail2Financial(a, orderData, false, order)
				if err = err2; err == nil {
					if msg.StatusID == jdapi.OrderStatusPayFinishedSettle {
						err = partner.CurOrderManager.SaveOrderFinancialInfo(orderFinancial, partner.CreatedPeration)
					} else {
						err = partner.CurOrderManager.SaveOrderFinancialInfo(orderFinancial, partner.UpdatedPeration)
					}
				}
			}
		} else {
			err = nil
		}
	} else if msg.StatusID == jdapi.AfsServiceStateRefundSuccess || msg.StatusID == jdapi.AfsServiceStateReturnGoodsSuccess { // 如果是退款单
		orderData, err2 := a.GetAfsService(msg.BillID)
		if err = err2; err == nil {
			err = partner.CurOrderManager.SaveAfsOrderFinancialInfo(CurPurchaseHandler.AfsOrderDetail2Financial(orderData))
		}
	}
	return jdapi.Err2CallbackResponse(nil, "jd OnFinancialMsg") // todo 强制返回成功
}

// 处理京东正向订单信息
func (p *PurchaseHandler) OrderDetail2Financial(a *jdapi.API, orderData map[string]interface{}, isFromOrderDetail bool, order *model.GoodsOrder) (orderFinancial *model.OrderFinancial, err error) {
	orderFinancial = &model.OrderFinancial{
		VendorID:             model.VendorIDJD,
		VendorOrderID:        utils.Int64ToStr(utils.MustInterface2Int64(orderData["orderId"])),
		ReceivableFreight:    utils.MustInterface2Int64(orderData["orderReceivableFreight"]),
		FreightMoney:         utils.MustInterface2Int64(orderData["orderFreightMoney"]),
		ActualPayMoney:       utils.MustInterface2Int64(orderData["orderBuyerPayableMoney"]),
		DiscountMoney:        utils.MustInterface2Int64(orderData["orderDiscountMoney"]),
		DistanceFreightMoney: utils.MustInterface2Int64(orderData["merchantPaymentDistanceFreightMoney"]),
		FreightTipsMoney:     utils.MustInterface2Int64(orderData["tips"]),
		PointsDeductionMoney: utils.MustInterface2Int64(orderData["platformPointsDeductionMoney"]),
		// BoxMoney:               utils.MustInterface2Int64(orderData["packagingMoney"]), // 京东包装（塑料袋）由京东提供，相应钱款也归京东，不记录/记录之后优化算法
	}
	skus := order.Skus
	if skus != nil {
		for _, x := range skus {
			orderFinancial.ShopPriceMoney += x.ShopPrice * int64(x.Count)
		}
	}
	if orderData["product"] != nil {
		product := orderData["product"].([]interface{})
		for _, x := range product {
			xMap := x.(map[string]interface{})
			orderSkuFinancial := &model.OrderSkuFinancial{
				VendorID:      orderFinancial.VendorID,
				VendorOrderID: orderFinancial.VendorOrderID,
				// OrderFinancialID: orderFinancial.VendorOrderID,
				// ConfirmTime:      utils.Str2Time(utils.Interface2String(orderData["orderStartTime"])),
				VendorStoreID: utils.Interface2String(orderData["deliveryStationNo"]),
				StoreID:       int(utils.Str2Int64WithDefault(utils.Interface2String(orderData["deliveryStationNoIsv"]), 0)),
				JxStoreID:     order.JxStoreID,
				VendorSkuID:   utils.Int64ToStr(utils.MustInterface2Int64(xMap["skuId"])),
				// SkuID:             int(utils.Str2Int64(utils.Interface2String(xMap["skuIdIsv"]))),
				PromotionType: int(utils.MustInterface2Int64(xMap["promotionType"])),
				Name:          utils.Interface2String(xMap["skuName"]),
				ShopPrice:     utils.MustInterface2Int64(xMap["skuStorePrice"]),
				SalePrice:     utils.MustInterface2Int64(xMap["skuJdPrice"]),
				Count:         int(utils.MustInterface2Int64(xMap["skuCount"])),
				IsAfsOrder:    0,
				// MealBoxMoney:      utils.MustInterface2Int64(xMap["canteenMoney"]), // 京东的目前不考虑结算餐盒费，因为都归京东所有
			}

			// PromotionType 是一个关键数据，可能某商品活动限购，用户超出限购数量，超出部分不享受优惠，那么除了要在活动表根据skuId,活动起止日期，活动城市来查询，还需要判断活动类型PromotionType
			// 平台/京西单条sku补贴金额，应该去京西后台活动库去取，活动里针对单条SKU，如果京东/京西有补贴，应该有记录
			// orderSkuFinancial.PmSubsidyMoneyForSku =
			// orderSkuFinancial.JxSubsidyMoneyForSku =
			// orderFinancial.JxSubsidyMoneyToSku += orderSkuFinancial.JxSubsidyMoneyForSku
			// orderFinancial.JxSubsidyMoney += orderSkuFinancial.JxSubsidyMoneyForSku
			orderFinancial.SalePriceMoney += orderSkuFinancial.SalePrice * int64(orderSkuFinancial.Count)
			orderSkuFinancial.SkuID = int(utils.Str2Int64WithDefault(utils.Interface2String(xMap["skuIdIsv"]), 0))
			if orderSkuFinancial.SkuID > math.MaxInt32 {
				orderSkuFinancial.SkuID = orderSkuFinancial.JxSkuID
			}
			orderFinancial.Skus = append(orderFinancial.Skus, orderSkuFinancial)
		}
	}
	// orderFinancial.DeliveryConfirmTime = utils.Str2TimeWithDefault(utils.Interface2String(orderData["deliveryConfirmTime"]), utils.DefaultTimeValue)
	if int(utils.Str2Int64WithDefault(utils.Interface2String(orderData["deliveryCarrierNo"]), 0)) == jdapi.CarrierNoSelfDelivery {
		// 如果为自配送，自配送补贴=订单初始运费，远距离费=0
		orderFinancial.SelfDeliveryDiscountMoney = utils.MustInterface2Int64(orderData["orderReceivableFreight"])
		orderFinancial.DistanceFreightMoney = 0
		orderFinancial.FreightTipsMoney = 0
		// 通过本地数据库去取是否转美团/达达，并计算运费
		// wayBill, err2 := partner.CurOrderManager.LoadWaybill(orderFinancial.VendorOrderID, orderFinancial.VendorID)
		// if err = err2; err == nil {
		// 	orderFinancial.JxFreightMoney = wayBill.DesiredFee
		// }
	}
	if orderData["discount"] != nil {
		discount := orderData["discount"].([]interface{})
		for _, x := range discount {
			xMap := x.(map[string]interface{})
			discountPrice := utils.MustInterface2Int64(xMap["discountPrice"])
			discountType := int(utils.MustInterface2Int64(xMap["discountType"]))
			if discountType == jdapi.FreightDiscountTypeByShop {
				orderFinancial.FreightDiscountMoney = discountPrice
			} else if discountType == jdapi.FreightDiscountTypeByVip || discountType == jdapi.FreightDiscountTypeByActivity {
				orderFinancial.PmFreightDiscountMoney = discountPrice
			} else if discountType == jdapi.FreightDiscountTypeByCoupons {
				if xMap["platPayMoney"] == nil {
					orderFinancial.PmFreightDiscountMoney = discountPrice
				} else {
					orderFinancial.PmFreightDiscountMoney = int64(utils.MustInterface2Float64(xMap["platPayMoney"]))
					orderFinancial.FreightDiscountMoney = discountPrice - orderFinancial.PmFreightDiscountMoney
				}
			}
			orderFinancial.TotalDiscountMoney += discountPrice
			if xMap["orderShareRatioData"] != nil {
				orderShareRatioData, _ := utils.HTTPBody2Values([]byte(utils.Interface2String(xMap["orderShareRatioData"])), false)
				if promotionID := orderShareRatioData.Get("promotionId"); promotionID != "" {
					activity := &model.OrderDiscountFinancial{
						VendorID:         orderFinancial.VendorID,
						VendorOrderID:    orderFinancial.VendorOrderID,
						VendorActivityID: promotionID, // utils.Interface2String(orderShareRatioData["promotionId"][0]),
						Type:             utils.Int64ToStr(int64(discountType)),
						// ActivityName:     utils.Interface2String(xMap["discountName"]),
						// ActivityMoney:    discountPrice,
						// Remark:           utils.Interface2String(xMap["orderShareRatioData"]),
					}
					orderFinancial.Discounts = append(orderFinancial.Discounts, activity)
					// 通过活动Id去取，京西活动补贴
					// orderFinancial.JxSubsidyMoney +=
				}
			}
		}
	}
	order1, err2 := a.OrderShoudSettlementService(orderFinancial.VendorOrderID)
	if err = err2; err == nil {
		orderFinancial.ShopMoney = utils.Interface2Int64WithDefault(order1["settlementAmount"], 0)
		orderFinancial.PmMoney += utils.Interface2Int64WithDefault(order1["goodsCommission"], 0)
		orderFinancial.PmMoney += utils.Interface2Int64WithDefault(order1["freightCommission"], 0)
		orderFinancial.PmMoney += utils.Interface2Int64WithDefault(order1["packageCommission"], 0)
		orderFinancial.PmMoney += utils.Interface2Int64WithDefault(order1["guaranteedCommission"], 0)
		orderFinancial.PmSkuSubsidyMoney = utils.Interface2Int64WithDefault(order1["platSkuGoodsDiscountMoney"], 0)
		orderFinancial.PmSubsidyMoney = utils.Interface2Int64WithDefault(order1["platOrderGoodsDiscountMoney"], 0) + orderFinancial.PmSkuSubsidyMoney
	}
	return orderFinancial, err
}

// 处理京东售后订单结账信息
func (p *PurchaseHandler) AfsOrderDetail2Financial(orderData map[string]interface{}) (afsOrder *model.AfsOrder) {
	afsOrder = &model.AfsOrder{
		VendorID:              model.VendorIDJD,
		AfsOrderID:            utils.Interface2String(orderData["afsServiceOrder"]),
		VendorOrderID:         utils.Interface2String(orderData["orderId"]),
		VendorStoreID:         utils.Interface2String(orderData["stationId"]),
		StoreID:               int(utils.Str2Int64WithDefault(utils.Interface2String(orderData["stationNumOutSystem"]), 0)),
		AfsCreatedAt:          utils.Timestamp2Time(utils.MustInterface2Int64(orderData["updateTime"].(map[string]interface{})["time"]) / 1000),
		FreightUserMoney:      utils.MustInterface2Int64(orderData["orderFreightMoney"]),
		AfsFreightMoney:       utils.MustInterface2Int64(orderData["afsFreight"]),
		BoxMoney:              utils.MustInterface2Int64(orderData["packagingMoney"]),
		TongchengFreightMoney: utils.MustInterface2Int64(orderData["tongchengFreightMoney"]),
		SkuBoxMoney:           utils.MustInterface2Int64(orderData["mealBoxMoney"]),
		VendorOrgCode:         utils.Interface2String(orderData["venderId"]),
	}
	order, err := partner.CurOrderManager.LoadOrder(afsOrder.VendorOrderID, afsOrder.VendorID)
	if err == nil {
		afsOrder.JxStoreID = order.JxStoreID
	} else {
		globals.SugarLogger.Warnf("jd AfsOrderDetail2Financial, afsOrderID:%s is not found from partner.CurOrderManager.LoadOrder", afsOrder.VendorOrderID)
	}
	if orderData["afsDetailList"] != nil {
		refundDetail := orderData["afsDetailList"].([]interface{})
		for _, x := range refundDetail {
			xMap := x.(map[string]interface{})
			orderSku := &model.OrderSkuFinancial{
				VendorID:      model.VendorIDJD,
				AfsOrderID:    afsOrder.AfsOrderID,
				VendorOrderID: afsOrder.VendorOrderID,
				VendorStoreID: afsOrder.VendorStoreID,
				StoreID:       afsOrder.StoreID,
				// ConfirmTime:          afsOrder.AfsCreateAt,
				VendorSkuID:       utils.Int64ToStr(utils.MustInterface2Int64(xMap["wareId"])),
				SkuID:             int(utils.Str2Int64WithDefault(utils.Interface2String(xMap["skuIdIsv"]), 0)),
				Name:              utils.Interface2String(xMap["wareName"]),
				UserMoney:         utils.MustInterface2Int64(xMap["afsMoney"]),
				PmSkuSubsidyMoney: utils.MustInterface2Int64(xMap["platPayMoney"]),
				IsAfsOrder:        1,
			}
			afsOrder.PmSkuSubsidyMoney += orderSku.PmSkuSubsidyMoney
			orderSku.PmSubsidyMoney += orderSku.PmSkuSubsidyMoney

			if xMap["afsSkuDiscountList"] != nil {
				afsSkuDiscountList := xMap["afsSkuDiscountList"].([]interface{})
				for _, y := range afsSkuDiscountList {
					orderSku.PmSubsidyMoney += utils.MustInterface2Int64(y.(map[string]interface{})["platPayMoney"])
				}
			}

			afsOrder.SkuUserMoney += orderSku.UserMoney
			afsOrder.PmSubsidyMoney += orderSku.PmSubsidyMoney
			afsOrder.Skus = append(afsOrder.Skus, orderSku)
		}
		if len(refundDetail) <= 0 {
			globals.SugarLogger.Warnf("jd AfsOrderDetail2Financial, orderID:%s have no refund_detail", afsOrder.VendorOrderID)
		}
	} else {
		globals.SugarLogger.Warnf("jd AfsOrderDetail2Financial, orderID:% refund_detail is nil", afsOrder.VendorOrderID)
	}
	return afsOrder
}

func (p *PurchaseHandler) OnOrderDetail(a *jdapi.API, orderDetail map[string]interface{}, peration string) (err error) {
	order, err := partner.CurOrderManager.LoadOrder(utils.Int64ToStr(utils.MustInterface2Int64(orderDetail["orderId"])), model.VendorIDJD)
	if err == nil {
		orderFinancial, err2 := CurPurchaseHandler.OrderDetail2Financial(a, orderDetail, true, order)
		if err = err2; err == nil {
			err = partner.CurOrderManager.SaveOrderFinancialInfo(orderFinancial, peration)
		}
	}
	return err
}
