package mtwm

import (
	"net/url"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"
	"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.VendorIDMTWM)
			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.VendorIDMTWM,
		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,
			// 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.VendorIDMTWM,
		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.VendorIDMTWM,
			AfsOrderID:    afsOrder.AfsOrderID,
			VendorOrderID: afsOrder.VendorOrderID,
			// 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 map[string]interface{}, operation string) (err error) {
	err = partner.CurOrderManager.SaveOrderFinancialInfo(p.OrderDetail2Financial(result), operation)
	return err
}

func (p *PurchaseHandler) OrderDetail2Financial(result map[string]interface{}) (orderFinancial *model.OrderFinancial) {
	orderFinancial = &model.OrderFinancial{
		VendorID:      model.VendorIDMTWM,
		VendorOrderID: utils.Int64ToStr(utils.MustInterface2Int64(result["order_id"])),
	}
	// orderFinancial.DeliveryConfirmTime = utils.Str2TimeWithDefault(utils.Interface2String(result["order_completed_time"]), utils.DefaultTimeValue)
	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
	}

	// 区分门店是否为报价门店
	// 报价门店商品如果京西系统存在则不管,不存在则获取平台上填写的进货价

	if result["package_bag_money"] != nil {
		orderFinancial.BoxMoney = utils.MustInterface2Int64(result["package_bag_money"])
	}
	detail := result["detail"]
	if detail != nil {
		var data []map[string]interface{}
		utils.UnmarshalUseNumber([]byte(utils.Interface2String(detail)), &data)
		for _, x := range data {
			orderSkuFinancial := &model.OrderSkuFinancial{
				VendorID:      orderFinancial.VendorID,
				VendorOrderID: orderFinancial.VendorOrderID,
				// OrderFinancialID: orderFinancial.VendorOrderID,
				// ConfirmTime:      utils.Str2TimeWithDefault(utils.Interface2String(result["ctime"]), utils.DefaultTimeValue),
				VendorStoreID: result["app_poi_code"].(string),
				StoreID:       0,
				JxStoreID:     jxStoreID,
				VendorSkuID:   utils.Interface2String(x["sku_id"]),
				SkuID:         int(utils.Str2Int64WithDefault(utils.Interface2String(x["sku_id"]), 0)),
				Name:          utils.Interface2String(x["food_name"]),
				SalePrice:     jxutils.StandardPrice2Int(utils.MustInterface2Float64(x["price"])),
				Count:         int(utils.MustInterface2Int64(x["quantity"])),
				SkuBoxMoney:   jxutils.StandardPrice2Int(utils.MustInterface2Float64(x["box_price"])) * jxutils.StandardPrice2Int(utils.MustInterface2Float64(x["box_num"])),
				IsAfsOrder:    0,
			}
			orderFinancial.Skus = append(orderFinancial.Skus, orderSkuFinancial)
			orderFinancial.SalePriceMoney += orderSkuFinancial.SalePrice * int64(orderSkuFinancial.Count)
			orderFinancial.SkuBoxMoney += orderSkuFinancial.SkuBoxMoney
		}
	} else {
		globals.SugarLogger.Warnf("mtwm OrderDetail2Financial, orderID:%s have no detail", orderFinancial.VendorOrderID)
	}
	extras := result["extras"]
	if extras != nil {
		var data []map[string]interface{}
		utils.UnmarshalUseNumber([]byte(utils.Interface2String(extras)), &data)
		for _, x := range data {
			if x["rider_fee"] == nil {
				activity := &model.OrderDiscountFinancial{
					VendorID:      orderFinancial.VendorID,
					VendorOrderID: orderFinancial.VendorOrderID,
					// ActivityName:     utils.Interface2String(x["remark"]),
					// ActivityMoney:    jxutils.StandardPrice2Int(utils.MustInterface2Float64(x["reduce_fee"])),
					// VendorActivityID: utils.Int64ToStr(utils.MustInterface2Int64(x["act_detail_id"])),
				}
				if x["act_detail_id"] != nil { // 容错处理
					activity.VendorActivityID = utils.Int64ToStr(utils.MustInterface2Int64(x["act_detail_id"]))
					orderFinancial.Discounts = append(orderFinancial.Discounts, activity)
				}
				// 通过活动Id去取，京西活动补贴
				// orderFinancial.JxSubsidyMoney +=
			}
		}
	}
	poiReceiveDetail := result["poi_receive_detail"]
	if poiReceiveDetail != nil {
		var data map[string]interface{}
		utils.UnmarshalUseNumber([]byte(utils.Interface2String(poiReceiveDetail)), &data)
		orderFinancial.ReceivableFreight = utils.MustInterface2Int64(data["logisticsFee"])
		orderFinancial.FreightMoney = utils.MustInterface2Int64(data["logisticsFee"])
		orderFinancial.ActualPayMoney = utils.MustInterface2Int64(data["onlinePayment"])
		orderFinancial.PmMoney = utils.MustInterface2Int64(data["foodShareFeeChargeByPoi"])
		orderFinancial.ShopMoney = utils.MustInterface2Int64(data["wmPoiReceiveCent"])
		for _, x := range data["actOrderChargeByMt"].([]interface{}) {
			orderFinancial.TotalDiscountMoney += utils.MustInterface2Int64(x.(map[string]interface{})["moneyCent"])
			orderFinancial.PmSubsidyMoney += utils.MustInterface2Int64(x.(map[string]interface{})["moneyCent"])
		}
		for _, x := range data["actOrderChargeByPoi"].([]interface{}) {
			orderFinancial.TotalDiscountMoney += utils.MustInterface2Int64(x.(map[string]interface{})["moneyCent"])
		}
	} else {
		globals.SugarLogger.Warnf("mtwm OrderDetail2Financial, orderID:%s have no poi_receive_detail", orderFinancial.VendorOrderID)
	}
	if utils.MustInterface2Int64(result["is_third_shipping"]) == SelfDeliveryCarrierNo { // is_third_shipping  int  是否是第三方配送平台配送,0表否，1表是）
		orderFinancial.SelfDeliveryDiscountMoney = orderFinancial.ReceivableFreight
		orderFinancial.DistanceFreightMoney = 0
		// 通过本地数据库去取是否转美团/达达，并计算运费
		// wayBill, err := partner.CurOrderManager.LoadWaybill(orderFinancial.VendorOrderID, orderFinancial.VendorID)
		// if err == nil {
		// 	orderFinancial.JxFreightMoney = wayBill.DesiredFee
		// }
	}
	//  // 美团订单单独处理部分，美团正向订单接口推送时总结算金额没有计算公益捐款一分钱，是否在这里直接提前扣除？
	// 	// 3/18之后的订单一直都不显示公益捐款金额，而且结算现在结算到了3/18之后的订单，没有的已经不计算了，先注释
	// 	// 2019-04-03 10.52 询问赵mf, 此计划是必须参加的，而且是长期的，每单固定扣除一分钱
	orderFinancial.DonationMoney = PublicWelfareDonation
	// 不应该对第三方结账金额做更改，就算有异常，也要保留异常，知道问题出在哪里
	// orderFinancial.ShopMoney -= PublicWelfareDonation
	return orderFinancial
}
