package tao_vegetable

import (
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	"net/url"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"
	domain591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/domain"
	"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"
)

const (
	PublicWelfareDonation = 1 // 美团公益捐款金额现阶段是每单一分钱
)

// 存储美团退款订单结账信息
func OnFinancialMsg(msg *mtwmapi.CallbackMsg) (err error) {
	if msg.Cmd == mtwmapi.MsgTypeOrderPartialRefund { // 部分退款处理
		orderData := msg.FormData
		if orderData.Get("notify_type") == mtwmapi.NotifyTypeSuccess {
			err = partner.CurOrderManager.SaveAfsOrderFinancialInfo(CurPurchaseHandler.AfsOrderDetail2Financial(orderData))
		}
	}
	if msg.Cmd == mtwmapi.MsgTypeOrderRefund { // todo 全额退款处理
		orderData := msg.FormData
		if orderData.Get("notify_type") == mtwmapi.NotifyTypeSuccess {
			afsOrderID := orderData.Get("order_id")
			orderFinancial, err := partner.CurOrderManager.LoadOrderFinancial(afsOrderID, model.VendorIDTaoVegetable)
			if err == nil {
				err = partner.CurOrderManager.SaveAfsOrderFinancialInfo(CurPurchaseHandler.OrderFinancialDetail2Refund(orderFinancial, orderData))
			} else {
				globals.SugarLogger.Warnf("mtwm OnFinancialMsg, afsOrderID:%s is not found from partner.CurOrderManager.LoadOrderFinancial", afsOrderID)
			}
		}
	}
	return err
}

func (p *PurchaseHandler) OrderFinancialDetail2Refund(orderFinancial *model.OrderFinancial, orderData url.Values) (afsOrder *model.AfsOrder) {
	afsOrder = &model.AfsOrder{
		VendorID:      model.VendorIDTaoVegetable,
		AfsOrderID:    orderData.Get("refund_id"),
		VendorOrderID: orderData.Get("order_id"),
		AfsCreatedAt:  utils.Timestamp2Time(utils.Str2Int64(orderData.Get("timestamp"))),
		// BoxMoney:         orderFinancial.BoxMoney,
		// SkuBoxMoney:      orderFinancial.SkuBoxMoney, // 美团的餐盒费已经拆到单条SKU里面去了,退款时直接计算用户支付sku金额就好了
		FreightUserMoney: orderFinancial.FreightMoney,
		SkuUserMoney:     orderFinancial.ActualPayMoney - orderFinancial.FreightMoney,
		PmSubsidyMoney:   orderFinancial.PmSubsidyMoney,
	}
	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("mtwm 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,
			// OrderFinancialID: 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,
			UserMoney:      sku.UserMoney,
			PmSubsidyMoney: sku.PmSubsidyMoney,
			IsAfsOrder:     1,
		}
		afsOrder.Skus = append(afsOrder.Skus, orderSkuFinancial)
	}
	return afsOrder
}

func (p *PurchaseHandler) AfsOrderDetail2Financial(orderData url.Values) (afsOrder *model.AfsOrder) {
	afsOrder = &model.AfsOrder{
		VendorID:      model.VendorIDTaoVegetable,
		AfsOrderID:    orderData.Get("order_id"),
		VendorOrderID: orderData.Get("order_id"),
		AfsCreatedAt:  utils.Timestamp2Time(utils.Str2Int64(orderData.Get("timestamp"))),
		RefundMoney:   jxutils.StandardPrice2Int(utils.Str2Float64(orderData.Get("money"))),
	}
	// if orderData.Get("timestamp") != "" {
	// 	afsOrder.AfsCreateAt = utils.Timestamp2Time(utils.Str2Int64(orderData.Get("timestamp")))
	// } else {
	// 	afsOrder.AfsCreateAt = time.Now()
	// }
	order, err := partner.CurOrderManager.LoadOrder(afsOrder.VendorOrderID, afsOrder.VendorID)
	if err == nil {
		afsOrder.JxStoreID = order.JxStoreID
	} else {
		globals.SugarLogger.Warnf("mtwm AfsOrderDetail2Financial, afsOrderID:%s is not found from partner.CurOrderManager.LoadOrder", afsOrder.VendorOrderID)
		err = nil
	}
	food := orderData.Get("food")
	var refundDetail []map[string]interface{}
	utils.UnmarshalUseNumber([]byte(food), &refundDetail)
	for _, xMap := range refundDetail {
		orderSkuFinancial := &model.OrderSkuFinancial{
			VendorID:         model.VendorIDTaoVegetable,
			AfsOrderID:       afsOrder.AfsOrderID,
			VendorOrderID:    afsOrder.VendorOrderID,
			VendorSubOrderID: afsOrder.VendorOrderID2,
			// ConfirmTime:      afsOrder.AfsCreateAt,
			VendorSkuID: utils.Interface2String(xMap["app_food_code"]),
			SkuID:       int(utils.Str2Int64WithDefault(utils.Interface2String(xMap["sku_id"]), 0)),
			Name:        utils.Interface2String(xMap["food_name"]),
			UserMoney:   jxutils.StandardPrice2Int(utils.MustInterface2Float64(xMap["refund_price"]))*utils.MustInterface2Int64(xMap["count"]) + jxutils.StandardPrice2Int(utils.MustInterface2Float64(xMap["box_price"]))*int64(utils.MustInterface2Float64(xMap["box_num"])),
			IsAfsOrder:  1,
		}
		afsOrder.Skus = append(afsOrder.Skus, orderSkuFinancial)
		afsOrder.SkuUserMoney += orderSkuFinancial.UserMoney
		// afsOrder.PmSubsidyMoney += orderSkuFinancial.PmSubsidyMoney // 美团只给了一个扣款金额，很尴尬、、
	}
	afsOrder.PmSubsidyMoney += afsOrder.RefundMoney - afsOrder.SkuUserMoney
	if len(refundDetail) <= 0 {
		globals.SugarLogger.Warnf("mtwm AfsOrderDetail2Financial, orderID:%s have no refund_detail", afsOrder.VendorOrderID)
	}
	return afsOrder
}

// 存储美团正向订单结账信息
func (p *PurchaseHandler) OnOrderDetail(result *domain591.AlibabaAelophyOrderGetOrderResponse, operation string) (err error) {
	err = partner.CurOrderManager.SaveOrderFinancialInfo(p.OrderDetail2Financial(result), operation)
	return err
}

func (p *PurchaseHandler) OrderDetail2Financial(result *domain591.AlibabaAelophyOrderGetOrderResponse) (orderFinancial *model.OrderFinancial) {
	orderFinancial = &model.OrderFinancial{
		VendorID:      model.VendorIDTaoVegetable,
		VendorOrderID: utils.Int64ToStr(*result.BizOrderId),
	}
	order, err := partner.CurOrderManager.LoadOrder(orderFinancial.VendorOrderID, orderFinancial.VendorID)
	jxStoreID := 0
	if err == nil {
		jxStoreID = order.JxStoreID
		if order.Skus != nil {
			for _, x := range order.Skus {
				orderFinancial.ShopPriceMoney += x.ShopPrice * int64(x.Count)
			}
		}
	} else {
		err = nil
	}

	// 订单
	for _, x := range *result.SubOrderResponseList {
		orderSkuFinancial := &model.OrderSkuFinancial{
			VendorID:         orderFinancial.VendorID,
			VendorOrderID:    orderFinancial.VendorOrderID,
			VendorSubOrderID: orderFinancial.VendorOrderID2,
			VendorStoreID:    *result.StoreId,
			StoreID:          0,
			JxStoreID:        jxStoreID,
			VendorSkuID:      *x.SkuCode,
			SkuID:            utils.Str2Int(*x.SkuCode),
			Name:             *x.SkuName,
			SalePrice:        *x.Price,
			Count:            utils.Float64TwoInt(*x.BuySaleQuantity),
			SkuBoxMoney:      0,
			IsAfsOrder:       0,
		}
		orderFinancial.Skus = append(orderFinancial.Skus, orderSkuFinancial)
		orderFinancial.SalePriceMoney += orderSkuFinancial.SalePrice * int64(orderSkuFinancial.Count)
		orderFinancial.SkuBoxMoney += orderSkuFinancial.SkuBoxMoney

		// 活动
		if x.Activitys != nil {
			for _, v := range *x.Activitys {
				activity := &model.OrderDiscountFinancial{
					VendorID:       orderFinancial.VendorID,
					VendorOrderID:  orderFinancial.VendorOrderID,
					VendorOrderID2: orderFinancial.VendorOrderID2,
				}
				if v.ChannelActivityId != nil {
					activity.VendorActivityID = *v.ChannelActivityId
					activity.Type = tao_vegetable.ActivityTypeChannel
				}
				if v.BizActivityId != nil {
					activity.VendorActivityID = *v.BizActivityId
					activity.Type = tao_vegetable.ActivityTypeBiz
				}
				if v.MerchantActivityId != nil {
					activity.VendorActivityID = *v.MerchantActivityId
					activity.Type = tao_vegetable.ActivityTypeMerchant
				}
				orderFinancial.Discounts = append(orderFinancial.Discounts, activity)
			}
		}
	}

	orderFinancial.ReceivableFreight = *result.PostFee
	orderFinancial.FreightMoney = 0
	orderFinancial.ActualPayMoney = *result.PayFee
	orderFinancial.PmMoney = 0                                                // 平台费
	orderFinancial.ShopMoney = 0                                              // 应结金额
	orderFinancial.TotalDiscountMoney = *result.DiscountFee                   // 订单优惠总金额
	orderFinancial.PmSubsidyMoney = *result.PostDiscountPlatformFee           // 平台活动补贴（订单主体活动补贴+订单单条sku补贴）1+
	orderFinancial.SelfDeliveryDiscountMoney = *result.SkuDiscountPlatformFee // 平台承担运费补贴（商家自送）+
	orderFinancial.DistanceFreightMoney = 0

	return orderFinancial
}
