package handler

import (
	"DataShare/global"
	"DataShare/model"
	"DataShare/service"
	"DataShare/util/response"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/sirupsen/logrus"
)

func DxpApi_RouteInit(Router *gin.RouterGroup){
	//mibRouter := Router.Use(middleware.TokenAuthMiddleware())
	dxpRouter := Router
	{
		//测试
		dxpRouter.POST("connect", connect)
		dxpRouter.POST("databaseQueryStatus", databaseQueryStatus)
		dxpRouter.POST("databaseUpdateNotify", databaseUpdateNotify)
		dxpRouter.POST("databaseDelete", databaseDelete)
		dxpRouter.POST("databaseQueryTableList", databaseQueryTableList)
		dxpRouter.POST("databaseQueryTableColnList", databaseQueryTableColnList)

		dxpRouter.POST("databaseCreateTable", databaseCreateTable)
		dxpRouter.POST("databaseAddIndex", databaseAddIndex)
		dxpRouter.POST("databaseDeleteIndex", databaseDeleteIndex)
		dxpRouter.POST("databaseInsertData", databaseInsertData)
		dxpRouter.POST("databaseDeleteTableData", databaseDeleteTableData)
		dxpRouter.POST("databaseQueryTable", databaseQueryTable)

		dxpRouter.POST("databaseDropTable", databaseDropTable)
	}
}

// @Tags 巨衍接口-数据库连接测试
// @Summary 数据库连接测试
// @Description 测试数据库连接
// @Accept application/json
// @Produce application/json
// @Param connect body model.DbConnInfo true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/connect [post]
func connect(c *gin.Context){

	var param model.DbConnInfo
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseConnect(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-查询数据库连接状态
// @Summary 查询数据库连接状态
// @Description 查询数据库连接状态
// @Accept application/json
// @Produce application/json
// @Param connect body model.Page true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseQueryStatus [post]
func databaseQueryStatus(c *gin.Context){

	var param model.Page
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	result,err := service.DatabaseList(&param)
	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.NullObj true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseUpdateNotify [post]
func databaseUpdateNotify(c *gin.Context){

	service.UpdateOfDbConnect()
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-查询指定数据库表结构
// @Summary 查询指定数据库表结构
// @Description 查询指定数据库表结构
// @Accept application/json
// @Produce application/json
// @Param connect body model.QueryId true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseQueryTableList [post]
func databaseQueryTableList(c *gin.Context){

	var param model.QueryId
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	result,err := service.QueryTableList(param.Id)
	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.QueryTableColn true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseQueryTableColnList [post]
func databaseQueryTableColnList(c *gin.Context){

	var param model.QueryTableColn
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	result,err := service.QueryTableColnList(param.Id,param.TableName)
	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.QueryId true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseDelete [post]
func databaseDelete(c *gin.Context){

	var param model.QueryId
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseDel(param.Id)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-动态创建数据表
// @Summary 动态创建数据表
// @Description 动态创建数据表
// @Accept application/json
// @Produce application/json
// @Param connect body model.DatabaseCreateRequest true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseCreateTable [post]
func databaseCreateTable(c *gin.Context){

	var param model.DatabaseCreateRequest
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseCreate(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-动态添加索引
// @Summary 动态添加索引
// @Description 动态添加索引
// @Accept application/json
// @Produce application/json
// @Param connect body model.TbIndex true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseAddIndex [post]
func databaseAddIndex(c *gin.Context){

	var param model.TbIndex
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseAddIndex(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-动态删除索引
// @Summary 动态删除索引
// @Description 动态删除索引
// @Accept application/json
// @Produce application/json
// @Param connect body model.TbIndex true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseDeleteIndex [post]
func databaseDeleteIndex(c *gin.Context){

	var param model.TbIndex
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseDeleteIndex(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-动态插入表数据
// @Summary 动态插入表数据
// @Description 动态插入表数据
// @Accept application/json
// @Produce application/json
// @Param connect body model.ColnDataInsert true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseInsertData [post]
func databaseInsertData(c *gin.Context){

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

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseInsert(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-删除表数据
// @Summary 删除表数据
// @Description 删除表数据
// @Accept application/json
// @Produce application/json
// @Param connect body model.TbDelete true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseDeleteTableData [post]
func databaseDeleteTableData(c *gin.Context){

	var param model.TbDelete
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseDeleteTable(param.Id,param.TbName)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}
// @Tags 巨衍接口-删除数据表
// @Summary 删除数据表
// @Description 删除数据表
// @Accept application/json
// @Produce application/json
// @Param connect body model.TbDelete true "json"
// @Success 200 {object} model.NullObj "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseDropTable [post]
func databaseDropTable(c *gin.Context){

	var param model.TbDelete
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	err = service.DatabaseDropTable(param.Id,param.TbName)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithMessage("success",c,"JSON")
}

// @Tags 巨衍接口-查询表数据
// @Summary 查询表数据
// @Description 查询表数据
// @Accept application/json
// @Produce application/json
// @Param connect body model.DbQuery true "json"
// @Success 200 {object} model.CommonList "{"code": 0, "msg": "xxx", data:{total:0,rows:[]}}"
// @Router /dxp/database/databaseQueryTable [post]
func databaseQueryTable(c *gin.Context){

	var param model.DbQuery
	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))
	}

	err := global.DataValidator.Struct(param)
	if err != nil {
		for _,e:= range err.(validator.ValidationErrors){
			global.SystemLogger.WithFields(logrus.Fields{"错误的字段:":e.Field(),"错误的值:":e.Value(),"错误的tag:":e.Tag()}).Info(err)
		}
		response.FailWithMessage("param validator failed.",c,"JSON")
		return
	}
	//数据库连接测试
	result,err := service.DatabaseQuery(&param)
	if err != nil {
		response.FailWithMessage(err.Error(),c,"JSON")
		return
	}
	response.OkWithData(result,c,"JSON")
}
