package jd

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

var (
	AfsVendorStatus2StatusMap = map[string]int{
		jdapi.AfsServiceStateWaiting4Audit: model.AfsOrderStatusWait4Approve, // 需要审核

		jdapi.AfsServiceStateWaiting4CSFeedback:       model.AfsOrderStatusNew,
		jdapi.AfsServiceStateRefundProcessing:         model.AfsOrderStatusNew,
		jdapi.AfsServiceStateWaiting4DirectCompensate: model.AfsOrderStatusNew,
		jdapi.AfsServiceStateWaiting4ReturnGoods:      model.AfsOrderStatusNew,

		jdapi.AfsServiceStateWaiting4MerchantReceiveGoods: model.AfsOrderStatusWait4ReceiveGoods,

		jdapi.AfsServiceStateRefundSuccess:           model.AfsOrderStatusFinished,
		jdapi.AfsServiceStateSolved:                  model.AfsOrderStatusFinished,
		jdapi.AfsServiceStateDirectCompensateSuccess: model.AfsOrderStatusFinished,
		jdapi.AfsServiceStateReturnGoodsSuccess:      model.AfsOrderStatusFinished,

		jdapi.AfsServiceStateRefundFailed:               model.AfsOrderStatusFailed,
		jdapi.AfsServiceStateAuditRefused:               model.AfsOrderStatusFailed,
		jdapi.AfsServiceStateUserCanceled:               model.AfsOrderStatusFailed,
		jdapi.AfsServiceStateMerchantFailedReceiveGoods: model.AfsOrderStatusFailed,
		jdapi.AfsServiceStateDirectCompensateFailed:     model.AfsOrderStatusFailed,
		jdapi.AfsServiceStateReturnGoodsFailed:          model.AfsOrderStatusFailed,
	}

	afsReasonTypeMap = map[int]int8{
		jdapi.AfsReasonTypeGoodsQuality:     model.AfsReasonTypeGoodsQuality,
		jdapi.AfsReasonTypeWrongGoods:       model.AfsReasonTypeWrongGoods,
		jdapi.AfsReasonTypeMissingGoods:     model.AfsReasonTypeMissingGoods,
		jdapi.AfsReasonTypeNoGoods:          model.AfsReasonTypeNoGoods,
		jdapi.AfsReasonTypeDamagedGoods:     model.AfsReasonTypeDamagedGoods,
		jdapi.AfsReasonTypeGoodsQuantity:    model.AfsReasonTypeGoodsQuantity,
		jdapi.AfsReasonTypeGoodsAbsent:      model.AfsReasonTypeGoodsAbsent,
		jdapi.AfsReasonTypeGoodsSizeNoSame:  model.AfsReasonTypeGoodsNoSame,
		jdapi.AfsReasonTypeGoodsColorNoSame: model.AfsReasonTypeGoodsNoSame,
		jdapi.AfsReasonWrongPurchase:        model.AfsReasonWrongPurchase,
		jdapi.AfsReasonNotReceivedIntime:    model.AfsReasonNotReceivedIntime,
	}
	afsAppealTypeMap = map[string]int8{
		jdapi.AfsDealTypeRefund:            model.AfsAppealTypeRefund,
		jdapi.AfsDealTypeReturnGoodsRefund: model.AfsAppealTypeReturnAndRefund,
		jdapi.AfsDealTypeDirectCompensate:  model.AfsAppealTypeNewGoods,
	}
	afsApproveTypeMap = map[int]int{
		partner.AfsApproveTypeRefund:      jdapi.AfsApproveTypeRefund,
		partner.AfsApproveTypeReturnGoods: jdapi.AfsApproveTypeReturnGoods,
		partner.AfsApproveTypeRefused:     jdapi.AfsApproveTypeRefused,
	}
)

func (c *PurchaseHandler) OnAfsOrderMsg(a *jdapi.API, msg *jdapi.CallbackOrderMsg) (retVal *jdapi.CallbackResponse) {
	jxutils.CallMsgHandlerAsync(func() {
		retVal = c.onAfsOrderMsg(a, msg)
	}, jxutils.ComposeUniversalOrderID(msg.BillID, model.VendorIDJD))
	return retVal
}

func (c *PurchaseHandler) onAfsOrderMsg(a *jdapi.API, msg *jdapi.CallbackOrderMsg) (retVal *jdapi.CallbackResponse) {
	afsInfo, err := a.GetAfsService2(msg.BillID)
	if err == nil {
		status := c.callbackAfsMsg2Status(msg, afsInfo)
		if partner.CurOrderManager.GetStatusDuplicatedCount(status) > 0 {
			return nil
		}
		if status.Status == model.AfsOrderStatusWait4Approve || status.Status == model.AfsOrderStatusNew {
			afsOrder := c.buildAfsOrder(afsInfo)
			err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, status)
		} else {
			err = partner.CurOrderManager.OnAfsOrderStatusChanged(status)
		}
		retVal = jdapi.Err2CallbackResponse(err, status.VendorStatus)
	}
	return retVal
}

func (c *PurchaseHandler) callbackAfsMsg2Status(msg *jdapi.CallbackOrderMsg, afsInfo *jdapi.AfsServiceResponse) *model.OrderStatus {
	orderStatus := &model.OrderStatus{
		VendorOrderID:    msg.BillID, // 是售后单ID，不是订单ID，订单ID在RefVendorOrderID中
		VendorID:         model.VendorIDJD,
		OrderType:        model.OrderTypeAfsOrder,
		RefVendorOrderID: afsInfo.OrderID,
		RefVendorID:      model.VendorIDJD,
		VendorStatus:     msg.StatusID,
		Status:           c.GetAfsStatusFromVendorStatus(msg.StatusID),
		StatusTime:       utils.Str2Time(msg.Timestamp),
		Remark:           msg.Remark,
	}
	return orderStatus
}

func (c *PurchaseHandler) GetAfsStatusFromVendorStatus(vendorStatus string) int {
	if status, ok := AfsVendorStatus2StatusMap[vendorStatus]; ok {
		return status
	}
	return model.OrderStatusUnknown
}

func (c *PurchaseHandler) convertAfsReasonType(vendorReasonType int) int8 {
	if status, ok := afsReasonTypeMap[vendorReasonType]; ok {
		return status
	}
	return model.AfsReasonNotOthers
}

func (c *PurchaseHandler) convertAfsAppealType(vendorAppealType string) int8 {
	if status, ok := afsAppealTypeMap[vendorAppealType]; ok {
		return status
	}
	return 0
}

func (c *PurchaseHandler) buildAfsOrder(afsInfo *jdapi.AfsServiceResponse) (afsOrder *model.AfsOrder) {
	afsOrder = &model.AfsOrder{
		VendorID:         model.VendorIDJD,
		AfsOrderID:       afsInfo.AfsServiceOrder,
		VendorOrderID:    afsInfo.OrderID,
		VendorStoreID:    afsInfo.StationID,
		StoreID:          int(utils.Str2Int64WithDefault(afsInfo.StationNumOutSystem, 0)),
		AfsCreatedAt:     afsInfo.CreateTime.GoTime(),
		VendorAppealType: afsInfo.ApplyDeal,
		AppealType:       c.convertAfsAppealType(afsInfo.ApplyDeal),
		VendorReasonType: utils.Int2Str(afsInfo.QuestionTypeCid),
		ReasonType:       c.convertAfsReasonType(afsInfo.QuestionTypeCid),
		ReasonDesc:       utils.LimitUTF8StringLen(afsInfo.QuestionDesc, 1024),
		ReasonImgList:    utils.LimitUTF8StringLen(jdapi.ProcessQuestionPic(afsInfo.QuestionPic), 1024),
		VendorOrgCode:    afsInfo.VenderID,

		FreightUserMoney:      afsInfo.OrderFreightMoney,
		AfsFreightMoney:       afsInfo.AfsFreight,
		BoxMoney:              afsInfo.PackagingMoney,
		TongchengFreightMoney: afsInfo.TongchengFreightMoney,
		SkuBoxMoney:           afsInfo.MealBoxMoney,
		VendorStatus:          utils.Int2Str(afsInfo.AfsServiceState),
	}
	afsOrder.Status = c.GetAfsStatusFromVendorStatus(afsOrder.VendorStatus)

	for _, x := range afsInfo.AfsDetailList {
		orderSku := &model.OrderSkuFinancial{
			// VendorID:      model.VendorIDJD,
			// AfsOrderID:    afsOrder.AfsOrderID,
			// VendorOrderID: afsOrder.VendorOrderID,
			// VendorStoreID: afsOrder.VendorStoreID,
			// StoreID:       afsOrder.StoreID,
			// IsAfsOrder:        1,

			Count: x.SkuCount,
			// ConfirmTime:          afsOrder.AfsCreateAt,
			VendorSkuID:       utils.Int64ToStr(x.WareID),
			SkuID:             int(utils.Str2Int64WithDefault(x.SkuIDIsv, 0)),
			Name:              x.WareName,
			UserMoney:         x.AfsMoney,
			PmSkuSubsidyMoney: x.PlatPayMoney,
		}
		if x.PromotionType != 0 && x.PromotionType != jdapi.PromotionTypeNormal {
			orderSku.StoreSubName = utils.Int2Str(x.PromotionType)
		}
		afsOrder.PmSkuSubsidyMoney += orderSku.PmSkuSubsidyMoney
		orderSku.PmSubsidyMoney += orderSku.PmSkuSubsidyMoney

		for _, y := range x.AfsSkuDiscountList {
			orderSku.PmSubsidyMoney += y.PlatPayMoney
		}

		afsOrder.SkuUserMoney += orderSku.UserMoney
		afsOrder.PmSubsidyMoney += orderSku.PmSubsidyMoney
		afsOrder.Skus = append(afsOrder.Skus, orderSku)
	}
	return afsOrder
}

//  审核售后单申请
func (c *PurchaseHandler) AgreeOrRefuseRefund(ctx *jxcontext.Context, order *model.AfsOrder, approveType int, reason string, review map[string]interface{}) (err error) {
	if globals.EnableJdStoreWrite {
		err = getAPI(order.VendorOrgCode).AfsOpenApprove(order.AfsOrderID, afsApproveTypeMap[approveType], reason, ctx.GetUserName())
	}
	return err
}

// 确认收到退货
func (c *PurchaseHandler) ConfirmReceivedReturnGoods(ctx *jxcontext.Context, order *model.AfsOrder) (err error) {
	if globals.EnableJdStoreWrite {
		err = getAPI(order.VendorOrgCode).ConfirmReceipt(order.AfsOrderID, ctx.GetUserName())
	}
	return err
}

func orderSkus2AfsSkus(refundSkuList []*model.OrderSku) (list []*jdapi.VenderAfsSkuDTO) {
	for _, v := range refundSkuList {
		actType := int(utils.Str2Int64WithDefault(v.StoreSubName, 0))
		if actType == 0 { //!(actType == jdapi.PromotionTypeOverflowGiveGift || actType == jdapi.PromotionTypeBuyGiveGift) {
			actType = 1
		}
		list = append(list, &jdapi.VenderAfsSkuDTO{
			SkuID:         utils.Str2Int64(v.VendorSkuID),
			SkuCount:      v.Count,
			PromotionType: actType,
		})
	}
	return list
}

// 发起全款退款
func (c *PurchaseHandler) RefundOrder(ctx *jxcontext.Context, order *model.GoodsOrder, reason string) (err error) {
	return c.PartRefundOrder(ctx, order, order.Skus, reason)
}

// 发起部分退款
func (c *PurchaseHandler) PartRefundOrder(ctx *jxcontext.Context, order *model.GoodsOrder, refundSkuList []*model.OrderSku, reason string) (err error) {
	if globals.EnableJdStoreWrite {
		_, err = getAPI(order.VendorOrgCode).AfsSubmit(order.VendorOrderID, ctx.GetUserName(), utils.Int2Str(jdapi.AfsReasonTypeGoodsQuality), reason, "", order.ConsigneeName, order.ConsigneeMobile, order.ConsigneeAddress, orderSkus2AfsSkus(refundSkuList))
	}
	return err
}

func (c *PurchaseHandler) GetOrderAfsInfo(ctx *jxcontext.Context, vendorOrderID, afsOrderID string) (orderAfsInfo *partner.OrderAfsInfo, err error) {
	orderAfsInfo = &partner.OrderAfsInfo{}
	var afsTotalShopMoney int
	if order, err := partner.CurOrderManager.LoadOrder(vendorOrderID, model.VendorIDJD); err == nil && order != nil {
		if billList, err2 := getAPI(order.VendorOrgCode).CheckAfsBill(vendorOrderID); err2 == nil && len(billList) > 0 {
			for _, v := range billList {
				afsTotalShopMoney += v.FreightBill + v.GoodsBill + v.MarketBill + v.PackageBill
			}
		}
		orderAfsInfo.AfsTotalShopMoney = order.TotalShopMoney + int64(afsTotalShopMoney)
	}
	return orderAfsInfo, err
}
