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-contrib/session"
	"github.com/labstack/echo/v4"
)

func Add_user_to_routes(e *echo.Echo) {
	group := e.Group("/sysUser")
	group.Use(middleware.AuthMiddleware)
	group.POST("/getPage", userGetPage)
	group.POST("/getList", userGetList)
	group.POST("/save", userSave)
	group.POST("/update", userUpdate)
	group.POST("/remove", userRemove)
	group.POST("/updatePass", userUpdatePass)
	group.POST("/resetPass", userResetPass)
}

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

	for i := range list {
		user := list[i]

		dept := new(models.SysDept)
		dept.ID = user.DeptId
		err := services.JdbcClient.GetJdbcModelById(dept)
		if err != nil {
			continue
		}

		user.Dept = dept

		for k := range paramMap {
			delete(paramMap, k)
		}
		paramMap["userId"] = user.ID
		p_result, err := services.JdbcClient.GetJdbcList(paramMap, models.SysUsersRoles{})
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		p_list := utils.ConvertInterface[[]models.SysUsersRoles](p_result)
		role_id_list := utils.Map(p_list, func(user_role models.SysUsersRoles) int64 {
			return *user_role.RoleID
		})

		for k := range paramMap {
			delete(paramMap, k)
		}
		paramMap["idIn"] = role_id_list
		r_result, err := services.JdbcClient.GetJdbcList(paramMap, models.SysRole{})
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		role_list := utils.ConvertInterface[[]models.SysRole](r_result)
		user.RoleList = &role_list

		tenant := new(models.Tenant)
		tenant.ID = user.TenantId
		err = services.JdbcClient.GetJdbcModelById(tenant)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		user.Tenant = tenant

		list[i] = user
	}
	result.Records = list
	return c.JSON(http.StatusOK, result)
}

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

	for i := range list {
		user := list[i]

		dept := new(models.SysDept)
		dept.ID = user.DeptId
		err := services.JdbcClient.GetJdbcModel(dept)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}

		user.Dept = dept

		for k := range paramMap {
			delete(paramMap, k)
		}
		paramMap["userId"] = user.ID
		p_result, err := services.JdbcClient.GetJdbcList(paramMap, models.SysUsersRoles{})
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		p_list := utils.ConvertInterface[[]models.SysUsersRoles](p_result)
		role_id_list := utils.Map(p_list, func(user_role models.SysUsersRoles) int64 {
			return *user_role.RoleID
		})

		for k := range paramMap {
			delete(paramMap, k)
		}
		paramMap["idIn"] = role_id_list
		r_result, err := services.JdbcClient.GetJdbcList(paramMap, models.SysRole{})
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		role_list := utils.ConvertInterface[[]models.SysRole](r_result)
		user.RoleList = &role_list

		tenant := new(models.Tenant)
		tenant.ID = user.TenantId
		err = services.JdbcClient.GetJdbcModelById(tenant)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		user.Tenant = tenant

		list[i] = user
	}
	return c.JSON(http.StatusOK, list)
}

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

	user := new(models.SysUser)
	if err := c.Bind(user); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	userParam := new(models.SysUser)
	userParam.Username = user.Username
	count, err := services.JdbcClient.GetJdbcCount(userParam, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	if count > 0 {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("用户名已存在", ""))
	}
	password, _ := utils.EncodePassword("123456")
	user.Password = &password

	err = services.JdbcClient.JdbcInsert(user, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	role_list := *user.RoleList
	for _, role := range role_list {
		user_role := new(models.SysUsersRoles)
		user_role.RoleID = role.ID
		user_role.UserID = user.ID
		err = services.JdbcClient.JdbcInsert(user_role, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, user)
}

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

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

	user_role := new(models.SysUsersRoles)
	user_role.UserID = user.ID

	err = services.JdbcClient.JdbcRemove(user_role, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	role_list := *user.RoleList
	for _, role := range role_list {
		user_role := new(models.SysUsersRoles)
		user_role.RoleID = role.ID
		user_role.UserID = user.ID
		err = services.JdbcClient.JdbcInsert(user_role, tx)
		if err != nil {
			utils.PrintSqlErr(err)
			tx.Rollback()
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}
	tx.Commit()
	return c.JSON(http.StatusOK, user)
}

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

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

	user_role := new(models.SysUsersRoles)
	user_role.UserID = user.ID

	err = services.JdbcClient.JdbcRemove(user_role, tx)
	if err != nil {
		utils.PrintSqlErr(err)
		tx.Rollback()
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}

	tx.Commit()
	return c.JSON(http.StatusOK, user)
}

func userUpdatePass(c echo.Context) error {
	sess, _ := session.Get("auth_session", c)
	if user_id, ok := sess.Values["user_id"].(int64); ok {
		var paramMap map[string]interface{}
		if err := c.Bind(&paramMap); err != nil {
			return c.JSON(http.StatusOK, [0]string{})
		}
		oldPass := paramMap["oldPass"]
		newPass := paramMap["newPass"]

		user := new(models.SysUser)
		user.ID = &user_id
		services.JdbcClient.GetJdbcModelById(user)

		oldPassStr := utils.FormatToString(oldPass)
		newPassStr := utils.FormatToString(newPass)
		oldPassStr, _ = utils.DecryptByPrivateKey(oldPassStr)
		newPassStr, _ = utils.DecryptByPrivateKey(newPassStr)

		result := utils.VerifyPassword(oldPassStr, *user.Password)
		if !result {
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("修改失败，旧密码错误", ""))
		}
		result = utils.VerifyPassword(newPassStr, *user.Password)
		if result {
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("新密码不能与旧密码相同", ""))
		}

		password, _ := utils.EncodePassword(newPassStr)
		user.Password = &password
		err := services.JdbcClient.JdbcUpdateById(user)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
		return c.JSON(http.StatusOK, user)
	}
	return c.JSON(http.StatusOK, nil)
}

func userResetPass(c echo.Context) error {
	user := new(models.SysUser)
	if err := c.Bind(user); err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("参数解析失败", err.Error()))
	}
	password, _ := utils.EncodePassword("123456")
	user.Password = &password
	err := services.JdbcClient.JdbcUpdateById(user)
	if err != nil {
		utils.PrintSqlErr(err)
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
	}
	return c.JSON(http.StatusOK, user)
}
