package handlers

import (
	"net/http"

	"easydo-echo_win7/middleware"
	"easydo-echo_win7/models"
	"easydo-echo_win7/services"
	"easydo-echo_win7/utils"

	"github.com/labstack/echo/v4"
)

func Add_dept_to_routes(e *echo.Echo) {
	group := e.Group("/sysDept")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getList", deptGetList)
	group.POST("/save", deptSave)
	group.POST("/update", deptUpdate)
	group.POST("/remove", deptRemove)
}

func deptGetList(c echo.Context) error {
	var paramMap map[string]interface{}
	if err := c.Bind(&paramMap); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	result, err := services.JdbcClient.GetJdbcList(paramMap, models.SysDept{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	list := utils.ConvertInterface[[]models.SysDept](result)
	if len(list) == 0 {
		return c.JSON(http.StatusOK, []models.SysDept{})
	}
	return c.JSON(http.StatusOK, list)
}

func deptSave(c echo.Context) error {
	dept := new(models.SysDept)
	if err := c.Bind(dept); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err := services.JdbcClient.JdbcInsert(dept)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	return c.JSON(http.StatusOK, dept)
}

func deptUpdate(c echo.Context) error {
	dept := new(models.SysDept)
	if err := c.Bind(dept); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err := services.JdbcClient.JdbcUpdateById(dept)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	return c.JSON(http.StatusOK, dept)
}

func deptRemove(c echo.Context) error {
	dept := new(models.SysDept)
	if err := c.Bind(dept); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	deptParam := new(models.SysDept)
	deptParam.Pid = dept.ID
	count, err := services.JdbcClient.GetJdbcCount(deptParam)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	if count > 0 {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("存在下级部门，无法删除", ""))
	}

	err = services.JdbcClient.JdbcRemoveById(dept)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", err.Error()))
	}
	return c.JSON(http.StatusOK, dept)
}
