package ebai

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

func (p *PurchaseHandler) OnFinancialMsg(msg *ebaiapi.CallbackMsg) (response *ebaiapi.CallbackResponse) {
	utils.CallFuncAsync(func() {
		response = p.onFinancialMsg(msg)
	})
	return response
}

// 存储饿百退款订单结账信息
func (p *PurchaseHandler) onFinancialMsg(msg *ebaiapi.CallbackMsg) (response *ebaiapi.CallbackResponse) {
	var err error
	if msg.Cmd == ebaiapi.CmdOrderPartRefund { // 部分退款处理
		if int(utils.MustInterface2Int64(msg.Body["status"])) == ebaiapi.OrderPartRefundSuccess {
			// 获取到部分退款订单id
			afsOrderID := GetOrderIDFromMsg(msg)
			// 处理部分退款信息
			orderData, err2 := api.EbaiAPI.OrderPartRefundGet(afsOrderID)
			if err = err2; err == nil {
				afsOrder := CurPurchaseHandler.AfsOrderDetail2Financial(orderData)
				err = partner.CurOrderManager.SaveAfsOrderFinancialInfo(afsOrder)
			}
		}
	} else if msg.Cmd == ebaiapi.CmdOrderReversePush {
		if int(utils.MustInterface2Int64(msg.Body["refund_status"])) == ebaiapi.OrderPartRefundSuccess {
			// 获取到部分退款订单id
			afsOrderID := GetOrderIDFromMsg(msg)
			// 处理部分退款信息
			orderData, err2 := api.EbaiAPI.OrderPartRefundGet(afsOrderID)
			if err = err2; err == nil {
				afsOrder := CurPurchaseHandler.AfsOrderDetail2Financial(orderData)
				err = partner.CurOrderManager.SaveAfsOrderFinancialInfo(afsOrder)
			}
		}
	} else if msg.Cmd == ebaiapi.CmdOrderUserCancel { // 全额退款处理
		messageType := int(utils.MustInterface2Int64(msg.Body["type"]))
		if int(utils.MustInterface2Int64(msg.Body["cancel_type"])) == ebaiapi.OrderUserCancelTypeAfterSale &&
			(messageType == ebaiapi.OrderUserCancelCSAgreed || messageType == ebaiapi.OrderUserCancelMerchantAgreed) {
			afsOrderID := GetOrderIDFromMsg(msg)
			// 获得退款订单ID，去本地数据库拿？饿百消息推送只给了订单号，但是没有查询全额退款的接口，只有部分退款才可以查询
			orderFinancial, err := partner.CurOrderManager.LoadOrderFinancial(afsOrderID, model.VendorIDEBAI)
			if err == nil {
				err = partner.CurOrderManager.SaveAfsOrderFinancialInfo(CurPurchaseHandler.OrderFinancialDetail2Refund(orderFinancial, msg))
			} else {
				globals.SugarLogger.Warnf("ebai OnFinancialMsg, afsOrderID:%s is not found from partner.CurOrderManager.LoadOrderFinancial", afsOrderID)
			}
		}
	} else if msg.Cmd == ebaiapi.CmdOrderDeliveryStatus { // 转自送调整
		if utils.Int64ToStr(utils.MustInterface2Int64(msg.Body["status"])) == ebaiapi.WaybillStatusSelfDelivery {
			vendorOrderID := GetOrderIDFromMsg(msg)
			orderMap, err := api.EbaiAPI.OrderGet(vendorOrderID)
			if err == nil {
				err = CurPurchaseHandler.OnOrderDetail(orderMap, partner.UpdatedPeration)
			}
			// 部分订单在隐私条约的保护下会隐藏用户收货地址,转自送成功自后才可以获取到正确的地址.
			userMap := orderMap["user"].(map[string]interface{})
			order, _ := partner.CurOrderManager.LoadOrder(vendorOrderID, model.VendorIDEBAI)
			order.ConsigneeAddress = utils.Interface2String(userMap["address"])
			partner.CurOrderManager.UpdateOrderFields(order, []string{"ConsigneeAddress"})
		}
	}
	return api.EbaiAPI.Err2CallbackResponse(msg.Cmd, err, msg.Cmd)
}

func (p *PurchaseHandler) OrderFinancialDetail2Refund(orderFinancial *model.OrderFinancial, msg *ebaiapi.CallbackMsg) (afsOrder *model.AfsOrder) {
	afsOrder = &model.AfsOrder{
		VendorID:      model.VendorIDEBAI,
		AfsOrderID:    GetOrderIDFromMsg(msg),
		VendorOrderID: GetOrderIDFromMsg(msg),
		AfsCreatedAt:  utils.Timestamp2Time(msg.Timestamp),
		// BoxMoney:         orderFinancial.BoxMoney, // 饿百的餐盒费已经拆分到单条Sku里面，退款时直接计算用户支付sku金额就好了
		// SkuBoxMoney:      orderFinancial.SkuBoxMoney,
		FreightUserMoney: orderFinancial.FreightMoney,
		SkuUserMoney:     orderFinancial.ActualPayMoney - orderFinancial.FreightMoney,
		PmSubsidyMoney:   orderFinancial.PmSubsidyMoney,
	}
	// if msg.Body["timestamp"] != nil {
	// 	afsOrder.AfsCreateAt = utils.Timestamp2Time(utils.Str2Int64(utils.Interface2String(msg.Body["timestamp"])))
	// } else {
	// 	afsOrder.AfsCreateAt = time.Now()
	// }
	order, err := partner.CurOrderManager.LoadOrder(afsOrder.VendorOrderID, afsOrder.VendorID)
	if err == nil {
		afsOrder.JxStoreID = order.JxStoreID
		afsOrder.VendorStoreID = order.VendorStoreID
		afsOrder.StoreID = order.StoreID
	} else {
		globals.SugarLogger.Warnf("ebai AfsOrderDetail2Financial, afsOrderID:%s is not found from partner.CurOrderManager.LoadOrder", afsOrder.VendorOrderID)
		err = nil
	}
	for _, sku := range orderFinancial.Skus {
		orderSkuFinancial := &model.OrderSkuFinancial{
			VendorID:         sku.VendorID,
			VendorOrderID:    sku.VendorOrderID,
			VendorSubOrderID: sku.VendorSubOrderID,
			AfsOrderID:       sku.VendorOrderID,
			// ConfirmTime:      afsOrder.AfsCreateAt,
			VendorStoreID:  afsOrder.VendorStoreID,
			StoreID:        afsOrder.StoreID,
			JxStoreID:      afsOrder.JxStoreID,
			VendorSkuID:    sku.VendorSkuID,
			SkuID:          sku.SkuID,
			PromotionType:  sku.PromotionType,
			Name:           sku.Name,
			ShopPrice:      sku.ShopPrice,
			SalePrice:      sku.SalePrice,
			Count:          sku.Count,
			SkuBoxMoney:    sku.SkuBoxMoney,
			UserMoney:      sku.UserMoney,
			PmSubsidyMoney: sku.PmSubsidyMoney,
			IsAfsOrder:     1,
		}
		afsOrder.Skus = append(afsOrder.Skus, orderSkuFinancial)
	}
	return afsOrder
}

func (p *PurchaseHandler) AfsOrderDetail2Financial(orderData map[string]interface{}) (afsOrder *model.AfsOrder) {
	afsOrder = &model.AfsOrder{
		VendorID:      model.VendorIDEBAI,
		AfsOrderID:    GetAfsIDFromMap(orderData),
		VendorOrderID: GetOrderIDFromMap(orderData),
	}
	order, err := partner.CurOrderManager.LoadOrder(afsOrder.VendorOrderID, afsOrder.VendorID)
	if err == nil {
		afsOrder.JxStoreID = order.JxStoreID
	} else {
		globals.SugarLogger.Warnf("ebai AfsOrderDetail2Financial, afsOrderID:%s is not found from partner.CurOrderManager.LoadOrder", afsOrder.VendorOrderID)
		err = nil
	}
	// 部分退款订单，第三方平台佣金会变化，金额为 orderData["commission"]，是否将该字段更新到正向订单结算表中
	// 不作更新的话，商户可以得到的钱会少几毛钱，最终京西受益
	// 如果要更新，总佣金，京西佣金是否都要更新，而其它一系列连锁反应，是否需要考虑更新
	// 或者换个思路，不考虑变更之前的正向订单，在佣金上入手，退款金额减去佣金减少的部分
	orderFinancial, err := partner.CurOrderManager.LoadOrderFinancial(afsOrder.VendorOrderID, model.VendorIDEBAI)
	if err == nil {
		afsOrder.PmRefundMoney = orderFinancial.PmMoney - utils.MustInterface2Int64(orderData["commission_amount"])
	} else {
		// 此处应该报错
		err = nil
	}
	if orderData["reverse_order_list"] != nil {
		refundDetail := orderData["reverse_order_list"].([]interface{})
		refundSkuList := refundDetail[len(refundDetail)-1].(map[string]interface{})["sub_reverse_order_list"].([]interface{})
		for _, refundInfo := range refundSkuList {
			xMap := refundInfo.(map[string]interface{})
			if xMap["virtual_type"] == ebaiapi.OrderVirtualType {
				orderSkuFinancial := &model.OrderSkuFinancial{
					VendorID:         model.VendorIDEBAI,
					AfsOrderID:       afsOrder.AfsOrderID,
					VendorOrderID:    afsOrder.VendorOrderID,
					VendorSubOrderID: afsOrder.VendorOrderID2,
					// ConfirmTime:      getTimeFromInterface(xMap["apply_time"]),
					VendorSkuID: utils.Int64ToStr(utils.Interface2Int64WithDefault(xMap["platform_sku_id"], 0)),
					SkuID:       int(utils.Str2Int64WithDefault(utils.Interface2String(xMap["custom_sku_id"]), 0)),
					Name:        utils.Interface2String(xMap["sku_name"]),
					UserMoney:   utils.MustInterface2Int64(xMap["refund_user_amount"]),
					IsAfsOrder:  1,
				}
				orderSkuFinancial.PmSubsidyMoney = utils.Interface2Int64WithDefault(xMap["discount_detail"].(map[string]interface{})["platform_discount_amount"], 0) + utils.Interface2Int64WithDefault(xMap["discount_detail"].(map[string]interface{})["agent_discount_amount"], 0) + utils.Interface2Int64WithDefault(xMap["discount_detail"].(map[string]interface{})["user_discount_amount"], 0)
				afsOrder.Skus = append(afsOrder.Skus, orderSkuFinancial)
				afsOrder.SkuUserMoney += orderSkuFinancial.UserMoney
				afsOrder.PmSubsidyMoney += orderSkuFinancial.PmSubsidyMoney
			}
		}
		if len(refundDetail) > 0 {
			afsOrder.AfsCreatedAt = getTimeFromInterface(refundDetail[0].(map[string]interface{})["apply_time"])
		} else {
			globals.SugarLogger.Warnf("ebai AfsOrderDetail2Financial, orderID:%s have no refund_detail", afsOrder.VendorOrderID)
		}
	} else {
		globals.SugarLogger.Warnf("ebai AfsOrderDetail2Financial, orderID:% refund_detail is nil", afsOrder.VendorOrderID)
	}
	return afsOrder
}

// 存储饿百正向订单结账信息
func (p *PurchaseHandler) OnOrderDetail(result map[string]interface{}, operation string) (err error) {
	err = partner.CurOrderManager.SaveOrderFinancialInfo(p.OrderDetail2Financial(result), operation)
	return err
}

// func (p *PurchaseHandler) GetTrueEbaiOrder(result1 map[string]interface{}) (result2 map[string]interface{}) {
// 	order := result1["order"].(map[string]interface{})
// 	if utils.MustInterface2Int64(order["down_flag"]) == 1 {
// 		result, err := api.EbaiAPI.OrderGet(GetOrderIDFromMap(order))
// 		if err == nil {
// 			return p.GetTrueEbaiOrder(result)
// 		}
// 	}
// 	return result1
// }

func (p *PurchaseHandler) OrderDetail2Financial(result map[string]interface{}) (orderFinancial *model.OrderFinancial) {
	orderFinancial = &model.OrderFinancial{
		VendorID: model.VendorIDEBAI,
	}
	order1 := result["order"].(map[string]interface{})
	orderFinancial.VendorOrderID = GetOrderIDFromMap(order1)
	orderFinancial.VendorOrderID2 = utils.Interface2String(order1["eleme_order_id"])
	// orderFinancial.DeliveryConfirmTime = getTimeFromInterface(order1["finished_time"])
	orderFinancial.TotalDiscountMoney = utils.MustInterface2Int64(order1["discount_fee"])
	orderFinancial.ReceivableFreight = utils.MustInterface2Int64(order1["send_fee"])
	orderFinancial.DownFlag = int8(utils.MustInterface2Int64(order1["down_flag"]))

	if int(getInt64FromInterface(order1["delivery_party"])) == ebaiapi.DeliveryPartyFengElmSelf {
		orderFinancial.SelfDeliveryDiscountMoney = orderFinancial.ReceivableFreight
		orderFinancial.DistanceFreightMoney = 0
		// 通过本地数据库去取是否转美团/达达，并计算运费
		// wayBill, err := partner.CurOrderManager.LoadWaybill(orderFinancial.VendorOrderID, orderFinancial.VendorID)
		// if err == nil {
		// 	orderFinancial.JxFreightMoney = wayBill.DesiredFee
		// }
	}
	orderFinancial.BoxMoney = utils.ForceInterface2Int64(order1["package_fee"])
	orderFinancial.ActualPayMoney = utils.ForceInterface2Int64(order1["user_fee"])
	orderFinancial.PmMoney = utils.ForceInterface2Int64(order1["commission"])
	orderFinancial.ShopMoney = utils.ForceInterface2Int64(order1["shop_fee"])
	order, err := partner.CurOrderManager.LoadOrder(orderFinancial.VendorOrderID, orderFinancial.VendorID)
	storeID := 0
	jxStoreID := 0
	if err == nil {
		storeID = order.StoreID
		jxStoreID = order.JxStoreID
		skus := order.Skus
		if skus != nil {
			for _, x := range skus {
				orderFinancial.ShopPriceMoney += x.ShopPrice * int64(x.Count)
			}
		}
	} else {
		globals.SugarLogger.Warnf("ebai OrderDetail2Financial, orderID:%s is not found from partner.CurOrderManager.LoadOrder", orderFinancial.VendorOrderID)
		err = nil
	}
	shop := result["shop"].(map[string]interface{})
	if result["products"] != nil {
		products := result["products"].([]interface{})
		for _, x := range products {
			for _, y := range x.([]interface{}) {
				product := y.(map[string]interface{})
				orderSkuFinancial := &model.OrderSkuFinancial{
					VendorID:      orderFinancial.VendorID,
					VendorOrderID: orderFinancial.VendorOrderID,
					// OrderFinancialID: orderFinancial.VendorOrderID,
					// ConfirmTime:      getTimeFromInterface(order1["create_time"]),
					VendorStoreID: utils.Interface2String(shop["baidu_shop_id"]),
					StoreID:       storeID,
					JxStoreID:     jxStoreID,
					VendorSkuID:   utils.Interface2String(product["baidu_product_id"]),
					SkuID:         int(utils.Str2Int64WithDefault(utils.Interface2String(product["custom_sku_id"]), 0)),
					Name:          utils.Interface2String(product["product_name"]),
					SalePrice:     utils.MustInterface2Int64(product["product_price"]),
					Count:         int(utils.MustInterface2Int64(product["product_amount"])),
					SkuBoxMoney:   utils.MustInterface2Int64(product["package_fee"]),
					IsAfsOrder:    0,
				}
				orderFinancial.Skus = append(orderFinancial.Skus, orderSkuFinancial)
				orderFinancial.SalePriceMoney += orderSkuFinancial.SalePrice * int64(orderSkuFinancial.Count)
				orderFinancial.SkuBoxMoney += orderSkuFinancial.SkuBoxMoney
				orderFinancial.BoxMoney -= orderSkuFinancial.SkuBoxMoney
			}
		}
	}
	if result["discount"] != nil {
		discount := result["discount"].([]interface{})
		for _, x := range discount {
			xMap := x.(map[string]interface{})
			discountPrice := utils.MustInterface2Int64(xMap["fee"])
			orderFinancial.DiscountMoney += discountPrice
			orderFinancial.PmSubsidyMoney += utils.MustInterface2Int64(xMap["baidu_rate"]) // 平台承担补贴
			activity := &model.OrderDiscountFinancial{
				VendorID:      orderFinancial.VendorID,
				VendorOrderID: orderFinancial.VendorOrderID,
				// ActivityName:     utils.Interface2String(xMap["desc"]),
				// ActivityMoney:    discountPrice,
				VendorActivityID: utils.Interface2String(xMap["activity_id"]),
				Type:             utils.Interface2String(xMap["type"]),
			}
			orderFinancial.Discounts = append(orderFinancial.Discounts, activity)
			// 通过活动Id去取，京西活动补贴
			// orderFinancial.JxSubsidyMoney +=
		}
	}
	orderFinancial.FreightDiscountMoney = orderFinancial.TotalDiscountMoney - orderFinancial.DiscountMoney
	return orderFinancial
}

func getInt64FromInterface(strOrNum interface{}) int64 {
	var resultNum int64
	if resultStr, ok := strOrNum.(string); ok {
		resultNum = utils.Str2Int64WithDefault(resultStr, 0)
	} else {
		resultNum = utils.Interface2Int64WithDefault(strOrNum, 0)
	}
	return resultNum
}
