package controllers

import (
	"encoding/json"
	"git.rosy.net.cn/baseapi/utils"
	"git.rosy.net.cn/jx-callback/business/model"
	"git.rosy.net.cn/jx-callback/business/model/dao"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"

	"git.rosy.net.cn/baseapi/platformapi/ebaiapi"
	"git.rosy.net.cn/jx-callback/business/partner/purchase/ebai"
	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
)

type EbaiController struct {
	web.Controller
}

var EBaiVendorStoreIDList = new(sync.Map)

func (c *EbaiController) Msg() {
	if c.Ctx.Input.Method() == http.MethodPost {
		obj, callbackResponse := api.EbaiAPI.GetCallbackMsg(c.Ctx.Request, web.BConfig.RunMode)
		if callbackResponse == nil {
			vendorStoreId, _ := utils.TryInterface2Int64(obj.Body["platform_shop_id"])
			if _, have := EBaiVendorStoreIDList.Load(vendorStoreId); vendorStoreId != 0 && !have {
				storeDetail, _ := dao.GetStoreDetailByVendorStoreID(dao.GetDB(), utils.Int64ToStr(vendorStoreId), model.VendorIDEBAI, "")
				if storeDetail == nil {
					switch web.BConfig.RunMode {
					case model.ServerTypeVegetable:
						callbackResponse = c.EBaiMsgPush2FruitsOrPet(model.ServerTypeFruits, utils.Struct2Map(obj, "", false))
					case model.ServerTypeFruits:
						callbackResponse = c.EBaiMsgPush2FruitsOrPet(model.ServerTypePet, utils.Struct2Map(obj, "", false))
					case model.ServerTypePet:
						callbackResponse = api.EbaiAPI.Err2CallbackResponse(ebaiapi.GetCmd(c.Ctx.Request), nil, nil) // api.EbaiAPI.Err2CallbackResponse(ebaiapi.GetCmd(c.Ctx.Request), fmt.Errorf("饿了么菜市推果园,果园退超市未找到门店cmd:%s,storeId:%s", obj.Cmd, vendorStoreId), nil)
					}
					c.Data["json"] = callbackResponse
					c.ServeJSON()
					return
				} else {
					EBaiVendorStoreIDList.Store(vendorStoreId, model.YES)
				}
			}
			callbackResponse = ebai.OnCallbackMsg(obj)
		}
		if callbackResponse == nil {
			callbackResponse = api.EbaiAPI.Err2CallbackResponse(ebaiapi.GetCmd(c.Ctx.Request), nil, nil)
		}
		c.Data["json"] = callbackResponse
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *EbaiController) EBaiMsgPush2FruitsOrPet(serverType string, msg map[string]interface{}) *ebaiapi.CallbackResponse {
	msgBody, _ := json.Marshal(msg["body"])
	msg["body"] = string(msgBody)
	cl := http.Client{}
	var request *http.Request
	var err error
	switch serverType {
	case model.ServerTypeFruits:
		request, err = http.NewRequest(http.MethodPost, "http://callback-jxgy.jxc4.com/ebai/msg", strings.NewReader(utils.Map2URLValues(msg).Encode()))
	case model.ServerTypePet:
		request, err = http.NewRequest(http.MethodPost, "http://callback-gblm.jxc4.com/ebai/msg", strings.NewReader(utils.Map2URLValues(msg).Encode()))
	}
	if err != nil {
		return api.EbaiAPI.Err2CallbackResponse(ebaiapi.GetCmd(c.Ctx.Request), err, nil)
	}

	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("accept", "application/json, text/plain, */*")
	resp, err := cl.Do(request)
	if err != nil {
		return api.EbaiAPI.Err2CallbackResponse(ebaiapi.GetCmd(c.Ctx.Request), err, nil)
	}
	defer resp.Body.Close()
	byteData, _ := ioutil.ReadAll(resp.Body)
	result := ebaiapi.CallbackResponse{}
	json.Unmarshal(byteData, &result)

	return &result
}
