package httpServer

import (
	config "common/configsYaml"
	"common/resultStatus"
	"common/utils"
	"common/webServer"
	"encoding/json"
	"fmt"
	"goutil/logUtilPlus"
	"goutil/stringUtil"
	"net/http"
	"strings"
)

// selfDefineMux
// @description: 定义自定义的Mux对象
type selfDefineMux struct {
}

// ServeHTTP
// @description: ServeHTTP
// parameter:
// @receiver mux: mux
// @w: w
// @r: r
// return:
func (mux *selfDefineMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	responseObj := webServer.GetInitResponseObj()
	defer utils.LogReqErrorRecover(r)

	// 判断是否是接口文档
	if strings.Contains(r.RequestURI, "Remarks") && r.Method == "GET" {
		remarkFunc(w, r)
		return
	}

	// 判断是否是POST方法
	if r.Method != "POST" {
		responseResult(w, responseObj.SetResultStatus(resultStatus.OnlySupportPOST))
		return
	}

	// 因为httpserver——面向外网client故屏蔽了webserver中的ip限制
	// 构造contex
	context, errMsg := NewApiContext(r, w, false)
	if errMsg != nil {
		// 输出结果
		responseResult(w, responseObj.SetResultStatus(resultStatus.APIDataError))
		return
	}

	// 根据路径选择不同的处理方法
	if handlerFunObj, exists := GetHandleFunc(r.RequestURI); exists {
		defer func() {
			if config.DEBUG {
				b, _ := json.Marshal(responseObj)
				msg := fmt.Sprintf("API:%v 请求数据：%v;返回数据：%s;",
					r.RequestURI, string(context.GetRequestBytes()), string(b))
				logUtilPlus.DebugLog(msg)
			}
		}()

		// 输出结果
		responseObj := handlerFunObj.HandleFun()(context)
		responseResult(w, responseObj)
		return
	}

	// 通过反射选择不同的方法
	strs := stringUtil.Split(r.RequestURI, []string{"/"})
	params, err := context.RequestDataBySlice2()
	if err != nil {
		responseResult(w, responseObj.SetResultStatus(resultStatus.APIDataError))
		return
	}
	resquestData := webServer.NewRequestObject(strs[1], strs[2], params)
	resp := CallFunction(resquestData)
	responseResult(w, resp)
}
