package org.xyzh.system.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.xyzh.api.system.menu.MenuService;
import org.xyzh.api.system.role.RoleService;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.dto.permission.TbSysPermission;
import org.xyzh.common.dto.role.TbSysRole;
import org.xyzh.common.dto.role.TbSysRolePermission;
import org.xyzh.common.dto.menu.TbSysMenu;
import org.xyzh.common.dto.menu.TbSysMenuPermission;
import org.xyzh.common.utils.IDUtils;
import org.xyzh.common.vo.PermissionVO;
import org.xyzh.system.mapper.MenuPermissionMapper;
import org.xyzh.system.mapper.MenuMapper;
import org.xyzh.system.mapper.PermissionMapper;
import org.xyzh.system.mapper.RolePermissionMapper;
import org.xyzh.system.mapper.RoleMapper;
import org.xyzh.system.permission.service.SysPermissionService;
import org.xyzh.system.utils.LoginUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @description SysPermissionServiceImpl.java文件描述 系统权限服务实现类
 * @filename SysPermissionServiceImpl.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
@Service
public class SysPermissionServiceImpl implements SysPermissionService {

    private static final Logger logger = LoggerFactory.getLogger(SysPermissionServiceImpl.class);

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private MenuPermissionMapper menuPermissionMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Transactional
    @Override
    public ResultDomain<TbSysPermission> createPermission(TbSysPermission permission) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始创建权限：{}", permission.getName());
            
            // 参数校验
            if (!StringUtils.hasText(permission.getName())) {
                resultDomain.fail("权限名称不能为空");
                return resultDomain;
            }
            
            if (!StringUtils.hasText(permission.getCode())) {
                resultDomain.fail("权限编码不能为空");
                return resultDomain;
            }
            
            // 检查权限名称是否已存在
            ResultDomain<Boolean> nameCheckResult = checkPermissionNameExists(permission.getName(), null);
            if (!nameCheckResult.isSuccess()) {
                resultDomain.fail(nameCheckResult.getMessage());
                return resultDomain;
            }
            if (nameCheckResult.getData()) {
                resultDomain.fail("权限名称已存在");
                return resultDomain;
            }
            
            // 检查权限编码是否已存在
            ResultDomain<Boolean> codeCheckResult = checkPermissionCodeExists(permission.getCode(), null);
            if (!codeCheckResult.isSuccess()) {
                resultDomain.fail(codeCheckResult.getMessage());
                return resultDomain;
            }
            if (codeCheckResult.getData()) {
                resultDomain.fail("权限编码已存在");
                return resultDomain;
            }
            
            // 设置基础信息
            permission.setID(IDUtils.generateID());
            permission.setPermissionID(IDUtils.generateID());
            permission.setCreateTime(new Date());
            
            // 插入数据库
            int result = permissionMapper.insertPermission(permission);
            
            if (result > 0) {
                logger.info("创建权限成功：{}", permission.getName());
                resultDomain.success("创建权限成功", permission);
                return resultDomain;
            } else {
                logger.warn("创建权限失败：{}", permission.getName());
                resultDomain.fail("创建权限失败");
            }
            
            return resultDomain;
        } catch (Exception e) {
            logger.error("创建权限异常：{}", permission.getName(), e);
            resultDomain.fail("创建权限失败：" + e.getMessage());
            return resultDomain;
        }
    }


    @Override
    public ResultDomain<PermissionVO> getPermissionVO(PermissionVO filter) {
        ResultDomain<PermissionVO> resultDomain = new ResultDomain<>();
        PermissionVO permission = permissionMapper.selectPermissionVO(filter);
        if (permission == null) {
            resultDomain.fail("权限不存在");
            return resultDomain;
        }
        resultDomain.success("查询成功", permission);
        return resultDomain;
    }

    @Transactional
    @Override
    public ResultDomain<TbSysPermission> updatePermission(TbSysPermission permission) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始更新权限：{}", permission.getPermissionID());
            
            // 参数校验
            if (!StringUtils.hasText(permission.getPermissionID())) {
                resultDomain.fail("权限ID不能为空");
                return resultDomain;
            }
            if (!StringUtils.hasText(permission.getName())) {
                resultDomain.fail("权限名称不能为空");
                return resultDomain;
            }
            if (!StringUtils.hasText(permission.getCode())) {
                resultDomain.fail("权限编码不能为空");
                return resultDomain;
            }
            
            // 检查权限是否存在
            ResultDomain<TbSysPermission> existResult = getPermissionById(permission.getPermissionID());
            if (!existResult.isSuccess()) {
                resultDomain.fail(existResult.getMessage());
                return resultDomain;
            }
            
            // 检查权限名称是否已存在（排除自身）
            ResultDomain<Boolean> nameCheckResult = checkPermissionNameExists(permission.getName(), permission.getID());
            if (!nameCheckResult.isSuccess()) {
                resultDomain.fail(nameCheckResult.getMessage());
                return resultDomain;
            }
            if (nameCheckResult.getData()) {
                resultDomain.fail("权限名称已存在");
                return resultDomain;
            }
            
            // 检查权限编码是否已存在（排除自身）
            ResultDomain<Boolean> codeCheckResult = checkPermissionCodeExists(permission.getCode(), permission.getID());
            if (!codeCheckResult.isSuccess()) {
                resultDomain.fail(codeCheckResult.getMessage());
                return resultDomain;
            }
            if (codeCheckResult.getData()) {
                resultDomain.fail("权限编码已存在");
                return resultDomain;
            }
            
            // 设置更新时间
            permission.setUpdateTime(new Date());
            
            // 更新数据库
            int result = permissionMapper.updatePermission(permission);
            
            if (result > 0) {
                logger.info("更新权限成功：{}", permission.getPermissionID());
                resultDomain.success("更新权限成功", permission);
                return resultDomain;
            } else {
                logger.warn("更新权限失败：{}", permission.getPermissionID());
                resultDomain.fail("更新权限失败");
                return resultDomain;
            }
            
        } catch (Exception e) {
            logger.error("更新权限异常：{}", permission.getPermissionID(), e);
            resultDomain.fail("更新权限失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Transactional
    @Override
    public ResultDomain<TbSysPermission> deletePermission(String permissionId) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        try {
            logger.info("开始删除权限：{}", permissionId);
            
            if (!StringUtils.hasText(permissionId)) {
                resultDomain.fail("权限ID不能为空");
                return resultDomain;
            }
            
            // 检查权限是否存在
            ResultDomain<TbSysPermission> existResult = getPermissionById(permissionId);
            if (!existResult.isSuccess()) {
                resultDomain.fail(existResult.getMessage());
                return resultDomain;
            }
            
            // TODO: 检查权限是否被角色使用，如果被使用则不能删除
            
            // 逻辑删除
            TbSysPermission permission = existResult.getData();
            Date now = new Date();
            permission.setDeleted(true);
            permission.setDeleteTime(now);
            permission.setUpdater(user.getID());
            permission.setUpdateTime(now);
            
            int result = permissionMapper.deletePermission(permission);
            
            if (result > 0) {
                logger.info("删除权限成功：{}", permissionId);
                resultDomain.success("删除权限成功", permission);
                return resultDomain;
            } else {
                logger.warn("删除权限失败：{}", permissionId);
                resultDomain.fail("删除权限失败");
                return resultDomain;
            }
            
        } catch (Exception e) {
            logger.error("删除权限异常：{}", permissionId, e);
            resultDomain.fail("删除权限失败：" + e.getMessage());
            return resultDomain;
        }
    }


    /**
     * @description    查询权限绑定列表
     * @param permission
     * @author    yslg
     * @ since 2025-10-08
     */
    @Override
    public ResultDomain<PermissionVO> listPermissionBinding(PermissionVO permission) {
        ResultDomain<PermissionVO> resultDomain = new ResultDomain<>();
        if (!permission.getBindType().equals("menu") && !permission.getBindType().equals("role")) {
            resultDomain.fail("绑定类型不存在");
            return resultDomain;
        }
        PermissionVO permissionVO = permissionMapper.selectPermissionVO(permission);

        if (permission.getBindType().equals("menu")) {
            List<TbSysMenu> bindMenus = permissionMapper.selectPermissionBindMenu(permission);
            permissionVO.setMenus(bindMenus);
            resultDomain.success("查询权限绑定列表成功", permissionVO);
            return resultDomain;
        } else {
            List<TbSysRole> bindRoles = permissionMapper.selectPermissionBindRole(permission);
            permissionVO.setRoles(bindRoles);
            resultDomain.success("查询权限绑定角色列表成功", permissionVO);
            return resultDomain;
        }
    }

    // ----------------------角色权限管理--------------------------
    /**
     * @description    角色权限绑定
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysRolePermission> bindRolePermission(String roleId, String permissionId) {
        ResultDomain<TbSysRolePermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验权限存在
        ResultDomain<TbSysPermission> permissionResult = getPermissionById(permissionId);
        if (!permissionResult.isSuccess()) {
            resultDomain.fail(permissionResult.getMessage());
            return resultDomain;
        }
        // 校验角色存在
        ResultDomain<TbSysRole> roleResult = roleService.getRoleById(roleId);
        if (!roleResult.isSuccess()) {
            resultDomain.fail(roleResult.getMessage());
            return resultDomain;
        }

        // 绑定角色权限
        TbSysRolePermission rolePermission = new TbSysRolePermission();
        rolePermission.setID(IDUtils.generateID());
        rolePermission.setRoleID(roleId);
        rolePermission.setPermissionID(permissionId);
        rolePermission.setCreator(user.getID());
        rolePermission.setCreateTime(new Date());

        int result = rolePermissionMapper.batchBindRolePermission(Arrays.asList(rolePermission));
        if (result > 0) {
            resultDomain.success("绑定角色权限成功", rolePermission);
        } else {
            resultDomain.fail("绑定角色权限失败");
        }

        return resultDomain;
    }

    /**
     * @description    角色权限批量绑定
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysRolePermission> batchBindRolePermission(List<String> roleIds, List<String> permissionIds) {
        ResultDomain<TbSysRolePermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验权限存在
        List<TbSysPermission> permissions = permissionMapper.checkPermissionExists(permissionIds);
        if (permissions.isEmpty()) {
            resultDomain.fail("权限不存在");
            return resultDomain;
        }

        // 检验角色存在
        List<TbSysRole> roles = roleMapper.checkRoleExists(roleIds);
        if (roles.isEmpty()) {
            resultDomain.fail("角色不存在");
            return resultDomain;
        }

        // 批量绑定角色权限
        List<TbSysRolePermission> rolePermissions = new ArrayList<>();
        for (String roleId : roleIds) {
            for (String permissionId : permissionIds) {
                TbSysRolePermission rolePermission = new TbSysRolePermission();
                rolePermission.setID(IDUtils.generateID());
                rolePermission.setRoleID(roleId);
                rolePermission.setPermissionID(permissionId);
                rolePermission.setCreator(user.getID());
                rolePermission.setCreateTime(new Date());
                rolePermissions.add(rolePermission);
            }
        }
        int result = rolePermissionMapper.batchBindRolePermission(rolePermissions);
        if (result > 0) {
            resultDomain.success("批量绑定角色权限成功", rolePermissions);
        } else {
            resultDomain.fail("批量绑定角色权限失败");
        }
        return resultDomain;
    }

    /**
     * @description    角色权限解绑  真删除，避免再次绑定导致的报错问题
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysRolePermission> unbindRolePermission(String roleId, String permissionId) {
        ResultDomain<TbSysRolePermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验权限存在
        ResultDomain<TbSysPermission> permissionResult = getPermissionById(permissionId);
        if (!permissionResult.isSuccess()) {
            resultDomain.fail(permissionResult.getMessage());
            return resultDomain;
        }
        // 校验角色存在
        ResultDomain<TbSysRole> roleResult = roleService.getRoleById(roleId);
        if (!roleResult.isSuccess()) {
            resultDomain.fail(roleResult.getMessage());
            return resultDomain;
        }
        // 解绑角色权限
        TbSysRolePermission rolePermission = new TbSysRolePermission();
        rolePermission.setRoleID(roleId);
        rolePermission.setPermissionID(permissionId);
        rolePermission.setUpdater(user.getID());
        rolePermission.setUpdateTime(new Date());
        int result = rolePermissionMapper.batchUnbindRolePermission(Arrays.asList(rolePermission));
        if (result > 0) {
            resultDomain.success("解绑角色权限成功", rolePermission);
        } else {
            resultDomain.fail("解绑角色权限失败");
        }
        return resultDomain;
    }

    /**
     * @description    角色权限批量解绑  真删除，避免再次绑定导致的报错问题
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysRolePermission> batchUnbindRolePermission(List<String> roleIds, List<String> permissionIds) {
        ResultDomain<TbSysRolePermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验权限存在
        List<TbSysPermission> permissions = permissionMapper.checkPermissionExists(permissionIds);
        if (permissions.isEmpty()) {
            resultDomain.fail("权限不存在");
            return resultDomain;
        }
        // 检验角色存在
        List<TbSysRole> roles = roleMapper.checkRoleExists(roleIds);
        if (roles.isEmpty()) {
            resultDomain.fail("角色不存在");
            return resultDomain;
        }
        // 批量解绑角色权限
        List<TbSysRolePermission> rolePermissions = new ArrayList<>();
        for (String roleId : roleIds) {
            for (String permissionId : permissionIds) {
                TbSysRolePermission rolePermission = new TbSysRolePermission();
                rolePermission.setRoleID(roleId);
                rolePermission.setPermissionID(permissionId);
                rolePermission.setUpdater(user.getID());
                rolePermission.setUpdateTime(new Date());
                rolePermissions.add(rolePermission);
            }
        }
        int result = rolePermissionMapper.batchUnbindRolePermission(rolePermissions);
        if (result > 0) {
            resultDomain.success("批量解绑角色权限成功", rolePermissions);
        } else {
            resultDomain.fail("批量解绑角色权限失败");
        }
        return resultDomain;
    }

    // ----------------------菜单权限管理--------------------------
    /**
     * @description    菜单权限绑定
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysMenuPermission> bindMenuPermission(String menuId, String permissionId) {
        ResultDomain<TbSysMenuPermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验菜单存在
        ResultDomain<TbSysMenu> menuResult = menuService.getMenuById(menuId);
        if (!menuResult.isSuccess()) {
            resultDomain.fail(menuResult.getMessage());
            return resultDomain;
        }
        // 检验权限存在
        ResultDomain<TbSysPermission> permissionResult = getPermissionById(permissionId);
        if (!permissionResult.isSuccess()) {
            resultDomain.fail(permissionResult.getMessage());
            return resultDomain;
        }
        // 绑定菜单权限
        TbSysMenuPermission menuPermission = new TbSysMenuPermission();
        menuPermission.setID(IDUtils.generateID());
        menuPermission.setMenuID(menuId);
        menuPermission.setPermissionID(permissionId);
        menuPermission.setCreator(user.getID());
        menuPermission.setCreateTime(new Date());
        int result = menuPermissionMapper.batchBindMenuPermission(Arrays.asList(menuPermission));
        if (result > 0) {
            resultDomain.success("绑定菜单权限成功", menuPermission);
        } else {
            resultDomain.fail("绑定菜单权限失败");
        }
        return resultDomain;
    }

    /**
     * @description    菜单权限批量绑定
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysMenuPermission> batchBindMenuPermission(List<String> menuIds, List<String> permissionIds) {
        ResultDomain<TbSysMenuPermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验菜单存在
        List<TbSysMenu> menus = menuMapper.checkMenuExists(menuIds);
        if (menus.isEmpty()) {
            resultDomain.fail("菜单不存在");
            return resultDomain;
        }
        // 检验权限存在
        List<TbSysPermission> permissions = permissionMapper.checkPermissionExists(permissionIds);
        if (permissions.isEmpty()) {
            resultDomain.fail("权限不存在");
            return resultDomain;
        }
        // 批量绑定菜单权限
        List<TbSysMenuPermission> menuPermissions = new ArrayList<>();
        for (String menuId : menuIds) {
            for (String permissionId : permissionIds) {
                TbSysMenuPermission menuPermission = new TbSysMenuPermission();
                menuPermission.setID(IDUtils.generateID());
                menuPermission.setMenuID(menuId);
                menuPermission.setPermissionID(permissionId);
                menuPermission.setCreator(user.getID());
                menuPermission.setCreateTime(new Date());
                menuPermissions.add(menuPermission);
            }
        }
        int result = menuPermissionMapper.batchBindMenuPermission(menuPermissions);
        if (result > 0) {
            resultDomain.success("批量绑定菜单权限成功", menuPermissions);
        } else {
            resultDomain.fail("批量绑定菜单权限失败");
        }
        return resultDomain;
    }

    /**
     * @description    菜单权限解绑
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysMenuPermission> unbindMenuPermission(String menuId, String permissionId) {
        ResultDomain<TbSysMenuPermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验菜单存在
        ResultDomain<TbSysMenu> menuResult = menuService.getMenuById(menuId);
        if (!menuResult.isSuccess()) {
            resultDomain.fail(menuResult.getMessage());
            return resultDomain;
        }
        // 检验权限存在
        ResultDomain<TbSysPermission> permissionResult = getPermissionById(permissionId);
        if (!permissionResult.isSuccess()) {
            resultDomain.fail(permissionResult.getMessage());
            return resultDomain;
        }
        // 解绑菜单权限
        TbSysMenuPermission menuPermission = new TbSysMenuPermission();
        menuPermission.setMenuID(menuId);
        menuPermission.setPermissionID(permissionId);
        menuPermission.setUpdater(user.getID());
        menuPermission.setUpdateTime(new Date());
        int result = menuPermissionMapper.batchUnbindMenuPermission(Arrays.asList(menuPermission));
        if (result > 0) {
            resultDomain.success("解绑菜单权限成功", menuPermission);
        } else {
            resultDomain.fail("解绑菜单权限失败");
        }
        return resultDomain;
    }

    /**
     * @description    菜单权限批量解绑
     * @param    
     * @author    yslg
     * @ since 2025-10-07
     */
    @Transactional
    @Override
    public ResultDomain<TbSysMenuPermission> batchUnbindMenuPermission(List<String> menuIds, List<String> permissionIds) {
        ResultDomain<TbSysMenuPermission> resultDomain = new ResultDomain<>();
        TbSysUser user = LoginUtil.getCurrentUser();
        if (user == null) {
            resultDomain.fail("当前用户不存在");
            return resultDomain;
        }
        // 检验菜单存在
        List<TbSysMenu> menus = menuMapper.checkMenuExists(menuIds);
        if (menus.isEmpty()) {
            resultDomain.fail("菜单不存在");
            return resultDomain;
        }
        // 检验权限存在
        List<TbSysPermission> permissions = permissionMapper.checkPermissionExists(permissionIds);
        if (permissions.isEmpty()) {
            resultDomain.fail("权限不存在");
            return resultDomain;
        }
        // 批量解绑菜单权限
        List<TbSysMenuPermission> menuPermissions = new ArrayList<>();
        for (String menuId : menuIds) {
            for (String permissionId : permissionIds) {
                TbSysMenuPermission menuPermission = new TbSysMenuPermission();
                menuPermission.setMenuID(menuId);
                menuPermission.setPermissionID(permissionId);
                menuPermission.setUpdater(user.getID());
                menuPermission.setUpdateTime(new Date());
                menuPermissions.add(menuPermission);
            }
        }
        int result = menuPermissionMapper.batchUnbindMenuPermission(menuPermissions);
        if (result > 0) {
            resultDomain.success("批量解绑菜单权限成功", menuPermissions);
        } else {
            resultDomain.fail("批量解绑菜单权限失败");
        }
        return resultDomain;
    }

    @Transactional
    @Override
    public ResultDomain<Boolean> checkPermissionNameExists(String permissionName, String excludeId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            logger.info("检查权限名称是否存在：{}", permissionName);
            
            if (!StringUtils.hasText(permissionName)) {
                resultDomain.fail("权限名称不能为空");
                return resultDomain;
            }
            
            int count = permissionMapper.countByPermissionName(permissionName, excludeId);
            boolean exists = count > 0;
            
            logger.info("权限名称存在性检查完成：{}，存在：{}", permissionName, exists);
            resultDomain.success("检查完成", exists);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("检查权限名称存在性失败：{}", permissionName, e);
            resultDomain.fail("检查失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<Boolean> checkPermissionCodeExists(String permissionCode, String excludeId) {
        ResultDomain<Boolean> resultDomain = new ResultDomain<>();
        try {
            logger.info("检查权限编码是否存在：{}", permissionCode);
            
            if (!StringUtils.hasText(permissionCode)) {
                resultDomain.fail("权限编码不能为空");
                return resultDomain;
            }
            
            int count = permissionMapper.countByPermissionCode(permissionCode, excludeId);
            boolean exists = count > 0;
            
            logger.info("权限编码存在性检查完成：{}，存在：{}", permissionCode, exists);
            resultDomain.success("检查完成", exists);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("检查权限编码存在性失败：{}", permissionCode, e);
            resultDomain.fail("检查失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbSysPermission> changePermissionStatus(String permissionId, Integer status) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始修改权限状态：{}，状态：{}", permissionId, status);
            
            if (!StringUtils.hasText(permissionId)) {
                resultDomain.fail("权限ID不能为空");
                return resultDomain;
            }
            
            if (status == null) {
                resultDomain.fail("权限状态不能为空");
                return resultDomain;
            }
            
            // 检查权限是否存在
            ResultDomain<TbSysPermission> existResult = getPermissionById(permissionId);
            if (!existResult.isSuccess()) {
                resultDomain.fail(existResult.getMessage());
                return resultDomain;
            }
            
            TbSysPermission permission = existResult.getData();
            
            permission.setUpdateTime(new Date());
            
            int result = permissionMapper.updateById(permission);
            
            if (result > 0) {
                logger.info("修改权限状态成功：{}", permissionId);
                resultDomain.success("修改权限状态成功", permission);
                return resultDomain;
            } else {
                logger.warn("修改权限状态失败：{}", permissionId);
                resultDomain.fail("修改权限状态失败");
                return resultDomain;
            }
            
        } catch (Exception e) {
            logger.error("修改权限状态异常：{}", permissionId, e);
            resultDomain.fail("修改权限状态失败：" + e.getMessage());
            return resultDomain;
        }
    }


    @Override
    public ResultDomain<TbSysPermission> getAllPermissions() {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();

        try {
            logger.info("开始查询所有权限");
            
            LambdaQueryWrapper<TbSysPermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbSysPermission::getDeleted, false)
                       .orderByAsc(TbSysPermission::getCreateTime);
            
            List<TbSysPermission> permissions = permissionMapper.selectList(queryWrapper);
            
            logger.info("查询所有权限完成，共找到{}个权限", permissions.size());
            resultDomain.success("查询成功", permissions);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("查询所有权限失败", e);
            resultDomain.fail("查询权限失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbSysPermission> getPermissionById(String permissionId) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始根据ID查询权限：{}", permissionId);
            
            if (!StringUtils.hasText(permissionId)) {
                resultDomain.fail("权限ID不能为空");
                return resultDomain;
            }
            
            TbSysPermission permissionQY = new TbSysPermission();
            permissionQY.setPermissionID(permissionId);
            
            TbSysPermission permission = permissionMapper.selectPermission(permissionQY);
            
            if (permission == null) {
                logger.warn("未找到权限：{}", permissionId);
                resultDomain.fail("未找到指定权限");
                return resultDomain;
            }
            
            logger.info("根据ID查询权限完成：{}", permissionId);
            resultDomain.success("查询成功", permission);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("根据ID查询权限失败：{}", permissionId, e);
            resultDomain.fail("查询权限失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbSysPermission> getPermissionByCode(String permissionCode) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始根据权限编码查询权限：{}", permissionCode);
            
            if (!StringUtils.hasText(permissionCode)) {
                resultDomain.fail("权限编码不能为空");
                return resultDomain;
            }
            
            TbSysPermission permission = permissionMapper.selectByPermissionCode(permissionCode);
            
            if (permission == null) {
                logger.warn("未找到权限：{}", permissionCode);
                resultDomain.fail("未找到指定权限");
                return resultDomain;
            }
            
            logger.info("根据权限编码查询权限完成：{}", permissionCode);
            resultDomain.success("查询成功", permission);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("根据权限编码查询权限失败：{}", permissionCode, e);
            resultDomain.fail("查询权限失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbSysPermission> getPermissionsByUserId(String userId) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始根据用户ID查询权限列表：{}", userId);
            
            if (!StringUtils.hasText(userId)) {
                resultDomain.fail("用户ID不能为空");
                return resultDomain;
            }
            
            List<TbSysPermission> permissions = permissionMapper.selectPermissionsByUserId(userId);
            
            logger.info("根据用户ID查询权限列表完成，共找到{}个权限", permissions.size());
            resultDomain.success("查询成功", permissions);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("根据用户ID查询权限列表失败：{}", userId, e);
            resultDomain.fail("查询权限失败：" + e.getMessage());
            return resultDomain;
        }
    }

    @Override
    public ResultDomain<TbSysPermission> getPermissionsByRoleId(String roleId) {
        ResultDomain<TbSysPermission> resultDomain = new ResultDomain<>();
        try {
            logger.info("开始根据角色ID查询权限列表：{}", roleId);
            
            if (!StringUtils.hasText(roleId)) {
                resultDomain.fail("角色ID不能为空");
                return resultDomain;
            }
            
            List<TbSysPermission> permissions = permissionMapper.selectPermissionsByRoleID(roleId);
            
            logger.info("根据角色ID查询权限列表完成，共找到{}个权限", permissions.size());
            resultDomain.success("查询成功", permissions);
            return resultDomain;
            
        } catch (Exception e) {
            logger.error("根据角色ID查询权限列表失败：{}", roleId, e);
            resultDomain.fail("查询权限失败：" + e.getMessage());
            return resultDomain;
        }
    }

    /**
     * @description    查询权限列表
     * @param    permission 权限对象
     * @return    ResultDomain<PermissionVO> 权限列表
     * @author    yslg
     * @ since 2025-10-08
     */
    @Override
    public ResultDomain<PermissionVO> listPermission(PermissionVO permission) {
        ResultDomain<PermissionVO> resultDomain = new ResultDomain<>();
        List<PermissionVO> permissions = permissionMapper.selectPermissionList(permission);
        if (permissions.isEmpty()) {
            resultDomain.fail("权限不存在");
            return resultDomain;
        }
        resultDomain.success("查询成功", permissions);
        return resultDomain;
    }

}
