package handler

import (
	"DataShare/dao"
	"DataShare/global"
	"DataShare/middleware"
	"DataShare/model"
	"DataShare/service"
	"DataShare/service/api_proxy"
	"DataShare/util/response"
	"encoding/json"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"time"
)

func OutApi_RouteInit(Router *gin.RouterGroup){
	//mibRouter := Router.Use(middleware.TokenAuthMiddleware())
	outRouter := Router
	{
		//测试
		outRouter.POST("authorize", authorize)
		outRouter.POST("apiCall", apiCall)

		outRouter.Any("proxyToService/any/:key",apiProxyToService)
		outRouter.Any("proxyToData/any/:key",apiProxyToData)
	}
}

func OutApi_RouteServiceInit(Router *gin.RouterGroup){
	outRouter := Router
	outRouter.Any("any/:key",apiProxyToService)
}

func OutApi_RouteDataInit(Router *gin.RouterGroup){
	outRouter := Router
	outRouter.Any("any/:key",apiProxyToData)

	//outRouter.Any("proxyToService/any/:key",apiProxyToService)
	//outRouter.Any("proxyToData/any/:key",apiProxyToData)
}


func OutApi_RouteInit2(Router *gin.RouterGroup){
	outRouter := Router.Use(middleware.TokenAuthMiddleware())
	//outRouter := Router
	{
		outRouter.POST("refreshToken", refreshToken)
		outRouter.Any("any/:key",any)

	}
}

// @Tags 第三方接口服务-应用鉴权
// @Summary 应用鉴权
// @Description 应用鉴权
// @Accept application/json
// @Produce application/json
// @Param connect body model.LoginRequest true "json"
// @Success 200 {object} model.ResponseToken "{"code": 0, "msg": "xxx", data:{}}"
// @Router /dxp/outapi/authorize [post]
func authorize(c *gin.Context){
	//先判断服务器授权
	ret,_,err := dao.Empower_GetInstance().GetLiceneseLeftDays()
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	if ret == false {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	var param model.LoginRequest
	if err := c.ShouldBindJSON(&param); err != nil {
		response.FailWithMessage("invalid json provided",c,"JSON")
		return
	}

	if global.SystemLogger.Level > logrus.DebugLevel {
		request_body,_ := json.Marshal(&param)
		defer c.Set("params",string(request_body))
	}

	result,err := service.UserLogin(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}

	response.OkWithData(result,c,"JSON")
}

// @Tags 第三方接口服务-动态刷新token
// @Summary 动态刷新token
// @Description 动态刷新token
// @Accept application/json
// @Produce application/json
// @Param connect body model.RefreshTokenRequest true "json"
// @Success 200 {object} model.ResponseToken "{"code": 0, "msg": "xxx", data:{}}"
// @Router /dxp/outapi/refreshToken [post]
func refreshToken(c *gin.Context){

	var param model.RefreshTokenRequest
	if err := c.ShouldBindJSON(&param); err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	refreshToken := param.RefreshToken

	//verify the token
	token, err := jwt.Parse(refreshToken, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(global.SystemConfig.Jwt.Signkey), nil
	})
	//if there is an error, the token must have expired
	if err != nil {
		response.FailWithMessage("Refresh token expired:"+err.Error(),c,"JSON")
		return
	}
	//is token valid?
	if _, ok := token.Claims.(jwt.Claims); !ok && !token.Valid {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	//Since token is valid, get the uuid:
	claims, ok := token.Claims.(jwt.MapClaims) //the token claims should conform to MapClaims
	if ok && token.Valid {
		refreshUuid, ok := claims["refresh_uuid"].(string) //convert the interface to string
		if !ok {
			response.FailWithMessage("refresh uuid failed.",c,"JSON")
			return
		}

		appId, appIdOk := claims["appId"].(string)
		if appIdOk == false {
			response.FailWithMessage("appid failed.",c,"JSON")
			return
		}
		appSecret, appSecretOk := claims["appSecret"].(string)
		if appSecretOk == false {
			response.FailWithMessage("appSecret failed.",c,"JSON")
			return
		}
		//Delete the previous Refresh Token
		delErr := dao.DeleteRefresh(refreshUuid)
		if delErr != nil { //if any goes wrong
			response.FailWithMessage(err.Error(),c,"JSON")
			return
		}
		//需要检查一下certKey是否已经过期?
		//如果过期了，不应该生成新的token！
		//todo：
		ts, err := middleware.CreateToken(appId,appSecret)
		if err != nil {
			response.FailWithMessage("create token failed",c,"JSON")
			return
		}
		// save token to redis
		uidValue := model.UuidValue{
			AppId: appId,
			AppSecret: appSecret,
		}
		jsonUidValue,_ := json.Marshal(&uidValue)
		err = dao.CreateAuth(string(jsonUidValue), ts)
		if err != nil {
			response.FailWithMessage(err.Error(),c,"JSON")
			return
		}

		result := model.ResponseToken{
			AccessToken:  ts.AccessToken,
			RefreshToken: ts.RefreshToken,
			ExpiresAt:    ts.AtExpires,
		}

		response.OkWithData(result,c,"JSON")
	} else {
		response.FailWithMessage("refresh expired",c,"JSON")
	}
}

// @Tags 第三方接口服务-数据库资源数据查询
// @Summary 数据库资源数据查询
// @Description 数据库资源数据查询
// @Accept application/json
// @Produce application/json
// @Param connect body model.RequestBody true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{}}"
// @Router /dxp/outapi/any/:key [post]
func any(c *gin.Context){

	call_log := &model.CallLog{
		AccessId:     "",
		CallDuration: 0,
		CallIp:       c.ClientIP(),
		CallResult:   "2",
		RequestParam: "",
		RequestUrl:   "",
		ReturnParam:  "",
	}
	//defer service.CallLog("http://1.116.36.127:9001/system/quantity/calllog",call_log)
	defer service.CallLog(global.SystemConfig.Log.CallLogUrl,call_log)
	key := c.Param("key")
	if len(key) <= 0 {
		response.FailWithMessage("invalid key",c,"JSON")
		return
	}
	call_log.AccessId = key
	resType,serviceInfo,dataInfo, err := service.Business2_GetAccessInfo(key)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	call_log.RequestUrl = "/dxp/outapi/any/"+key


	start := time.Now()

	if resType == "Service"{

		if serviceInfo.DayLimit > 0 {
			cnt := dao.GetApiCallCount(serviceInfo.AccessId)
			if cnt > serviceInfo.DayLimit {
				response.FailWithMessage("超出单日调用最大次数!",c,serviceInfo.Format)
				return
			}
			dao.IncApiCallCount(serviceInfo.AccessId)
		}
		request_body,_:=ioutil.ReadAll(c.Request.Body)

		//request_body,_ := json.Marshal(&param)
		if global.SystemLogger.Level > logrus.DebugLevel {
			defer c.Set("params",string(request_body))
		}
		call_log.RequestParam = string(request_body)

		fmt.Println("accesskey:",key)
		fmt.Println("request url:",serviceInfo.ResData.ServiceUrl)
		fmt.Println("request param",string(request_body))

		userReq := make(map[string]interface{},0)
		if len(request_body) > 0 {
			err := json.Unmarshal(request_body, &userReq)
			if err != nil {
				global.SystemLogger.Log(logrus.ErrorLevel,"请求参数格式不对，JSON转换失败：", err)
				response.FailWithMessage(err.Error(),c,serviceInfo.Format)
				return
			}
		}
		//拼接内置参数
		search := ""
		if userReq["search"] != nil {
			search = userReq["search"].(string)
		}
		if serviceInfo.ResData.FixParams != nil && len(*serviceInfo.ResData.FixParams) > 0 {
			if len(search) == 0 {
				userReq["search"] = *serviceInfo.ResData.FixParams
			}else{
				//将search 参数和 fixparams 参数组装在一起
				searchMap := make(map[string]interface{},0)
				err := json.Unmarshal([]byte(search),&searchMap)
				if err != nil {
					global.SystemLogger.Log(logrus.ErrorLevel,"fix参数格式不对，JSON转换失败：", err)
					response.FailWithMessage(err.Error(),c,serviceInfo.Format)
					return
				}
				fixReq := make(map[string]interface{},0)
				err = json.Unmarshal([]byte(*serviceInfo.ResData.FixParams), &fixReq)
				if err != nil {
					global.SystemLogger.Log(logrus.ErrorLevel,"fix参数格式不对，JSON转换失败：", err)
					response.FailWithMessage(err.Error(),c,serviceInfo.Format)
					return
				}
				for k,v := range fixReq {
					searchMap[k] = v
				}

				newSearch, err := json.Marshal(searchMap)
				if err != nil {
					global.SystemLogger.Log(logrus.ErrorLevel,"请求参数格式不对，JSON转换失败：", err)
					response.FailWithMessage(err.Error(),c,serviceInfo.Format)
					return
				}
				userReq["search"] = string(newSearch)
			}

		}


		newReq, err := json.Marshal(userReq)
		if err != nil {
			global.SystemLogger.Log(logrus.ErrorLevel,"请求参数格式不对，JSON转换失败：", err)
			response.FailWithMessage(err.Error(),c,serviceInfo.Format)
			return
		}

		mapData,byteData,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(serviceInfo.ResData.ServiceUrl,newReq)
		if serviceInfo.ResData.AuthWay == "gov" {
			mapData,byteData,err = api_proxy.GovDataFormatToResource(byteData)
		}

		duration := time.Since(start)
		call_log.CallDuration = duration.Milliseconds()
		if err != nil {
			response.FailWithMessage(err.Error(),c,serviceInfo.Format)
			call_log.ReturnParam = err.Error()
			return
		}
		if serviceInfo.ResData.ResponseForm != "standard"{
			response.OkWithData(mapData,c,serviceInfo.Format)
			call_log.ReturnParam = string(byteData)
		}else{
			out,err := service.Business2_Cq119NormalApiVerify(byteData,serviceInfo)

			if err != nil {
				response.FailWithMessage(err.Error(),c,serviceInfo.Format)
				return
			}

			response.OkWithData(out,c,serviceInfo.Format)

			//c.JSON(http.StatusOK, *out)

			v, err := json.Marshal(*out)
			if err == nil {
				call_log.ReturnParam = string(v)
			}
		}

		//result,err := api_proxy.CQ119_GetInstance().CQ119_ApiRequest("http://dam.cq119.gov.cn:9528/admin-ht/api/resource/dapi/yzzcptcs/1/0483b954d71c30163a966146af74ccfd",&api_proxy.CQ119RequestBody{
		//	Page:      1,
		//	Size:      10,
		//	Search:    "{}",
		//	RowIdOnly: 0,
		//})
	}else if resType == "Data"{

		if dataInfo.DayLimit > 0 {
			cnt := dao.GetApiCallCount(dataInfo.AccessId)
			if cnt > dataInfo.DayLimit {
				response.FailWithMessage("超出单日调用最大次数!",c,dataInfo.Format)
				return
			}
			dao.IncApiCallCount(dataInfo.AccessId)
		}

		var param model.DbQuery
		if err := c.ShouldBindJSON(&param); err != nil {
			response.FailWithMessage("invalid json param",c,dataInfo.Format)
			return
		}
		request_body,_ := json.Marshal(&param)
		if global.SystemLogger.Level > logrus.DebugLevel {
			defer c.Set("params",string(request_body))
		}
		call_log.RequestParam = string(request_body)

		fmt.Println(key)
		fmt.Println(param)

		result, err := service.Business2_QueryTable(&param,dataInfo)
		if err != nil {
			response.FailWithMessage(err.Error(),c,dataInfo.Format)
			return
		}

		response.OkWithData(result,c,dataInfo.Format)

		duration := time.Since(start)
		call_log.CallDuration = duration.Microseconds()
		v, err := json.Marshal(result)
		if err == nil {
			call_log.ReturnParam = string(v)
		}
	}
	call_log.CallResult = "1"

}

func any2(c *gin.Context){

	key := c.Param("key")
	if len(key) <= 0 {
		response.FailWithMessage("invalid key",c,"JSON")
		return
	}

	var param model.RequestBody
	if err := c.ShouldBindJSON(&param); err != nil {
		response.FailWithMessage("invalid json param",c,"JSON")
		return
	}
	if global.SystemLogger.Level > logrus.DebugLevel {
		request_body,_ := json.Marshal(&param)
		defer c.Set("params",string(request_body))
	}
	fmt.Println(key)
	fmt.Println(param)
	if len(key) < 0 {
		response.FailWithMessage("invalid access key value.",c,"JSON")
		return
	}
	result,err := api_proxy.CQ119_GetInstance().CQ119_ApiRequest("http://dam.cq119.gov.cn:9528/admin-ht/api/resource/dapi/yzzcptcs/1/0483b954d71c30163a966146af74ccfd",&api_proxy.CQ119RequestBody{
		Page:      1,
		Size:      10,
		Search:    "{}",
		RowIdOnly: 0,
	})

	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}

	response.OkWithData(result,c,"JSON")
}

// @Tags 第三方接口服务-服务测试接口
// @Summary 服务测试接口
// @Description 服务测试接口
// @Accept application/json
// @Produce application/json
// @Param connect body model.ApiTranslateRequest true "json"
// @Success 200 {object} map[string]interface{} "{"code": 0, "msg": "xxx", data:{}}"
// @Router /dxp/outapi/base/apiCall [post]
func apiCall(c *gin.Context){

	var param model.ApiTranslateRequest
	if err := c.ShouldBindJSON(&param); err != nil {
		response.FailWithMessage("invalid json param",c,"JSON")
		return
	}
	if global.SystemLogger.Level > logrus.DebugLevel {
		request_body,_ := json.Marshal(&param)
		defer c.Set("params",string(request_body))
	}

	if param.AuthWay == "gov"{
		_,byteData,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(param.ServiceUrl,[]byte(param.RequestParam))
		if err != nil {
			response.FailWithMessage("call api failed.",c,"JSON")
			return
		}
		mapData,_,err := api_proxy.GovDataFormatToResource(byteData)
		if err != nil {
			response.FailWithMessage(fmt.Sprintf("gov data swap to cq119 format failed.err:%s",err.Error()),c,"JSON")
			return
		}
		response.OkWithData(mapData,c,"JSON")
	}else if param.AuthWay == "119"{
		result,_,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(param.ServiceUrl,[]byte(param.RequestParam))
		if err != nil {
			response.FailWithMessage("call api failed.",c,"JSON")
			return
		}
		response.OkWithData(result,c,"JSON")
	}
}

// @Tags 巨衍接口-数据库资源数据查询
// @Summary 数据库资源数据查询
// @Description 数据库资源数据查询
// @Accept application/json
// @Produce application/json
// @Param connect body model.RequestBody true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{}}"
// @Router /dxp/outapi/base/proxyToData/any/:key [post]
func apiProxyToData(c *gin.Context){

	call_log := &model.CallLog{
		AccessId:     "",
		CallDuration: 0,
		CallIp:       c.ClientIP(),
		CallResult:   "2",
		RequestParam: "",
		RequestUrl:   "",
		ReturnParam:  "",
	}
	//defer service.CallLog("http://1.116.36.127:9001/system/quantity/calllog",call_log)
	defer service.CallLog(global.SystemConfig.Log.CallLogUrl,call_log)
	key := c.Param("key")
	if len(key) <= 0 {
		response.FailWithMessage("invalid key",c,"JSON")
		return
	}
	call_log.AccessId = key
	resType,_,dataInfo, err := service.Business2_GetAccessInfo(key)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	call_log.RequestUrl = "/dxp/outapi/proxyToData/any/"+key


	start := time.Now()

	if resType == "Data"{

		if dataInfo.DayLimit > 0 {
			cnt := dao.GetApiCallCount(dataInfo.AccessId)
			if cnt > dataInfo.DayLimit {
				response.FailWithMessage("超出单日调用最大次数!",c,dataInfo.Format)
				return
			}
			dao.IncApiCallCount(dataInfo.AccessId)
		}

		var param model.DbQuery
		if err := c.ShouldBindJSON(&param); err != nil {
			response.FailWithMessage("invalid json param",c,dataInfo.Format)
			return
		}
		request_body,_ := json.Marshal(&param)
		if global.SystemLogger.Level > logrus.DebugLevel {
			defer c.Set("params",string(request_body))
		}
		call_log.RequestParam = string(request_body)

		fmt.Println(key)
		fmt.Println(param)

		result, err := service.Business2_QueryTable(&param,dataInfo)
		if err != nil {
			response.FailWithMessage(err.Error(),c,dataInfo.Format)
			return
		}

		response.OkWithData(result,c,dataInfo.Format)

		duration := time.Since(start)
		call_log.CallDuration = duration.Microseconds()
		v, err := json.Marshal(result)
		if err == nil {
			call_log.ReturnParam = string(v)
		}
	}
	call_log.CallResult = "1"

}

// @Tags 巨衍接口-接口服务资源数据查询
// @Summary 接口服务资源数据查询
// @Description 接口服务资源数据查询
// @Accept application/json
// @Produce application/json
// @Param connect body model.RequestBody true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{}}"
// @Router /dxp/outapi/base/proxyToService/any/:key [post]
func apiProxyToService(c *gin.Context){

	call_log := &model.CallLog{
		AccessId:     "",
		CallDuration: 0,
		CallIp:       c.ClientIP(),
		CallResult:   "2",
		RequestParam: "",
		RequestUrl:   "",
		ReturnParam:  "",
	}
	//defer service.CallLog("http://1.116.36.127:9001/system/quantity/calllog",call_log)
	defer service.CallLog(global.SystemConfig.Log.CallLogUrl,call_log)
	key := c.Param("key")
	if len(key) <= 0 {
		response.FailWithMessage("invalid key",c,"JSON")
		return
	}
	call_log.AccessId = key
	resType,serviceInfo,dataInfo, err := service.Business2_GetAccessInfo(key)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	call_log.RequestUrl = "/dxp/outapi/proxyToService/any/"+key


	start := time.Now()

	if resType == "Service"{

		if serviceInfo.DayLimit > 0 {
			cnt := dao.GetApiCallCount(serviceInfo.AccessId)
			if cnt > serviceInfo.DayLimit {
				response.FailWithMessage("超出单日调用最大次数!",c,serviceInfo.Format)
				return
			}
			dao.IncApiCallCount(serviceInfo.AccessId)
		}
		request_body,_:=ioutil.ReadAll(c.Request.Body)

		//request_body,_ := json.Marshal(&param)
		if global.SystemLogger.Level > logrus.DebugLevel {
			defer c.Set("params",string(request_body))
		}
		call_log.RequestParam = string(request_body)

		fmt.Println("accesskey:",key)
		fmt.Println("request url:",serviceInfo.ResData.ServiceUrl)
		fmt.Println("request param",string(request_body))

		userReq := make(map[string]interface{},0)
		if len(request_body) > 0 {
			err := json.Unmarshal(request_body, &userReq)
			if err != nil {
				global.SystemLogger.Log(logrus.ErrorLevel,"请求参数格式不对，JSON转换失败：", err)
				response.FailWithMessage(err.Error(),c,serviceInfo.Format)
				return
			}
		}
		//拼接内置参数
		search := ""
		if userReq["search"] != nil {
			search = userReq["search"].(string)
		}
		if serviceInfo.ResData.FixParams != nil && len(*serviceInfo.ResData.FixParams) > 0 {
			if len(search) == 0 {
				userReq["search"] = *serviceInfo.ResData.FixParams
			}else{
				//将search 参数和 fixparams 参数组装在一起
				searchMap := make(map[string]interface{},0)
				err := json.Unmarshal([]byte(search),&searchMap)
				if err != nil {
					global.SystemLogger.Log(logrus.ErrorLevel,"fix参数格式不对，JSON转换失败：", err)
					response.FailWithMessage(err.Error(),c,serviceInfo.Format)
					return
				}
				fixReq := make(map[string]interface{},0)
				err = json.Unmarshal([]byte(*serviceInfo.ResData.FixParams), &fixReq)
				if err != nil {
					global.SystemLogger.Log(logrus.ErrorLevel,"fix参数格式不对，JSON转换失败：", err)
					response.FailWithMessage(err.Error(),c,serviceInfo.Format)
					return
				}
				for k,v := range fixReq {
					searchMap[k] = v
				}

				newSearch, err := json.Marshal(searchMap)
				if err != nil {
					global.SystemLogger.Log(logrus.ErrorLevel,"请求参数格式不对，JSON转换失败：", err)
					response.FailWithMessage(err.Error(),c,serviceInfo.Format)
					return
				}
				userReq["search"] = string(newSearch)
			}

		}


		newReq, err := json.Marshal(userReq)
		if err != nil {
			global.SystemLogger.Log(logrus.ErrorLevel,"请求参数格式不对，JSON转换失败：", err)
			response.FailWithMessage(err.Error(),c,serviceInfo.Format)
			return
		}

		fmt.Println("--------------------------------------")
		fmt.Println(string(newReq))
		fmt.Println("--------------------------------------")


		mapData,byteData,err := api_proxy.CQ119_GetInstance().CQ119_ApiCall(serviceInfo.ResData.ServiceUrl,newReq)
		if serviceInfo.ResData.AuthWay == "gov" {
			mapData,byteData,err = api_proxy.GovDataFormatToResource(byteData)
		}

		duration := time.Since(start)
		call_log.CallDuration = duration.Milliseconds()
		if err != nil {
			response.FailWithMessage(err.Error(),c,serviceInfo.Format)
			call_log.ReturnParam = err.Error()
			return
		}
		if serviceInfo.ResData.ResponseForm != "standard"{
			response.OkWithData(mapData,c,serviceInfo.Format)
			call_log.ReturnParam = string(byteData)
		}else{
			out,err := service.Business2_Cq119NormalApiVerify(byteData,serviceInfo)

			if err != nil {
				response.FailWithMessage(err.Error(),c,serviceInfo.Format)
				return
			}

			response.OkWithData(out,c,serviceInfo.Format)

			//c.JSON(http.StatusOK, *out)

			v, err := json.Marshal(*out)
			if err == nil {
				call_log.ReturnParam = string(v)
			}
		}

		//result,err := api_proxy.CQ119_GetInstance().CQ119_ApiRequest("http://dam.cq119.gov.cn:9528/admin-ht/api/resource/dapi/yzzcptcs/1/0483b954d71c30163a966146af74ccfd",&api_proxy.CQ119RequestBody{
		//	Page:      1,
		//	Size:      10,
		//	Search:    "{}",
		//	RowIdOnly: 0,
		//})
	}else if resType == "Data"{

		if dataInfo.DayLimit > 0 {
			cnt := dao.GetApiCallCount(dataInfo.AccessId)
			if cnt > dataInfo.DayLimit {
				response.FailWithMessage("超出单日调用最大次数!",c,dataInfo.Format)
				return
			}
			dao.IncApiCallCount(dataInfo.AccessId)
		}

		var param model.DbQuery
		if err := c.ShouldBindJSON(&param); err != nil {
			response.FailWithMessage("invalid json param",c,dataInfo.Format)
			return
		}
		request_body,_ := json.Marshal(&param)
		if global.SystemLogger.Level > logrus.DebugLevel {
			defer c.Set("params",string(request_body))
		}
		call_log.RequestParam = string(request_body)

		fmt.Println(key)
		fmt.Println(param)

		result, err := service.Business2_QueryTable(&param,dataInfo)
		if err != nil {
			response.FailWithMessage(err.Error(),c,dataInfo.Format)
			return
		}

		response.OkWithData(result,c,dataInfo.Format)

		duration := time.Since(start)
		call_log.CallDuration = duration.Microseconds()
		v, err := json.Marshal(result)
		if err == nil {
			call_log.ReturnParam = string(v)
		}
	}
	call_log.CallResult = "1"

}