package org.xyzh.system.service.impl;

import org.apache.dubbo.config.annotation.DubboService;
import org.xyzh.api.system.service.ModulePermissionService;
import org.xyzh.api.system.vo.PermissionVO;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.dto.sys.TbSysModuleDTO;
import org.xyzh.common.dto.sys.TbSysPermissionDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.Collections;
import java.util.List;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.common.utils.StringUtils;
import org.xyzh.system.mapper.module.TbSysModuleMapper;
import org.xyzh.system.mapper.permission.TbSysPermissionMapper;
import org.xyzh.system.mapper.role.TbSysRolePermissionMapper;
import org.xyzh.system.mapper.user.TbSysUserRoleMapper;

/**
 * @description    模块权限服务实现类
 * @filename    ModulePermissionServiceImpl.java
 */
@DubboService(
    version = "1.0.0",
    group = "system",
    timeout = 3000,
    retries = 0
)
public class ModulePermissionServiceImpl implements ModulePermissionService {

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

    private static final String MSG_MODULE_PARAM_REQUIRED = "模块参数不能为空";
    private static final String MSG_PERMISSION_PARAM_REQUIRED = "权限参数不能为空";
    private static final String MSG_MODULE_ID_REQUIRED = "模块ID不能为空";
    private static final String MSG_PERMISSION_ID_REQUIRED = "权限ID不能为空";
    private static final String MSG_QUERY_PARAM_REQUIRED = "查询条件不能为空";
    private static final String MSG_PAGE_PARAM_REQUIRED = "分页参数不能为空";

    @Resource
    private TbSysModuleMapper moduleMapper;

    @Resource
    private TbSysPermissionMapper permissionMapper;

    @Resource
    private TbSysRolePermissionMapper rolePermissionMapper;

    @Resource
    private TbSysUserRoleMapper userRoleMapper;

    @Override
    public ResultDomain<TbSysModuleDTO> insertModule(TbSysModuleDTO moduleDTO) {
        if (moduleDTO == null) {
            return ResultDomain.failure(MSG_MODULE_PARAM_REQUIRED);
        }
        if (StringUtils.isBlank(moduleDTO.getModuleId())) {
            moduleDTO.setModuleId(IdUtil.generateID());
        }
        if (moduleDTO.getCreateTime() == null) {
            moduleDTO.setCreateTime(new Date());
        }
        if (moduleDTO.getDeleted() == null) {
            moduleDTO.setDeleted(false);
        }
        int rows = moduleMapper.insertModule(moduleDTO);
        if (rows > 0) {
            logger.info("新增模块成功, moduleId={}", moduleDTO.getModuleId());
            return ResultDomain.success("新增模块成功", moduleDTO);
        }
        logger.warn("新增模块失败, moduleId={}", moduleDTO.getModuleId());
        return ResultDomain.failure("新增模块失败");
    }

    @Override
    public ResultDomain<TbSysModuleDTO> updateModule(TbSysModuleDTO moduleDTO) {
        if (moduleDTO == null || StringUtils.isBlank(moduleDTO.getModuleId())) {
            return ResultDomain.failure(MSG_MODULE_ID_REQUIRED);
        }
        moduleDTO.setUpdateTime(new Date());
        int rows = moduleMapper.updateModule(moduleDTO);
        if (rows > 0) {
            logger.info("更新模块成功, moduleId={}", moduleDTO.getModuleId());
            return ResultDomain.success("更新模块成功", moduleDTO);
        }
        logger.warn("更新模块失败, moduleId={}", moduleDTO.getModuleId());
        return ResultDomain.failure("更新模块失败");
    }

    @Override
    public ResultDomain<Boolean> deleteModule(TbSysModuleDTO moduleDTO) {
        if (moduleDTO == null || StringUtils.isBlank(moduleDTO.getModuleId())) {
            return ResultDomain.failure(MSG_MODULE_ID_REQUIRED);
        }
        int rows = moduleMapper.deleteModule(moduleDTO);
        if (rows > 0) {
            logger.info("删除模块成功, moduleId={}", moduleDTO.getModuleId());
            return ResultDomain.success("删除模块成功", Boolean.TRUE);
        }
        logger.warn("删除模块失败, moduleId={}", moduleDTO.getModuleId());
        return ResultDomain.failure("删除模块失败");
    }

    @Override
    public ResultDomain<PermissionVO> getModulePage(PageRequest<PermissionVO> pageRequest) {
        if (pageRequest == null) {
            return ResultDomain.failure(MSG_PAGE_PARAM_REQUIRED);
        }
        PageParam pageParam = pageRequest.getPageParam();
        TbSysModuleDTO filter = org.xyzh.api.system.vo.PermissionVO.toModuleDTO(pageRequest.getFilter());
        int total = moduleMapper.getModuleCount(filter);
        pageParam.setTotal(total);
        pageParam.setTotalPages(pageParam.getPageSize() == 0 ? 0 : (int) Math.ceil((double) total / pageParam.getPageSize()));
        List<PermissionVO> list = moduleMapper.getModulePageByFilter(filter, pageParam);
        PageDomain<PermissionVO> pageDomain = new PageDomain<>(pageParam, list == null ? Collections.emptyList() : list);
        return ResultDomain.success("分页查询模块成功", pageDomain);
    }

    @Override
    public ResultDomain<PermissionVO> getModuleList(PermissionVO filter) {
        TbSysModuleDTO dto = org.xyzh.api.system.vo.PermissionVO.toModuleDTO(filter);
        List<PermissionVO> list = moduleMapper.getModuleByFilter(dto);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("获取模块列表成功", list);
    }

    @Override
    public ResultDomain<TbSysPermissionDTO> insertPermission(TbSysPermissionDTO permissionDTO) {
        if (permissionDTO == null) {
            return ResultDomain.failure(MSG_PERMISSION_PARAM_REQUIRED);
        }
        if (StringUtils.isBlank(permissionDTO.getPermissionId())) {
            permissionDTO.setPermissionId(IdUtil.generateID());
        }
        if (permissionDTO.getCreateTime() == null) {
            permissionDTO.setCreateTime(new Date());
        }
        if (permissionDTO.getDeleted() == null) {
            permissionDTO.setDeleted(false);
        }
        int rows = permissionMapper.insertPermission(permissionDTO);
        if (rows > 0) {
            logger.info("新增权限成功, permissionId={}", permissionDTO.getPermissionId());
            return ResultDomain.success("新增权限成功", permissionDTO);
        }
        logger.warn("新增权限失败, permissionId={}", permissionDTO.getPermissionId());
        return ResultDomain.failure("新增权限失败");
    }

    @Override
    public ResultDomain<TbSysPermissionDTO> updatePermission(TbSysPermissionDTO permissionDTO) {
        if (permissionDTO == null || StringUtils.isBlank(permissionDTO.getPermissionId())) {
            return ResultDomain.failure(MSG_PERMISSION_ID_REQUIRED);
        }
        permissionDTO.setUpdateTime(new Date());
        int rows = permissionMapper.updatePermission(permissionDTO);
        if (rows > 0) {
            logger.info("更新权限成功, permissionId={}", permissionDTO.getPermissionId());
            return ResultDomain.success("更新权限成功", permissionDTO);
        }
        logger.warn("更新权限失败, permissionId={}", permissionDTO.getPermissionId());
        return ResultDomain.failure("更新权限失败");
    }

    @Override
    public ResultDomain<Boolean> deletePermission(TbSysPermissionDTO permissionDTO) {
        if (permissionDTO == null || StringUtils.isBlank(permissionDTO.getPermissionId())) {
            return ResultDomain.failure(MSG_PERMISSION_ID_REQUIRED);
        }
        int rows = permissionMapper.deletePermission(permissionDTO);
        if (rows > 0) {
            logger.info("删除权限成功, permissionId={}", permissionDTO.getPermissionId());
            return ResultDomain.success("删除权限成功", Boolean.TRUE);
        }
        logger.warn("删除权限失败, permissionId={}", permissionDTO.getPermissionId());
        return ResultDomain.failure("删除权限失败");
    }

    @Override
    public ResultDomain<PermissionVO> getPermissionListByModuleId(String moduleId) {
        if (StringUtils.isBlank(moduleId)) {
            return ResultDomain.failure(MSG_MODULE_ID_REQUIRED);
        }
        TbSysPermissionDTO filter = new TbSysPermissionDTO();
        filter.setModuleId(moduleId);
        List<PermissionVO> list = permissionMapper.getPermissionByFilter(filter);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("根据模块获取权限列表成功", list);
    }

    @Override
    public ResultDomain<PermissionVO> getModulePermission(PermissionVO filter) {
        TbSysPermissionDTO dto = org.xyzh.api.system.vo.PermissionVO.toPermissionDTO(filter);
        if (dto == null) {
            return ResultDomain.failure(MSG_QUERY_PARAM_REQUIRED);
        }
        List<PermissionVO> list = permissionMapper.getPermissionByFilter(dto);
        if (list == null || list.isEmpty()) {
            return ResultDomain.failure("未找到模块权限");
        }
        return ResultDomain.success("获取模块权限成功", list.get(0));
    }

    @Override
    public ResultDomain<PermissionVO> getModulePermissionList(PermissionVO filter) {
        TbSysPermissionDTO dto = org.xyzh.api.system.vo.PermissionVO.toPermissionDTO(filter);
        List<PermissionVO> list = permissionMapper.getPermissionByFilter(dto);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("获取模块权限列表成功", list);
    }

    @Override
    public ResultDomain<PermissionVO> getModulePermissionPage(PageRequest<PermissionVO> pageRequest) {
        if (pageRequest == null) {
            return ResultDomain.failure(MSG_PAGE_PARAM_REQUIRED);
        }
        PageParam pageParam = pageRequest.getPageParam();
        TbSysPermissionDTO filter = org.xyzh.api.system.vo.PermissionVO.toPermissionDTO(pageRequest.getFilter());
        int total = permissionMapper.getPermissionCount(filter);
        pageParam.setTotal(total);
        pageParam.setTotalPages(pageParam.getPageSize() == 0 ? 0 : (int) Math.ceil((double) total / pageParam.getPageSize()));
        List<PermissionVO> list = permissionMapper.getPermissionPageByFilter(filter, pageParam);
        PageDomain<PermissionVO> pageDomain = new PageDomain<>(pageParam, list == null ? Collections.emptyList() : list);
        return ResultDomain.success("分页查询模块权限成功", pageDomain);
    }

    @Override
    public ResultDomain<PermissionVO> getModulePermissionListByRoleId(String roleId) {
        if (StringUtils.isBlank(roleId)) {
            return ResultDomain.failure("角色ID不能为空");
        }
        List<PermissionVO> list = rolePermissionMapper.getRolePermissionByRoleId(roleId);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("根据角色获取权限列表成功", list);
    }

    @Override
    public ResultDomain<PermissionVO> getUserPermissions(String userId) {
        if (StringUtils.isBlank(userId)) {
            return ResultDomain.failure("用户ID不能为空");
        }
        List<PermissionVO> list = rolePermissionMapper.getPermissionsByUserId(userId);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("获取用户权限成功", list);
    }    

}

