package tao_vegetable

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.rosy.net.cn/baseapi/platformapi/tao_vegetable"
	domain3156 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability3156/domain"
	request3156 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability3156/request"
	domain591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/domain"
	request591 "git.rosy.net.cn/baseapi/platformapi/tao_vegetable/sdk/ability591/request"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	"time"
)

var (
	AfsVendorStatus2StatusMap = map[string]int{
		tao_vegetable.OrderStatusApplyAfs:      model.AfsOrderStatusWait4Approve,
		tao_vegetable.OrderStatusCancelAfs:     model.AfsOrderStatusCancelAfs,
		tao_vegetable.OrderStatusRefundSuccess: model.AfsOrderStatusFinished,
		tao_vegetable.OrderStatusOnSaleCancel:  model.AfsOrderStatusOnSaleAfs,
	}
)

func (c *PurchaseHandler) isAfsMsg(orderStatus string, orderId string, orderCallback interface{}) bool {
	switch orderStatus {
	case tao_vegetable.OrderStatusApplyAfs, tao_vegetable.OrderStatusCancelAfs:
		order, _ := partner.CurOrderManager.LoadOrder2(orderId, model.VendorIDTaoVegetable)
		if order != nil {
			return true
		}
	case tao_vegetable.OrderStatusRefundSuccess:
		return true
		//success := orderCallback.(*tao_vegetable.RefundOrderFinish)
		//param := &request591.AlibabaWdkOrderRefundGetRequest{
		//	OrderFrom: utils.Int64ToPointer(utils.Str2Int64(tao_vegetable.TaoVegetableChannelCode)),
		//	ShopId:    nil,
		//	StoreId:   utils.String2Pointer(success.StoreId),
		//	RefundIds: &[]int64{utils.Str2Int64(success.BizSubRefundId)},
		//}
		//refundAfs, _ := getAPI("", 0, success.StoreId).QueryAfsOrderDetail(param)
		//if refundAfs.Orders != nil {
		//	return true
		//}
	case tao_vegetable.OrderStatusOnSaleCancel:
		order, _ := partner.CurOrderManager.LoadOrder(orderId, model.VendorIDTaoVegetable)
		if order != nil {
			return true
		}
	}
	return false
}

func (c *PurchaseHandler) OnAfsOrderMsg(orderId, status string, msg interface{}) (retVal *tao_vegetable.CallBackResult) {
	// 取消线程池执行代码,异步返回
	jxutils.CallMsgHandlerAsync(func() {
		retVal = c.onAfsOrderMsg(status, msg)
	}, jxutils.ComposeUniversalOrderID(orderId, model.VendorIDTaoVegetable))
	if retVal == nil {
		return tao_vegetable.CallBackResultInfo(nil)
	}
	return retVal
}

// todo 淘宝暂无部分退款，只有整单退款
func (c *PurchaseHandler) onAfsOrderMsg(status string, msg interface{}) (retVal *tao_vegetable.CallBackResult) {
	var err error
	var db = dao.GetDB()
	orderStatus, scarceGoods := c.callbackAfsMsg2Status(status, msg)
	switch status {
	case tao_vegetable.OrderStatusApplyAfs:
		refundData := msg.(*tao_vegetable.UserApplyRefundCallBack)
		var afsOrder *model.AfsOrder
		var apiObj = getAPI("", 0, refundData.StoreId)

		// 订单商品详细信息
		queryOrderDetailParam := &request591.AlibabaAelophyOrderGetRequest{OrderGetRequest: &domain591.AlibabaAelophyOrderGetOrderGetRequest{
			StoreId: utils.String2Pointer(refundData.StoreId),
		}}

		queryOrderDetailParam.OrderGetRequest.BizOrderId = utils.Int64ToPointer(utils.Str2Int64(orderStatus.RefVendorOrderID))
		skuList, err := apiObj.QueryOrderDetail(queryOrderDetailParam)
		if err != nil {
			return tao_vegetable.CallBackResultInfo(err)
		}

		for _, refundSku := range refundData.SubRefundOrders { // 本次退款订单
			afsOrder = &model.AfsOrder{
				VendorID:         model.VendorIDTaoVegetable,
				VendorOrderID:    orderStatus.RefVendorOrderID,
				VendorStoreID:    refundData.StoreId,
				StoreID:          0,
				AfsCreatedAt:     orderStatus.StatusTime,
				VendorAppealType: status,                        // 原始售后方式
				AppealType:       model.AfsAppealTypeUserCancel, // 淘宝这个接口下发的只有用户取消
				VendorReasonType: refundData.RefundReason,
				ReasonType:       0,
				ReasonDesc:       refundData.RefundReason,
				ReasonImgList:    utils.LimitUTF8StringLen(refundData.RefundPictures, 1024),
				VendorOrgCode:    apiObj.GetVendorOrgCode(),
				VendorOrderID2:   refundData.RefundId,
			}
			afsOrder.FreightUserMoney = 0                    // 订单运费
			afsOrder.AfsFreightMoney = 0                     // 暂时未发现退货取件费用
			afsOrder.BoxMoney = 0                            // 餐盒费
			afsOrder.TongchengFreightMoney = 0               // 同城配送费
			afsOrder.SkuBoxMoney = 0                         // 商品包装费
			afsOrder.VendorStatus = orderStatus.VendorStatus // 退货状态

			var refundSkuCount int64 = 0 // 子订单申请退款的商品数
			var orderSkuCount int64 = 0  // 子订单购买的商品数
			var skuBag bool = false      // 当前商品是否为包装袋,包装袋不参与收货
			refundSkuCount += refundSku.RefundAmount
			for _, sku := range *skuList.SubOrderResponseList { // 总订单
				if refundSku.OutSubOrderId == *sku.OutSubOrderId {
					if *sku.SkuCode == "6108080" {
						skuBag = true
						continue
					}
					orderSku := &model.OrderSkuFinancial{
						Count:             utils.Float64TwoInt(*sku.BuySaleQuantity),
						VendorSkuID:       *sku.SkuCode,
						Name:              *sku.SkuName,
						UserMoney:         refundSku.MaxRefundFee,
						PmSkuSubsidyMoney: *sku.DiscountPlatformFee, // 平台补贴商品
						VendorOrderID:     orderStatus.VendorOrderID,
						VendorSubOrderID:  *sku.OutSubOrderId,
					}
					if len(*sku.SkuCode) <= 9 {
						orderSku.SkuID = utils.Str2Int(*sku.SkuCode)
					}
					afsOrder.PmSkuSubsidyMoney += orderSku.PmSkuSubsidyMoney
					afsOrder.Skus = append(afsOrder.Skus, orderSku)
					orderSkuCount += utils.Float64TwoInt64(*sku.BuySaleQuantity)
					afsOrder.VendorOrderID = utils.Int64ToStr(*skuList.BizOrderId)
					afsOrder.AfsOrderID = utils.Int64ToStr(*sku.BizSubOrderId)
				}
			}
			if skuBag {
				continue
			}

			if refundSkuCount == orderSkuCount && refundData.RefundFee == *skuList.PayFee { // 全退
				afsOrder.RefundType = model.AfsTypeFullRefund
			} else {
				afsOrder.RefundType = model.AfsTypePartRefund
			}
			afsOrder.SkuUserMoney += refundData.RefundFee

			afs2, _ := partner.CurOrderManager.LoadAfsOrder(afsOrder.AfsOrderID, afsOrder.VendorID)
			if afs2 != nil {
				_, err = dao.DeleteEntity(db, afsOrder, "VendorOrderID", "AfsOrderID", "VendorID")
				_, err = dao.DeleteEntity(db, &model.OrderSkuFinancial{
					VendorOrderID: afsOrder.VendorOrderID,
					VendorID:      afsOrder.VendorID,
					IsAfsOrder:    1,
					AfsOrderID:    afsOrder.AfsOrderID,
				}, "VendorOrderID", "VendorID", "IsAfsOrder", "AfsOrderID")
				afsOrder.ReasonDesc += "(拒绝退款后,用户再次申请)"
			}
			//直接就来一个新的售后单，并且还是售后完成的
			if orderStatus.Status == model.AfsOrderStatusFinished {
				afsOrder.AfsFinishedAt = afsOrder.AfsCreatedAt
			}
			orderStatus.RefVendorOrderID = afsOrder.VendorOrderID
			orderStatus.VendorOrderID = afsOrder.AfsOrderID
			err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
		}

	case tao_vegetable.OrderStatusCancelAfs:
		// 删除售后单
		afsOrder, err := dao.GetAfsOrders(db, model.VendorIDTaoVegetable, orderStatus.RefVendorOrderID, "")
		if err != nil || afsOrder == nil {
			globals.SugarLogger.Debugf("用户取消售后单,获取之前生成的售后单失败")
			return tao_vegetable.CallBackResultInfo(err)
		}

		cancelMsg := msg.(*tao_vegetable.UserCancelRefundApply)
		for _, v := range afsOrder {
			// 商家驳回,会发出用户撤销的回调通知,不管他
			if v.VendorOrderID2 != cancelMsg.RefundId {
				continue
			}

			// 用户撤销未处理的售后订单
			if v.Flag == 0 {
				// 下面处理用户撤销售后
				if err = utils.CallFuncLogError(func() error {
					_, err = dao.DeleteEntity(db, v, "VendorOrderID", "AfsOrderID", "VendorID")
					return err
				}, "SaveAfsOrder delete AfsOrder, afsOrderID:%s", v.AfsOrderID); err != nil {
					return tao_vegetable.CallBackResultInfo(err)
				}
				// 删除售后商品
				if err = utils.CallFuncLogError(func() error {
					_, err = dao.DeleteEntity(db, &model.OrderSkuFinancial{
						VendorOrderID: v.VendorOrderID,
						VendorID:      v.VendorID,
						IsAfsOrder:    1,
						AfsOrderID:    v.AfsOrderID,
					}, "VendorOrderID", "VendorID", "IsAfsOrder", "AfsOrderID")
					return err
				}, "SaveAfsOrder delete OrderSkuFinancial, afsOrderID:%s", v.AfsOrderID); err != nil {
					return tao_vegetable.CallBackResultInfo(err)
				}
			}
		}
		// 业务上规定的是打包之后不能取消，但是如果配送超过了预计送达时间1-2小时，
	// c端的取消按钮会自动打开，让用户操作取消，但是如果你没接这个接口，用户申请取消了，
	// 你这边没有响应那么就不会退钱给用户，就会造成客诉。为什么不接售中取消呢
	case tao_vegetable.OrderStatusOnSaleCancel:
		onSaleMsg := msg.(*tao_vegetable.OnSaleCancel)
		var afsOrder *model.AfsOrder
		var api = getAPI("", 0, onSaleMsg.PartCancelRequest.StoreId)
		queryOrderDetailParam := &request591.AlibabaAelophyOrderGetRequest{OrderGetRequest: &domain591.AlibabaAelophyOrderGetOrderGetRequest{
			StoreId:    utils.String2Pointer(onSaleMsg.PartCancelRequest.StoreId),
			BizOrderId: utils.Int64ToPointer(onSaleMsg.PartCancelRequest.BizOrderId),
		}}
		orderDetail, err := api.QueryOrderDetail(queryOrderDetailParam)
		if err != nil {
			return tao_vegetable.CallBackResultInfo(err)
		}

		for _, v1 := range onSaleMsg.PartCancelRequest.SubOrders {
			afsOrder = &model.AfsOrder{
				VendorID:         model.VendorIDTaoVegetable,
				AfsOrderID:       utils.Int64ToStr(v1.BizSubOrderId),
				VendorOrderID:    orderStatus.RefVendorOrderID,
				VendorStoreID:    onSaleMsg.PartCancelRequest.StoreId,
				StoreID:          0,
				AfsCreatedAt:     orderStatus.StatusTime,
				VendorAppealType: status,                        // 原始售后方式
				AppealType:       model.AfsAppealTypeUserCancel, // 淘宝这个接口下发的只有用户取消
				VendorReasonType: tao_vegetable.OrderStatusOnSaleCancel,
				ReasonType:       0,
				ReasonDesc:       "售中取消:订单未打包,或者长时间为送到!响应成功直接退款",
				VendorOrgCode:    api.GetVendorOrgCode(),
			}
			afsOrder.FreightUserMoney = 0                    // 订单运费
			afsOrder.AfsFreightMoney = 0                     // 暂时未发现退货取件费用
			afsOrder.BoxMoney = 0                            // 餐盒费
			afsOrder.TongchengFreightMoney = 0               // 同城配送费
			afsOrder.SkuBoxMoney = 0                         // 商品包装费
			afsOrder.VendorStatus = orderStatus.VendorStatus // 退货状态

			ifAfsTypeFullRefund := false
			var refundFee int64 = 0
			for _, v := range *orderDetail.SubOrderResponseList {
				for _, v2 := range onSaleMsg.PartCancelRequest.SubOrders {
					if *v.BizSubOrderId == v2.BizSubOrderId {
						if *v.SkuCode == "6108080" {
							continue
						}
						orderSku := &model.OrderSkuFinancial{
							Count:             utils.Float64TwoInt(*v.BuySaleQuantity),
							VendorSkuID:       *v.SkuCode,
							SkuID:             utils.Str2Int(*v.SkuCode),
							Name:              *v.SkuName,
							UserMoney:         *v.OriginalFee,
							PmSkuSubsidyMoney: *v.DiscountPlatformFee, // 平台补贴商品
							VendorOrderID:     orderStatus.VendorOrderID,
							VendorSubOrderID:  *v.OutSubOrderId,
						}
						afsOrder.PmSkuSubsidyMoney += orderSku.PmSkuSubsidyMoney
						afsOrder.Skus = append(afsOrder.Skus, orderSku)
						refundFee += *v.OriginalFee
					}
				}
			}
			if len(onSaleMsg.PartCancelRequest.SubOrders) == len(*orderDetail.SubOrderResponseList) {
				ifAfsTypeFullRefund = true
			}

			afsOrder.SkuUserMoney += refundFee
			if ifAfsTypeFullRefund { // 全退
				afsOrder.RefundType = model.AfsTypeFullRefund
				afsOrder.SkuUserMoney += *orderDetail.PostFee
				afsOrder.Skus[len(afsOrder.Skus)-1].UserMoney += *orderDetail.PostFee
			} else {
				afsOrder.RefundType = model.AfsTypePartRefund
			}

			if afsOrder != nil {
				//直接就来一个新的售后单，并且还是售后完成的
				afsOrder.AfsFinishedAt = afsOrder.AfsCreatedAt
				afsOrder.Flag = model.AfsOrderFlagAgreeUserRefund
				orderStatus.VendorOrderID = afsOrder.AfsOrderID
				err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
			}
		}
	case tao_vegetable.OrderStatusRefundSuccess:
		// 用户退款成功回调,缺货拣货时,送达回触发.此时并没有售后单
		if scarceGoods != nil {
			refundSuccess := msg.(*tao_vegetable.RefundOrderFinish)
			var afsOrder *model.AfsOrder
			var api = getAPI("", 0, refundSuccess.StoreId)
			detail, err := api.QueryAfsOrderDetail(&request591.AlibabaWdkOrderRefundGetRequest{
				OrderFrom: utils.Int64ToPointer(tao_vegetable.ChannelCome),
				ShopId:    nil,
				StoreId:   utils.String2Pointer(refundSuccess.StoreId),
				RefundIds: &[]int64{utils.Str2Int64(refundSuccess.BizSubRefundId)},
			})
			if err != nil {
				return tao_vegetable.CallBackResultInfo(err)
			}

			for _, v := range *detail.Orders {
				afs, _ := partner.CurOrderManager.LoadAfsOrder(utils.Int64ToStr(*v.OriginOrderId), model.VendorIDTaoVegetable)
				if afs == nil {
					afsOrder = &model.AfsOrder{
						VendorID:         model.VendorIDTaoVegetable,
						AfsOrderID:       utils.Int64ToStr(*v.OriginOrderId),
						VendorOrderID:    orderStatus.RefVendorOrderID,
						VendorOrderID2:   refundSuccess.BizSubRefundId,
						VendorStoreID:    refundSuccess.StoreId,
						StoreID:          0,
						AfsCreatedAt:     orderStatus.StatusTime,
						VendorAppealType: status,                        // 原始售后方式
						AppealType:       model.AfsAppealTypeUserCancel, // 淘宝这个接口下发的只有用户取消
						VendorReasonType: tao_vegetable.OrderStatusOnSaleCancel,
						ReasonType:       0,
						ReasonDesc:       "缺货调整,退款成功通知",
						VendorOrgCode:    api.GetVendorOrgCode(),
					}
					afsOrder.FreightUserMoney = 0                    // 订单运费
					afsOrder.AfsFreightMoney = 0                     // 暂时未发现退货取件费用
					afsOrder.BoxMoney = 0                            // 餐盒费
					afsOrder.TongchengFreightMoney = 0               // 同城配送费
					afsOrder.SkuBoxMoney = 0                         // 商品包装费
					afsOrder.VendorStatus = orderStatus.VendorStatus // 退货状态

					for _, v := range *scarceGoods {
						var refundFee int64 = 0
						skuDetail := tao_vegetable.GoodsScarceRefund{}
						if err := json.Unmarshal([]byte(*v.Attributes), &skuDetail); err != nil {
							return tao_vegetable.CallBackResultInfo(err)
						}
						if *v.SkuCode == "6108080" {
							continue
						}
						orderSku := &model.OrderSkuFinancial{
							Count:             utils.Float64TwoInt(utils.Str2Float64(*v.RefundQuantity)),
							VendorSkuID:       *v.SkuCode,
							SkuID:             utils.Str2Int(*v.SkuCode),
							Name:              skuDetail.SkuName,
							UserMoney:         *v.RefundAmount,
							PmSkuSubsidyMoney: 0, // 平台补贴商品
							VendorOrderID:     orderStatus.VendorOrderID,
							VendorSubOrderID:  *v.OutOrderId,
						}
						afsOrder.PmSkuSubsidyMoney += orderSku.PmSkuSubsidyMoney
						afsOrder.Skus = append(afsOrder.Skus, orderSku)
						refundFee += *v.RefundAmount

						afsOrder.SkuUserMoney += refundFee
						afsOrder.RefundType = model.AfsTypePartRefund
						if afsOrder != nil {
							//直接就来一个新的售后单，并且还是售后完成的
							afsOrder.AfsFinishedAt = afsOrder.AfsCreatedAt
							afsOrder.Flag = model.AfsOrderFlagAgreeUserRefund
							err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
						}
					}
				} else {
					afs.VendorOrderID2 = refundSuccess.BizSubRefundId
					afs.AfsFinishedAt = time.Now()
					afs.Status = model.AfsOrderStatusFinished
					afs.AfsTotalShopMoney = *v.RefundAmount
					dao.UpdateEntity(db, afs, "VendorOrderID2", "AfsFinishedAt", "Status", "AfsTotalShopMoney")
				}
			}
		}
	default:

	}

	if err := partner.CurOrderManager.OnAfsOrderStatusChanged(orderStatus); err == nil {
		skuList, _ := dao.GetSimpleOrderSkus(db, orderStatus.RefVendorOrderID, nil)
		totalSkuCount := 0
		for _, v := range skuList {
			totalSkuCount += v.Count
		}

		financialSku, _ := dao.GetOrderRefundSkuList(db, []string{orderStatus.RefVendorOrderID})
		refundSkuCount := 0
		for _, v := range financialSku {
			refundSkuCount += v.Count
		}
		if err == nil && status == tao_vegetable.OrderStatusRefundSuccess && totalSkuCount == refundSkuCount {
			goodsOrder, _ := partner.CurOrderManager.LoadOrder(orderStatus.RefVendorOrderID, orderStatus.VendorID)
			goodsOrder.Status = model.OrderStatusCanceled
			goodsOrder.VendorStatus = orderStatus.VendorStatus
			dao.UpdateEntity(db, goodsOrder, "Status", "VendorStatus")
			// 取消三方运单
			waybill, _ := dao.GetWaybills(db, goodsOrder.VendorOrderID, []int64{model.VendorIDMTPS, model.VendorIDDada, model.VendorIDFengNiao, model.VendorIDUUPT, model.VendorIDSFPS})
			for _, v := range waybill {
				err = partner.GetDeliveryPlatformFromVendorID(v.WaybillVendorID).Handler.CancelWaybill(v, 0, "订单被取消了11")
				if err != nil {
					partner.CurOrderManager.OnOrderMsg(goodsOrder, fmt.Sprintf("订单[%s]被取消了,运单[%s]取消失败Err: %s", goodsOrder.VendorOrderID, v.VendorWaybillID, err.Error()), "")
				} else {
					partner.CurOrderManager.OnOrderMsg(goodsOrder, fmt.Sprintf("订单[%s]被取消了,运单[%s]取消成功", goodsOrder.VendorOrderID, v.VendorWaybillID), "")
				}
			}
		}
	}

	return tao_vegetable.CallBackResultInfo(err)
}

func (c *PurchaseHandler) callbackAfsMsg2Status(status string, msg interface{}) (orderStatus *model.OrderStatus, taoRefundList *[]domain591.AlibabaWdkOrderRefundGetOrderSyncRefundDto) {
	orderStatus = &model.OrderStatus{
		VendorID:    model.VendorIDTaoVegetable,
		OrderType:   model.OrderTypeAfsOrder,
		RefVendorID: model.VendorIDTaoVegetable,
	}

	switch status {
	case tao_vegetable.OrderStatusApplyAfs: // 用户申请售后
		refundData := msg.(*tao_vegetable.UserApplyRefundCallBack)
		orderStatus.VendorStatus = fmt.Sprintf("%s:%s", tao_vegetable.OrderStatusApplyAfs, "用户申请取消")
		orderStatus.Status = c.GetAfsStatusFromVendorStatus(tao_vegetable.OrderStatusApplyAfs)
		orderStatus.StatusTime = time.Now()
		orderStatus.Remark = refundData.Remarks
		//orderStatus.VendorOrderID = refundData.RefundId

		order, _ := partner.CurOrderManager.LoadOrder2(refundData.OutOrderId, model.VendorIDTaoVegetable)
		orderStatus.RefVendorOrderID = order.VendorOrderID
	case tao_vegetable.OrderStatusCancelAfs: // 用户取消售后
		refundData := msg.(*tao_vegetable.UserCancelRefundApply)
		orderStatus.VendorStatus = fmt.Sprintf("%s:%s", tao_vegetable.OrderStatusCancelAfs, "用户取消售后申请")
		orderStatus.Status = c.GetAfsStatusFromVendorStatus(tao_vegetable.OrderStatusCancelAfs)
		orderStatus.StatusTime = time.Now()
		orderStatus.VendorOrderID = refundData.RefundId
		order, _ := partner.CurOrderManager.LoadOrder2(refundData.OutOrderId, model.VendorIDTaoVegetable)
		orderStatus.RefVendorOrderID = order.VendorOrderID
	case tao_vegetable.OrderStatusOnSaleCancel:
		refundData := msg.(*tao_vegetable.OnSaleCancel)
		orderStatus.RefVendorOrderID = utils.Int64ToStr(refundData.PartCancelRequest.BizOrderId)
		orderStatus.VendorStatus = fmt.Sprintf("%s:%s", tao_vegetable.OrderStatusOnSaleCancel, "用户售中取消")
		orderStatus.Status = c.GetAfsStatusFromVendorStatus(tao_vegetable.OrderStatusOnSaleCancel)
		orderStatus.StatusTime = time.Now()
		orderStatus.VendorOrderID = utils.Int64ToStr(refundData.PartCancelRequest.SubOrders[0].BizSubOrderId)
	case tao_vegetable.OrderStatusRefundSuccess: // 售后成功
		refundData := msg.(*tao_vegetable.RefundOrderFinish)
		var refundAfs *domain591.AlibabaWdkOrderRefundGetOrderSyncRefundListResult
		for i := 0; i < 4; i++ {
			param := &request591.AlibabaWdkOrderRefundGetRequest{
				OrderFrom: utils.Int64ToPointer(utils.Str2Int64(tao_vegetable.TaoVegetableChannelCode)),
				ShopId:    nil,
				StoreId:   utils.String2Pointer(refundData.StoreId),
				RefundIds: &[]int64{utils.Str2Int64(refundData.BizSubRefundId)},
			}
			refundAfs, _ = getAPI("", 0, refundData.StoreId).QueryAfsOrderDetail(param)
			if refundAfs.Orders != nil {
				break
			}
			time.Sleep(time.Second * 1)
		}
		orders := *refundAfs.Orders

		afsOrder, _ := partner.CurOrderManager.LoadAfsOrder(utils.Int64ToStr(*orders[0].OriginOrderId), model.VendorIDTaoVegetable)
		if afsOrder != nil {
			orderStatus.RefVendorOrderID = afsOrder.VendorOrderID
			orderStatus.VendorStatus = fmt.Sprintf("%s:%s", tao_vegetable.OrderStatusRefundSuccess, "用户售后退款成功")
			orderStatus.Status = c.GetAfsStatusFromVendorStatus(tao_vegetable.OrderStatusRefundSuccess)
			orderStatus.StatusTime = time.Now()
			orderStatus.Remark = fmt.Sprintf("QueryTaoAfsOrderId:%s", refundData.BizSubRefundId)
			orderStatus.VendorOrderID = utils.Int64ToStr(*orders[0].OriginOrderId)
		} else {
			orderStatus.RefVendorOrderID = utils.Int64ToStr(*orders[0].OriginParentId)
			orderStatus.VendorStatus = fmt.Sprintf("%s:%s", tao_vegetable.OrderStatusRefundSuccess, "用户售中退款成功")
			orderStatus.Status = c.GetAfsStatusFromVendorStatus(tao_vegetable.OrderStatusRefundSuccess)
			orderStatus.StatusTime = time.Now()
			orderStatus.Remark = fmt.Sprintf("QueryTaoAfsOrderId:%s", refundData.BizSubRefundId)
			orderStatus.VendorOrderID = utils.Int64ToStr(*orders[0].OriginOrderId)
			taoRefundList = refundAfs.Orders
		}

	}

	if orderStatus.VendorOrderID == "" {
		orderStatus.VendorOrderID = orderStatus.RefVendorOrderID
	}
	return orderStatus, taoRefundList
}

func (c *PurchaseHandler) GetAfsStatusFromVendorStatus(notifyType string) int {
	status := AfsVendorStatus2StatusMap[notifyType]
	//if status == model.AfsOrderStatusWait4Approve || status == model.AfsOrderStatusOnSaleAfs {
	//	status = model.AfsOrderStatusNew
	//}
	return status
}

// 审核售后单申请
func (c *PurchaseHandler) AgreeOrRefuseRefund(ctx *jxcontext.Context, order *model.AfsOrder, approveType int, reason string, review map[string]interface{}) (err error) {
	db := dao.GetDB()
	if approveType == partner.AfsApproveTypeRefused {
		param := &request3156.AlibabaTclsAelophyRefundDisagreeRequest{
			RefundId:     utils.String2Pointer(order.VendorOrderID2),
			RejectReason: utils.String2Pointer(reason),
			OrderFrom:    utils.Int64ToPointer(utils.Str2Int64(tao_vegetable.TaoVegetableChannelCode)),
		}
		err = getAPI(order.VendorOrgCode, jxutils.GetSaleStoreIDFromAfsOrder(order), order.VendorStoreID).DisAgreeUserCancel(param)
		if err == nil {
			order.Status = model.AfsOrderStatusFailed
			order.VendorStatus = "老板拒绝"
			order.Flag = model.AfsOrderFlagRefuseUserRefund
			order.ReasonDesc += "," + reason
			dao.UpdateEntity(dao.GetDB(), order, "Status", "ReasonDesc", "VendorStatus")
		}
	} else if approveType == partner.AfsApproveTypeRefusedToRefundMoney {
		return errors.New("此平台暂时不支持")
	} else {
		// 加载子订单号
		orderDetail, _ := partner.CurOrderManager.LoadOrder(order.VendorOrderID, model.VendorIDTaoVegetable)
		// 加载退款商品
		afsSkuOrder, _ := dao.GetOrderRefundSkuList(db, []string{order.VendorOrderID})
		param := &request3156.AlibabaTclsAelophyRefundAgreeRequest{
			StoreId:    utils.String2Pointer(order.VendorStoreID),
			OutOrderId: utils.String2Pointer(orderDetail.VendorOrderID2),
			RefundId:   utils.String2Pointer(order.VendorOrderID2),
			OrderFrom:  utils.Int64ToPointer(utils.Str2Int64(tao_vegetable.TaoVegetableChannelCode)),
		}

		subRefundList := make([]domain3156.AlibabaTclsAelophyRefundAgreeSubrefundlist, 0, len(afsSkuOrder))
		for _, v := range afsSkuOrder {
			subRefundList = append(subRefundList, domain3156.AlibabaTclsAelophyRefundAgreeSubrefundlist{
				OutSubOrderId: utils.String2Pointer(v.VendorSubOrderID),
				RefundFee:     utils.Int64ToPointer(v.UserMoney / int64(v.Count)),
			})
		}

		param.SubRefundList = &subRefundList
		param.AuditMemo = utils.String2Pointer(fmt.Sprintf("商户同意退款"))
		if reason != "" {
			param.AuditMemo = utils.String2Pointer(*param.AuditMemo + fmt.Sprintf(",%s", reason))
		}
		err = getAPI(order.VendorOrgCode, jxutils.GetSaleStoreIDFromAfsOrder(order), order.VendorStoreID).AgreeUserCancel(param)

	}
	return err
}

// 确认收到退货
func (c *PurchaseHandler) ConfirmReceivedReturnGoods(ctx *jxcontext.Context, order *model.AfsOrder) (err error) {
	err = fmt.Errorf("内部错误，美团外卖平台不支持确认收到退货操作")
	return err
}

// 发起全款退款
func (c *PurchaseHandler) RefundOrder(ctx *jxcontext.Context, order *model.GoodsOrder, reason string) (err error) {
	return fmt.Errorf("%s不支持售后全额退款，请让买家发起退款", model.VendorChineseNames[model.VendorIDTaoVegetable])
}

// 发起部分退款
func (c *PurchaseHandler) PartRefundOrder(ctx *jxcontext.Context, order *model.GoodsOrder, refundSkuList []*model.OrderSku, reason string) (err error) {
	return c.AdjustOrder(ctx, order, refundSkuList, reason)
}

func (c *PurchaseHandler) GetOrderAfsInfo(ctx *jxcontext.Context, vendorOrderID, afsOrderID string) (orderAfsInfo *partner.OrderAfsInfo, err error) {
	orderAfsInfo = &partner.OrderAfsInfo{}
	var afsTotalShopMoney int64
	if list, err := api.MtwmAPI.GetOrderRefundDetail(utils.Str2Int64(vendorOrderID), 0); err == nil {
		for _, v := range list {
			if v.RefundPartialEstimateCharge.SettleAmount != "" {
				afsTotalShopMoney += jxutils.StandardPrice2Int(utils.Str2Float64(v.RefundPartialEstimateCharge.SettleAmount))
			}
		}
	}
	if order, err := partner.CurOrderManager.LoadOrder(vendorOrderID, model.VendorIDTaoVegetable); err == nil {
		orderAfsInfo.AfsTotalShopMoney = order.TotalShopMoney + afsTotalShopMoney
	}
	return orderAfsInfo, err
}
