package mtwm

import (
	"encoding/json"
	"net/http"
	"strings"

	"git.rosy.net.cn/jx-callback/business/partner/im"

	"git.rosy.net.cn/baseapi/platformapi/mtwmapi"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/jxutils/jxcontext"
	"git.rosy.net.cn/jx-callback/business/jxutils/netprinter"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
)

// 美团回调接口
func OnCallbackMsg(msg *mtwmapi.CallbackMsg, msgType string) (response *mtwmapi.CallbackResponse) {
	// 获取平台门店id
	//_, err := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), GetVendorStoreIDFromMsg(msg), model.VendorIDMTWM, GetVendorAppIdFromMsg(msg))
	//if err != nil && strings.Contains(err.Error(), "no row found") {
	//	forwardOrderToGy(msg, msgType)
	//	return mtwmapi.SuccessResponse
	//}
	if CurPurchaseHandler != nil {
		if msg.Cmd == mtwmapi.MsgTypeStoreStatusChanged || msg.Cmd == mtwmapi.MsgTypeStoreAuditStatusChanged {
			response = CurPurchaseHandler.onStoreStatusChanged(msg)
		} else if msg.Cmd == mtwmapi.MsgTypePrivateNumberDowngrade {
			response = CurPurchaseHandler.onNumberDowngrade(msg)
		} else if msg.Cmd == mtwmapi.MsgTypeStoreBind {
			// 门店授权发生变化 17,失去授权
			vendorStoreID := msg.FormData.Get("app_poi_code")
			storeDetail, _ := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), vendorStoreID, model.VendorIDMTWM, "")
			_, err := netprinter.PrintStoreStatus(jxcontext.AdminCtx, storeDetail, model.VendorIDMTWM, -9)
			response = mtwmapi.Err2CallbackResponse(err, "")
		} else {
			if orderID := GetOrderIDFromMsg(msg); orderID != "" {
				jxutils.CallMsgHandler(func() {
					switch msg.Cmd {
					case mtwmapi.MsgTypeWaybillStatus:
						response = CurPurchaseHandler.onWaybillMsg(msg)
					default:
						response = CurPurchaseHandler.onOrderMsg(msg)
					}
				}, jxutils.ComposeUniversalOrderID(orderID, model.VendorIDMTWM))
			}
			/*if msg.Cmd == mtwmapi.MsgTypeOrderRefund || msg.Cmd == mtwmapi.MsgTypeOrderPartialRefund {
				utils.CallFuncAsync(func() {
					OnFinancialMsg(msg)
				})
			} */
		}
	}
	return response
}

func GetOrderIDFromMsg(msg *mtwmapi.CallbackMsg) string {
	return msg.FormData.Get(mtwmapi.KeyOrderID)
}

func GetVendorStoreIDFromMsg(msg *mtwmapi.CallbackMsg) string {
	return msg.FormData.Get(mtwmapi.KeyAppPoiCode)
}

func GetVendorAppIdFromMsg(msg *mtwmapi.CallbackMsg) string {
	return msg.FormData.Get(mtwmapi.KeyAppID)
}

func forwardOrderToGy(msg *mtwmapi.CallbackMsg, msgType string) {
	cl := http.Client{}
	callbackUrl := GetMsgCallBackUrl(msgType, msg.AppID)
	request, err := http.NewRequest(http.MethodPost, "http://callback-jxgy.jxc4.com/mtwm/"+callbackUrl, strings.NewReader(msg.FormData.Encode()))
	if err != nil {
		return
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	cl.Do(request)
}

func GetMsgCallBackUrl(msgType, appId string) string {
	interfaceUrl := ""
	switch msgType {
	case mtwmapi.MsgTypeWaybillStatus:
		interfaceUrl = "/waybillStatus"
	case mtwmapi.MsgTypeNewOrder:
		interfaceUrl = "/newOrder"
	case mtwmapi.MsgTypeOrderAccepted:
		interfaceUrl = "/orderAccepted"
	case mtwmapi.MsgTypeOrderFinished:
		interfaceUrl = "/orderFinished"
	case mtwmapi.MsgTypeOrderFinancial:
		interfaceUrl = "/orderFinancial"
	case mtwmapi.MsgTypeOrderCanceled:
		interfaceUrl = "/orderCanceled"
	case mtwmapi.MsgTypeUserUrgeOrder:
		interfaceUrl = "/userUrgeOrder"
	case mtwmapi.MsgTypePrivateNumberDowngrade:
		interfaceUrl = "/numberDowngrade"
	case mtwmapi.MsgTypeOrderModified:
		interfaceUrl = "/orderModified"
	case mtwmapi.MsgTypeOrderRefund:
		interfaceUrl = "/orderRefund"
	case mtwmapi.MsgTypeOrderPartialRefund:
		interfaceUrl = "/orderPartialRefund"
	case mtwmapi.MsgTypeOrderFinishedPickup:
		interfaceUrl = "/orderFinishedPickup"
	case mtwmapi.MsgTypeStoreStatusChanged:
		interfaceUrl = "/storeStatusChanged"
	case mtwmapi.MsgTypeStoreAuditStatusChanged:
		interfaceUrl = "/storeAuditStatusChanged"
	case mtwmapi.MsgTypeSkuDelete:
		interfaceUrl = "/skuDelete"
	case mtwmapi.MsgTypeStoreBind:
		interfaceUrl = "/storeBind"
	default:
		globals.SugarLogger.Errorf("美团超市[app_id :=%s ,callbackUrl := %s ]回调推送到果园错误,回调地址不正确", appId, msgType)
	}
	return interfaceUrl
}

// OnImMsg  im消息回调
func OnImMsg(msg *mtwmapi.ImCallbackMsg) (response *mtwmapi.CallbackResponse) {
	if str, err := json.Marshal(msg.PushContent); err == nil {
		err = im.ReadMsgFromVendor(model.VendorIDMTWM, "", str)
		if err != nil {
			globals.SugarLogger.Debugf("OnImMsg提示：%v", err)
		}
	}
	return mtwmapi.SuccessResponse
}
