package mtwm

import (
	"encoding/json"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/partner/im"
	beego "github.com/astaxie/beego/server/web"
	"net/http"
	"strings"

	"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) {
	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)
}

// OnImMsg  im消息回调
func OnImMsg(msg *mtwmapi.ImCallbackMsg) (response *mtwmapi.CallbackResponse) {
	if str, err := json.Marshal(msg.PushContent); err == nil {
		var PushContentReq = mtwmapi.PushContentReq{}
		if err = json.Unmarshal(str, &PushContentReq); err != nil {
			return mtwmapi.SignatureIsNotOk
		}
		storeDetail, err2 := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), PushContentReq.AppPoiCode, model.VendorIDMTWM, utils.Int2Str(PushContentReq.AppID))
		if err2 != nil || storeDetail == nil {
			switch beego.BConfig.RunMode {
			case model.ServerTypeFruits:
				pushIMToGyOrPet(msg, model.ServerTypePet)
				return mtwmapi.SuccessResponse
			case model.ServerTypeVegetable:
				pushIMToGyOrPet(msg, model.ServerTypeFruits)
				return mtwmapi.SuccessResponse
			}
		}

		err = im.ReadMsgFromVendor(model.VendorIDMTWM, "", str)
		if err != nil {
			globals.SugarLogger.Debugf("OnImMsg提示：%v", err)
			return mtwmapi.SignatureIsNotOk
		}
	}
	return mtwmapi.SuccessResponse
}

func pushIMToGyOrPet(msg *mtwmapi.ImCallbackMsg, serverType string) {
	var (
		cl      = http.Client{}
		request = &http.Request{}
		err     error
	)
	params := make(map[string]interface{})
	params["timestamp"] = msg.Timestamp
	params["sign"] = msg.Sig
	params["app_id"] = msg.AppID
	params["biz_type"] = msg.BizType
	params["push_content"] = msg.PushContent

	switch serverType {
	case model.ServerTypeFruits:
		request, err = http.NewRequest(http.MethodPost, "http://callback-jxgy.jxc4.com/mtwm/iMCallback", strings.NewReader(utils.Map2URLValues(params).Encode()))
		if err != nil {
			return
		}
	case model.ServerTypePet:
		request, err = http.NewRequest(http.MethodPost, "http://callback-gblm.jxc4.com/mtwm/iMCallback", strings.NewReader(utils.Map2URLValues(params).Encode()))
		if err != nil {
			return
		}
	}

	request.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	cl.Do(request)
}
