package tiktok_store

import (
	"fmt"
	tiktokShop "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/tiktok_api"
	"git.rosy.net.cn/baseapi/utils"
	"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"
	"strings"
)

var (
	afsAppealTypeMap = map[int64]int8{
		tiktokShop.AfterSaleTypeAll:                    model.AfsAppealTypeReturnAndRefund,
		tiktokShop.AfterSaleTypeSendPkgOnlyReturnMoney: model.AfsAppealTypeRefund,
		tiktokShop.AfterSaleTypeReturnMoney:            model.AfsAppealTypeRefund,
		tiktokShop.AfterSaleTypeChangePkg:              model.AfsAppealTypeNewGoods,
		tiktokShop.AfterSaleTypeSystemCancel:           model.AfsAppealTypeSystemCancel,
		tiktokShop.AfterSaleTypeUserCancel:             model.AfsAppealTypeUserCancel,
		tiktokShop.AfterSaleTypeInsuredPrice:           model.AfsAppealTypeInsuredPrice,
		tiktokShop.AfterSaleTypeReissue:                model.AfsAppealTypeReissue,
	}
)

// convertAfsAppealType 抖音订单索赔状态转换为当前系统状态
func (c *PurchaseHandler) convertAfsAppealType(vendorAppealType int64) int8 {
	if status, ok := afsAppealTypeMap[vendorAppealType]; ok {
		return status
	}
	return 0
}

// 是否为售后消息
func (c *PurchaseHandler) isAfsMsg(msg string) bool {
	_, ok := AfsTagIDMap[msg]
	return ok
}

func (c *PurchaseHandler) OnAfsOrderMsg(msgId, orderId string, msg interface{}) (retVal *tiktokShop.CallbackResponse) {
	//jxutils.CallMsgHandlerAsync(func() {
	retVal = c.onAfsOrderMsg(msgId, msg)
	//}, jxutils.ComposeUniversalOrderID(orderId, model.VendorIDDD))
	return retVal
}

// todo 对于退款与部分退款，order.go与这个文件中对于状态的处理不一致
func (c *PurchaseHandler) onAfsOrderMsg(msgId string, msg interface{}) (retVal *tiktokShop.CallbackResponse) {
	var err error
	var db = dao.GetDB()
	orderStatus, vendorOrgCode := c.callbackAfsMsg2Status(msgId, msg)
	if orderStatus == nil {
		return tiktokShop.Err2CallbackResponse(nil, "")
	}
	needCallNew := orderStatus.Status == model.AfsOrderStatusWait4Approve || orderStatus.Status == model.AfsOrderStatusNew
	if !needCallNew {
		if _, err := partner.CurOrderManager.LoadAfsOrder(orderStatus.VendorOrderID, orderStatus.VendorID); err != nil {
			if dao.IsNoRowsError(err) {
				needCallNew = true
			} else {
				return tiktokShop.Err2CallbackResponse(err, "")
			}
		}
	}

	if needCallNew {
		var afsOrder *model.AfsOrder
		// 查询售后订单详情
		tiktokAfsOrderDetail, err := getAPI(utils.Int2Str(vendorOrgCode), 0, "").QueryAfsOrderDetail(orderStatus.VendorOrderID, false)
		if err != nil {
			return tiktokShop.Err2CallbackResponse(err, "")
		}

		if msgId == tiktokShop.CallbackRefundOrderMsgTagId || msgId == tiktokShop.CallbackUpdateRefundOrderMsgTagId { // 不存在的新订单
			afsOrder = &model.AfsOrder{
				VendorID:      model.VendorIDDD,
				AfsOrderID:    orderStatus.VendorOrderID,
				VendorOrderID: orderStatus.RefVendorOrderID,
				VendorStoreID: tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.StoreId,
				StoreID:       0,
				AfsCreatedAt:  orderStatus.StatusTime,

				VendorAppealType: utils.Int64ToStr(tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.AfterSaleStatus),
				AppealType:       c.convertAfsAppealType(tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.AfterSaleType),
				VendorReasonType: tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.Reason,
				ReasonType:       int8(tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.ReasonCode),
				ReasonDesc:       tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.ReasonRemark,
				ReasonImgList:    utils.LimitUTF8StringLen(strings.Join(tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.Evidence, ","), 1024),
				RefundType:       model.AfsTypeUnknown,
				VendorOrgCode:    utils.Int2Str(vendorOrgCode),
			}
			afsOrder.FreightUserMoney = tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.RefundPostAmount
			afsOrder.AfsFreightMoney = tiktokAfsOrderDetail.Data.ProcessInfo.AfterSaleInfo.RefundPostAmount // 暂时未发现退货取件费用
			afsOrder.BoxMoney = 0                                                                           // 餐盒费
			afsOrder.TongchengFreightMoney = 0                                                              // 同城配送费
			afsOrder.SkuBoxMoney = 0                                                                        // 商品包装费
			afsOrder.VendorStatus = orderStatus.VendorStatus                                                // 退货状态
			for _, sku := range tiktokAfsOrderDetail.Data.OrderInfo.SkuOrderInfos {
				orderSku := &model.OrderSkuFinancial{
					Count:             int(sku.AfterSaleItemCount),
					VendorSkuID:       utils.Int64ToStr(sku.SkuOrderId),
					SkuID:             utils.Str2Int(sku.ShopSkuCode),
					Name:              sku.ProductName,
					UserMoney:         sku.PayAmount,
					PmSkuSubsidyMoney: sku.PromotionAmount, // 平台补贴商品
				}

				afsOrder.PmSkuSubsidyMoney += orderSku.PmSkuSubsidyMoney
				afsOrder.SkuUserMoney += orderSku.UserMoney
				afsOrder.Skus = append(afsOrder.Skus, orderSku)
			}
		}
		if afsOrder != nil {
			//直接就来一个新的售后单，并且还是售后完成的
			if orderStatus.Status == model.AfsOrderStatusFinished {
				afsOrder.AfsFinishedAt = afsOrder.AfsCreatedAt
			}
			if msgId == tiktokShop.CallbackUpdateRefundOrderMsgTagId {
				_, err = dao.DeleteEntity(db, afsOrder, "VendorOrderID", "VendorID")
				afsOrder.Skus[0].VendorOrderID = afsOrder.VendorOrderID
				_, err = dao.DeleteEntity(db, afsOrder.Skus[0], "VendorOrderID")
			}
			err = partner.CurOrderManager.OnAfsOrderNew(afsOrder, orderStatus)
		}
	} else {
		if err2 := partner.CurOrderManager.OnAfsOrderStatusChanged(orderStatus); err2 == nil {
			if msgId == tiktokShop.CallbackRefundOrderSuccessMsgTagId || msgId == tiktokShop.CallbackReturnRefundAgreedMsgTagId {
				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 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, orderStatus.RefVendorOrderID, nil)
					for _, v := range wayBill {
						if v.Status != model.WaybillStatusCanceled {
							if handlerInfo := partner.GetDeliveryPlatformFromVendorID(v.WaybillVendorID); handlerInfo != nil {
								if err := handlerInfo.Handler.CancelWaybill(v, 0, "订单被取消了12"); err != nil {
									partner.CurOrderManager.OnOrderMsg(goodsOrder, "", fmt.Sprintf("抖店订单取消时,取消运单异常:%s", err.Error()))
								}
							}
						}
					}
				}

			}
		}

	}

	return tiktokShop.Err2CallbackResponse(err, "")
}

func (c *PurchaseHandler) callbackAfsMsg2Status(msgId string, msg interface{}) (orderStatus *model.OrderStatus, vendorOrgCode int) {
	switch msgId {
	case tiktokShop.CallbackRefundOrderMsgTagId: // 买家发起售后申请消息
		refundOrder := msg.(tiktokShop.BuyerRefundCreatedData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "create"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackRefundOrderMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.ApplyTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "买家发起售后回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}

		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	case tiktokShop.CallbackUpdateRefundOrderMsgTagId: // 买家修改售后申请消息
		refundOrder := msg.(tiktokShop.BuyerRefundModifiedData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "update"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackUpdateRefundOrderMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.ModifyTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "买家修改售后回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}

		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	case tiktokShop.CallbackRefundOrderSuccessMsgTagId: // 退款成功消息
		refundOrder := msg.(tiktokShop.BusinessRefundSuccessData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "refund_success"),
			Status:           c.GetAfsStatusFromVendorStatus(int(refundOrder.AftersaleType), tiktokShop.CallbackUpdateRefundOrderMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.SuccessTime)),
		}
		if k, ok := ReasonCodeMap[int(refundOrder.ReasonCode)]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "退款成功回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int64ToStr(refundOrder.ReasonCode)
		}
		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = int(refundOrder.ShopId)
		orderStatus = orderMsg
	case tiktokShop.CallbackRefundOrderRefuseMsgTagId: // 拒绝退款消息
		refundOrder := msg.(tiktokShop.BusinessNotRefundRefusedData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "refund_money_fail"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackUpdateRefundOrderMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.RefuseTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "拒绝退款回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}
		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	case tiktokShop.CallbackRefundShopMsgTagId: // 拒绝退货申请消息
		refundOrder := msg.(tiktokShop.BusinessNotReturnApplyRefusedData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "refuse_shop_fail"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackRefundShopMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.RefuseTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "拒绝退货回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}
		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	case tiktokShop.CallbackReturnApplyAgreedMsgTagId: // 同意退货申请消息
		refundOrder := msg.(tiktokShop.BusinessReturnApplyAgreedData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "refund_shop_success"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackReturnApplyAgreedMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.AgreeTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "同意退货回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}
		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	case tiktokShop.CallbackReturnRefundAgreedMsgTagId: // 同意退款消息
		refundOrder := msg.(tiktokShop.BusinessRefundAgreedData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "refund_money_success"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackReturnRefundAgreedMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.AgreeTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "同意退款消息,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}
		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	case tiktokShop.CallbackRefundClosedMsgTagId: // 取消售后
		refundOrder := msg.(tiktokShop.UserCancelRefundOrderData)
		orderMsg := &model.OrderStatus{
			VendorID:         model.VendorIDDD,
			OrderType:        model.OrderTypeAfsOrder,
			RefVendorOrderID: utils.Int64ToStr(refundOrder.PId),
			RefVendorID:      model.VendorIDDD,
			VendorStatus:     fmt.Sprintf("%s:%s", "order", "cancel_refund_afsOrder"),
			Status:           c.GetAfsStatusFromVendorStatus(refundOrder.AftersaleType, tiktokShop.CallbackRefundClosedMsgTagId),
			StatusTime:       utils.Timestamp2Time(int64(refundOrder.CloseTime)),
		}
		if k, ok := ReasonCodeMap[refundOrder.ReasonCode]; ok {
			orderMsg.Remark = k
		} else {
			orderMsg.Remark = "用户取消售后回调,抖音reason_code对应reason不足,需要更新.code:" + utils.Int2Str(refundOrder.ReasonCode)
		}
		if refundOrder.AftersaleId > 0 {
			orderMsg.VendorOrderID = utils.Int64ToStr(refundOrder.AftersaleId)
		} else {
			orderMsg.VendorOrderID = orderMsg.RefVendorOrderID
		}
		vendorOrgCode = refundOrder.ShopId
		orderStatus = orderMsg
	default:
		return nil, 0
	}

	return orderStatus, vendorOrgCode
}

func (c *PurchaseHandler) GetAfsStatusFromVendorStatus(resType int, notifyType string) int {
	status := AfsVendorStatus2StatusMap[notifyType]
	if status == model.AfsOrderStatusWait4Approve && resType == tiktokShop.AfterSaleStatusApply {
		status = model.AfsOrderStatusNew
	}
	return status
}
