package handlers

import (
	"net/http"

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

	"easydo-echo_win7/middleware"

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

func Add_role_menu_to_routes(e *echo.Echo) {
	group := e.Group("/sysRolesMenus")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getList", rolesMenusGetList)
	group.POST("/batchSave", rolesMenusBatchSave)

}

func rolesMenusGetList(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.SysRolesMenus{})
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	list := utils.ConvertInterface[[]models.SysRolesMenus](result)
	if len(list) == 0 {
		return c.JSON(http.StatusOK, []string{})
	}
	return c.JSON(http.StatusOK, list)
}

func rolesMenusBatchSave(c echo.Context) error {
	tx, _ := services.MYSQL_DB.Beginx()

	role_menu := new(models.SysRolesMenus)
	if err := c.Bind(role_menu); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	err := services.JdbcClient.JdbcRemove(role_menu, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	menu_id_list := *role_menu.MenuIdList
	for _, menu_id := range menu_id_list {
		role_menu_c := new(models.SysRolesMenus)
		role_menu_c.RoleID = role_menu.RoleID
		role_menu_c.MenuID = &menu_id
		err = services.JdbcClient.JdbcInsert(role_menu_c, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, role_menu)
}
