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/uuptapi"
	"git.rosy.net.cn/jx-callback/business/partner/delivery/uupt"
	"git.rosy.net.cn/jx-callback/globals/api"
	"github.com/astaxie/beego/server/web"
)

type UuPtController struct {
	web.Controller
}

var UUVendorStoreIDList = new(sync.Map)

//运单状态回调
func (c *UuPtController) UuWaybillCallback() {
	if c.Ctx.Input.Method() == http.MethodPost {
		resp, data, callbackResponse := api.UuAPI.WaybillCallback(c.Ctx.Request)
		if callbackResponse.ReturnCode == uuptapi.ReturnFail {
			c.Data["code"] = callbackResponse
			c.ServeJSON()
			return
		}

		if good, err := dao.GetSimpleOrder(dao.GetDB(), resp.OriginID); err == nil && good != nil {
			callbackResponse = uupt.OnWaybillMsg(resp, good)
		} else {
			switch web.BConfig.RunMode {
			case model.ServerTypeVegetable:
				callbackResponse = c.UuPtPush2FruitsOrPet(model.ServerTypeFruits, map[string]interface{}{"data": data})
			case model.ServerTypeFruits:
				callbackResponse = c.UuPtPush2FruitsOrPet(model.ServerTypePet, map[string]interface{}{"data": data})
			case model.ServerTypePet:
				return
			}
		}

		c.Data["code"] = callbackResponse
		c.ServeJSON()
	} else {
		c.Abort("404")
	}
}

func (c *UuPtController) UuPtPush2FruitsOrPet(serverType string, msg map[string]interface{}) *uuptapi.CallbackResponse {
	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/uuPt/uuWaybillCallback", strings.NewReader(utils.Map2URLValues(msg).Encode()))
	case model.ServerTypePet:
		request, err = http.NewRequest(http.MethodPost, "http://callback-gblm.jxc4.com/uuPt/uuWaybillCallback", strings.NewReader(utils.Map2URLValues(msg).Encode()))
	}
	if err != nil {
		return uuptapi.Err2CallbackResponse(err)
	}

	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 uuptapi.Err2CallbackResponse(err)
	}
	defer resp.Body.Close()
	byteData, _ := ioutil.ReadAll(resp.Body)
	result := uuptapi.CallbackResponse{}
	json.Unmarshal(byteData, &result)

	return &result
}
