package tiktok_store

import (
	"encoding/json"
	tiktokShop "git.rosy.net.cn/baseapi/platformapi/tiktok_shop/tiktok_api"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/jxutils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"git.rosy.net.cn/jx-callback/globals"
	"git.rosy.net.cn/jx-callback/globals/api"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

// 同一账号下,菜市消息推送到果园
const (
	CaiShiPushGyTagOrder            = "order"          // 订单
	CaiShiPushGyTagToken            = "token"          // 授权
	CaiShiPushGyTagDeliveryRegister = "delivery"       // 配送注册查询
	CaiShiPushGyTagDeliveryDetail   = "deliveryDetail" // 配送详情
	CaiShiPushGyTagWayBill          = "waybill"        // 配送
)

var TiktokVendorStoreID = make(map[string]string, 0)

// OnOrderMsg 抖音
func OnOrderMsg(msgId string, msg interface{}) (response *tiktokShop.CallbackResponse) {
	if CurPurchaseHandler != nil {
		orderId, shopId, _ := api.TiktokStore.GetCallbackOrderId(msgId, msg)
		if shopId == 53802960 {
			return tiktokShop.Err2CallbackResponse(nil, "")
		}
		orderDetail, err := GetTiktokApi(utils.Int64ToStr(shopId), 0, "").GetTiktokOrderDetail(orderId)
		if err != nil {
			return tiktokShop.Err2CallbackResponse(err, "")
		}
		vendorStoreID := orderDetail.SkuOrderList[0].StoreInfo.StoreId

		if _, ok := TiktokVendorStoreID[vendorStoreID]; !ok {
			storeDetail, _ := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), vendorStoreID, model.VendorIDDD, "")
			if storeDetail == nil || storeDetail.Store.ID == 0 {
				gyMsg := map[string]interface{}{"tag": msgId, "msg_id": utils.Int64ToStr(time.Now().Unix()) + msgId, "data": msg}
				if shopId == 68023619 {
					gyResult, err := HttpToGuoYuan(gyMsg, CaiShiPushGyTagOrder, model.ServerTypePet)
					if err != nil {
						return tiktokShop.Err2CallbackResponse(err, "")
					}
					result, _ := ioutil.ReadAll(gyResult.Body)
					var guoYuan *tiktokShop.CallbackResponse
					if err2 := json.Unmarshal(result, guoYuan); err2 != nil {
						return tiktokShop.Err2CallbackResponse(err2, "")
					}
					return guoYuan
				}
				//switch beego.BConfig.RunMode {
				//case model.ServerTypeFruits:
				//	// 当前订单所属门店不属于菜市时,将消息推送到果园
				//	gyResult, err := HttpToGuoYuan(gyMsg, CaiShiPushGyTagOrder, model.ServerTypePet)
				//	if err != nil {
				//		return tiktokShop.Err2CallbackResponse(err, "")
				//	}
				//	result, _ := ioutil.ReadAll(gyResult.Body)
				//	var guoYuan *tiktokShop.CallbackResponse
				//	if err2 := json.Unmarshal(result, guoYuan); err2 != nil {
				//		return tiktokShop.Err2CallbackResponse(err2, "")
				//	}
				//	return guoYuan
				//case model.ServerTypeVegetable:
				//	// 当前订单所属门店不属于菜市时,将消息推送到果园
				//	gyResult, err := HttpToGuoYuan(gyMsg, CaiShiPushGyTagOrder, model.ServerTypeFruits)
				//	if err != nil {
				//		return tiktokShop.Err2CallbackResponse(err, "")
				//	}
				//	result, _ := ioutil.ReadAll(gyResult.Body)
				//	var guoYuan *tiktokShop.CallbackResponse
				//	if err2 := json.Unmarshal(result, guoYuan); err2 != nil {
				//		return tiktokShop.Err2CallbackResponse(err2, "")
				//	}
				//	return guoYuan
				//case model.ServerTypePet:
				//	return nil
				//}
			} else {
				TiktokVendorStoreID[vendorStoreID] = "1"
			}
		}
		jxutils.CallMsgHandler(func() {
			response = CurPurchaseHandler.onOrderMsg(msgId, orderId, msg)
		}, jxutils.ComposeUniversalOrderID(orderId, model.VendorIDDD))
	} else {
		globals.SugarLogger.Debugf("============2")
	}
	return response
}

// HttpToGuoYuan 暂时还未开通果园和宠物的抖音
func HttpToGuoYuan(param map[string]interface{}, requestType string, serverType string) (*http.Response, error) {
	var paramData []byte
	var err error
	if requestType == "order" || requestType == "waybill" {
		param["data"] = utils.Format4Output(param["data"], false)
		paramData, err = json.Marshal([]interface{}{param})
		if err != nil {
			return nil, err
		}
	} else {
		paramData, err = json.Marshal(param)
		if err != nil {
			return nil, err
		}
	}
	body := strings.NewReader(string(paramData))
	url := ""
	if serverType == model.ServerTypeFruits {
		switch requestType {
		case CaiShiPushGyTagOrder: // 订单相关
			url = "http://callback-jxgy.jxc4.com/tiktok/callbackTiktokOrderMsg"
		case CaiShiPushGyTagToken: // 授权相关
			url = "http://callback-jxgy.jxc4.com/tiktokShop/jxcsToGyTiktokToken"
		case CaiShiPushGyTagDeliveryRegister: // 配送查询注册
			url = "http://callback-jxgy.jxc4.com/logistics/logisticsRegister"
		case CaiShiPushGyTagDeliveryDetail: // 配送查询详情
			url = "http://callback-jxgy.jxc4.com/logistics/logisticsQuery"
		case CaiShiPushGyTagWayBill: // 运单消息
			url = "http://callback-jxgy.jxc4.com/tiktok/callbackTiktokOrderMsg"
		}
	} else if serverType == model.ServerTypePet {
		switch requestType {
		case CaiShiPushGyTagOrder: // 订单相关
			url = "http://callback-gblm.jxc4.com/tiktok/callbackTiktokOrderMsg"
		case CaiShiPushGyTagToken: // 授权相关
			url = "http://callback-gblm.jxc4.com/tiktokShop/jxcsToGyTiktokToken"
		case CaiShiPushGyTagDeliveryRegister: // 配送查询注册
			url = "http://callback-gblm.jxc4.com/logistics/logisticsRegister"
		case CaiShiPushGyTagDeliveryDetail: // 配送查询详情
			url = "http://callback-gblm.jxc4.com/logistics/logisticsQuery"
		case CaiShiPushGyTagWayBill: // 运单消息
			url = "http://callback-gblm.jxc4.com/tiktok/callbackTiktokOrderMsg"
		}
	}

	httpReq, err := http.NewRequest(http.MethodPost, url, body)
	if err != nil {
		return nil, err
	}

	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("accept", "application/json, text/plain, */*")

	httpRes, err := http.DefaultClient.Do(httpReq)
	defer httpRes.Body.Close()
	if err != nil {
		return nil, err
	}

	return httpRes, err
}
