package defsch

import (
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	push "git.rosy.net.cn/jx-callback/business/jxutils/unipush"
	"git.rosy.net.cn/jx-callback/business/jxutils/weixinmsg"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/msghub"
	"git.rosy.net.cn/jx-callback/business/partner"
	"git.rosy.net.cn/jx-callback/globals"
)

var (
	autoRejectSkuMap = map[int]int{
		33996: 1,
		33995: 1,
		33994: 1,
		33991: 1,
	}
)

func (s *DefScheduler) OnAfsOrderNew(order *model.AfsOrder, isPending bool) (err error) {
	if order.Status == model.AfsOrderStatusWait4Approve {
		if !isPending {
			if isAutoRejectAfsOrder(order) {
				if handler := partner.GetPurchaseOrderHandlerFromVendorID(order.VendorID); handler != nil {
					if err := handler.AgreeOrRefuseRefund(jxcontext.AdminCtx, order, partner.AfsApproveTypeRefused, "抱歉，蟹券不接受退货或换货"); err != nil {
						globals.SugarLogger.Debugf("OnAfsOrderNew, orderID:%s, afsOrderID:%s failed with err:%v", order.VendorOrderID, order.AfsOrderID, err)
					}
				}
			}
			msghub.OnNewWait4ApproveAfsOrder(order)
			weixinmsg.NotifyAfsOrderStatus(order)
			push.NotifyAfsOrder(order)
		}
	}
	return err
}

func (s *DefScheduler) OnAfsOrderStatusChanged(order *model.AfsOrder, status *model.OrderStatus, isPending bool) (err error) {
	if status.Status == model.AfsOrderStatusWait4ReceiveGoods {
		if !isPending {
			msghub.OnKeyAfsOrderStatusChanged(order)
			weixinmsg.NotifyAfsOrderStatus(order)
		}
	}
	return err
}

func isAutoRejectAfsOrder(order *model.AfsOrder) (isReject bool) {
	for _, v := range order.Skus {
		if autoRejectSkuMap[jxutils.GetSkuIDFromOrderSkuFinancial(v)] == 1 {
			isReject = true
			break
		}
	}
	return isReject
}
