package org.xyzh.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.Collections;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xyzh.api.system.service.DeptRoleService;
import org.xyzh.api.system.vo.PermissionVO;
import org.xyzh.api.system.vo.UserDeptRoleVO;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;

import org.xyzh.common.dto.sys.TbSysDeptDTO;
import org.xyzh.common.dto.sys.TbSysDeptRoleDTO;
import org.xyzh.common.dto.sys.TbSysRoleDTO;
import org.xyzh.common.dto.sys.TbSysRolePermissionDTO;
import org.xyzh.common.dto.sys.TbSysUserRoleDTO;
import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.common.utils.StringUtils;
import org.xyzh.system.mapper.dept.TbSysDeptMapper;
import org.xyzh.system.mapper.role.TbSysRoleMapper;
import org.xyzh.system.mapper.role.TbSysRolePermissionMapper;
import org.xyzh.system.mapper.user.TbSysUserRoleMapper;

/**
 * @description    部门角色服务实现类
 * @filename    DeptRoleServiceImpl.java
 */
@DubboService(
    version = "1.0.0",
    group = "system",
    timeout = 3000,
    retries = 0
)
public class DeptRoleServiceImpl implements DeptRoleService {

    private static final Logger logger = LoggerFactory.getLogger(DeptRoleServiceImpl.class);
    private static final String MSG_DEPT_PARAM_REQUIRED = "部门参数不能为空";
    private static final String MSG_ROLE_PARAM_REQUIRED = "角色参数不能为空";
    private static final String MSG_DEPT_ID_REQUIRED = "部门ID不能为空";
    private static final String MSG_ROLE_ID_REQUIRED = "角色ID不能为空";
    private static final String MSG_DEPT_ROLE_ID_REQUIRED = "部门ID和角色ID不能为空";
    private static final String MSG_QUERY_PARAM_REQUIRED = "查询条件不能为空";
    private static final String MSG_PAGE_PARAM_REQUIRED = "分页参数不能为空";

    @Resource
    private TbSysDeptMapper deptMapper;

    @Resource
    private TbSysRoleMapper roleMapper;

    @Resource
    private TbSysUserRoleMapper userRoleMapper;

    @Resource
    private TbSysRolePermissionMapper rolePermissionMapper;

    @Override
    public ResultDomain<TbSysDeptDTO> insertDept(TbSysDeptDTO deptDTO) {
        if (deptDTO == null) {
            return ResultDomain.failure(MSG_DEPT_PARAM_REQUIRED);
        }
        if (StringUtils.isBlank(deptDTO.getDeptId())) {
            deptDTO.setDeptId(IdUtil.generateID());
        }
        if (deptDTO.getCreateTime() == null) {
            deptDTO.setCreateTime(new Date());
        }
        if (deptDTO.getDeleted() == null) {
            deptDTO.setDeleted(false);
        }
        int rows = deptMapper.insertDept(deptDTO);
        if (rows > 0) {
            logger.info("新增部门成功, deptId={}", deptDTO.getDeptId());
            return ResultDomain.success("新增部门成功", deptDTO);
        }
        logger.warn("新增部门失败, deptId={}", deptDTO.getDeptId());
        return ResultDomain.failure("新增部门失败");
    }

    @Override
    public ResultDomain<TbSysDeptDTO> updateDept(TbSysDeptDTO deptDTO) {
        if (deptDTO == null || StringUtils.isBlank(deptDTO.getDeptId())) {
            return ResultDomain.failure(MSG_DEPT_ID_REQUIRED);
        }
        deptDTO.setUpdateTime(new Date());
        int rows = deptMapper.updateDept(deptDTO);
        if (rows > 0) {
            logger.info("更新部门成功, deptId={}", deptDTO.getDeptId());
            return ResultDomain.success("更新部门成功", deptDTO);
        }
        logger.warn("更新部门失败, deptId={}", deptDTO.getDeptId());
        return ResultDomain.failure("更新部门失败");
    }

    @Override
    public ResultDomain<Boolean> deleteDept(TbSysDeptDTO deptDTO) {
        if (deptDTO == null || StringUtils.isBlank(deptDTO.getDeptId())) {
            return ResultDomain.failure(MSG_DEPT_ID_REQUIRED);
        }
        int rows = deptMapper.deleteDept(deptDTO);
        if (rows > 0) {
            logger.info("删除部门成功, deptId={}", deptDTO.getDeptId());
            return ResultDomain.success("删除部门成功", Boolean.TRUE);
        }
        logger.warn("删除部门失败, deptId={}", deptDTO.getDeptId());
        return ResultDomain.failure("删除部门失败");
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getDept(UserDeptRoleVO filter) {
        TbSysDeptDTO dto = UserDeptRoleVO.toDeptDTO(filter);
        if (dto == null) {
            return ResultDomain.failure(MSG_QUERY_PARAM_REQUIRED);
        }
        List<PermissionVO> permissionList = deptMapper.getDeptByFilter(dto);
        if (permissionList == null || permissionList.isEmpty()) {
            return ResultDomain.failure("未找到部门");
        }
        UserDeptRoleVO dept = UserDeptRoleVO.fromPermission(permissionList.get(0));
        return ResultDomain.success("获取部门成功", dept);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getDeptList(UserDeptRoleVO filter) {
        TbSysDeptDTO dto = UserDeptRoleVO.toDeptDTO(filter);
        List<PermissionVO> permissionList = deptMapper.getDeptByFilter(dto);
        List<UserDeptRoleVO> result = (permissionList == null || permissionList.isEmpty()) ?
            java.util.Collections.emptyList() :
            permissionList.stream().map(UserDeptRoleVO::fromPermission).filter(java.util.Objects::nonNull).toList();
        return ResultDomain.success("获取部门列表成功", result);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getDeptPage(PageRequest<UserDeptRoleVO> pageRequest) {
        if (pageRequest == null) {
            return ResultDomain.failure(MSG_PAGE_PARAM_REQUIRED);
        }
        PageParam pageParam = pageRequest.getPageParam();
        TbSysDeptDTO filter = UserDeptRoleVO.toDeptDTO(pageRequest.getFilter());
        int total = deptMapper.getDeptCount(filter);
        pageParam.setTotal(total);
        pageParam.setTotalPages(pageParam.getPageSize() == 0 ? 0 : (int) Math.ceil((double) total / pageParam.getPageSize()));
        List<PermissionVO> permissionList = deptMapper.getDeptPageByFilter(filter, pageParam);
        List<UserDeptRoleVO> data = (permissionList == null || permissionList.isEmpty()) ?
            java.util.Collections.emptyList() :
            permissionList.stream().map(UserDeptRoleVO::fromPermission).filter(java.util.Objects::nonNull).toList();
        PageDomain<UserDeptRoleVO> pageDomain = new PageDomain<>(pageParam, data);
        return ResultDomain.success("分页查询部门成功", pageDomain);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getDeptTree(UserDeptRoleVO filter) {
        return getDeptList(filter);
    }

    @Override
    public ResultDomain<TbSysRoleDTO> insertRole(TbSysRoleDTO roleDTO) {
        if (roleDTO == null) {
            return ResultDomain.failure(MSG_ROLE_PARAM_REQUIRED);
        }
        if (StringUtils.isBlank(roleDTO.getRoleId())) {
            roleDTO.setRoleId(IdUtil.generateID());
        }
        if (roleDTO.getCreateTime() == null) {
            roleDTO.setCreateTime(new Date());
        }
        if (roleDTO.getDeleted() == null) {
            roleDTO.setDeleted(false);
        }
        int rows = roleMapper.insertRole(roleDTO);
        if (rows > 0) {
            logger.info("新增角色成功, roleId={}", roleDTO.getRoleId());
            return ResultDomain.success("新增角色成功", roleDTO);
        }
        logger.warn("新增角色失败, roleId={}", roleDTO.getRoleId());
        return ResultDomain.failure("新增角色失败");
    }

    @Override
    public ResultDomain<TbSysRoleDTO> updateRole(TbSysRoleDTO roleDTO) {
        if (roleDTO == null || StringUtils.isBlank(roleDTO.getRoleId())) {
            return ResultDomain.failure(MSG_ROLE_ID_REQUIRED);
        }
        roleDTO.setUpdateTime(new Date());
        int rows = roleMapper.updateRole(roleDTO);
        if (rows > 0) {
            logger.info("更新角色成功, roleId={}", roleDTO.getRoleId());
            return ResultDomain.success("更新角色成功", roleDTO);
        }
        logger.warn("更新角色失败, roleId={}", roleDTO.getRoleId());
        return ResultDomain.failure("更新角色失败");
    }

    @Override
    public ResultDomain<Boolean> deleteRole(TbSysRoleDTO roleDTO) {
        if (roleDTO == null || StringUtils.isBlank(roleDTO.getRoleId())) {
            return ResultDomain.failure(MSG_ROLE_ID_REQUIRED);
        }
        int rows = roleMapper.deleteRole(roleDTO);
        if (rows > 0) {
            logger.info("删除角色成功, roleId={}", roleDTO.getRoleId());
            return ResultDomain.success("删除角色成功", Boolean.TRUE);
        }
        logger.warn("删除角色失败, roleId={}", roleDTO.getRoleId());
        return ResultDomain.failure("删除角色失败");
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getRole(UserDeptRoleVO filter) {
        TbSysRoleDTO dto = UserDeptRoleVO.toRoleDTO(filter);
        if (dto == null) {
            return ResultDomain.failure(MSG_QUERY_PARAM_REQUIRED);
        }
        List<PermissionVO> permissionList = roleMapper.getRoleByFilter(dto);
        if (permissionList == null || permissionList.isEmpty()) {
            return ResultDomain.failure("未找到角色");
        }
        UserDeptRoleVO role = UserDeptRoleVO.fromPermission(permissionList.get(0));
        return ResultDomain.success("获取角色成功", role);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getRoleList(UserDeptRoleVO filter) {
        TbSysRoleDTO dto = UserDeptRoleVO.toRoleDTO(filter);
        List<PermissionVO> permissionList = roleMapper.getRoleByFilter(dto);
        List<UserDeptRoleVO> result = (permissionList == null || permissionList.isEmpty()) ?
            java.util.Collections.emptyList() :
            permissionList.stream().map(UserDeptRoleVO::fromPermission).filter(java.util.Objects::nonNull).toList();
        return ResultDomain.success("获取角色列表成功", result);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getRolePage(PageRequest<UserDeptRoleVO> pageRequest) {
        if (pageRequest == null) {
            return ResultDomain.failure(MSG_PAGE_PARAM_REQUIRED);
        }
        PageParam pageParam = pageRequest.getPageParam();
        TbSysRoleDTO filter = UserDeptRoleVO.toRoleDTO(pageRequest.getFilter());
        int total = roleMapper.getRoleCount(filter);
        pageParam.setTotal(total);
        pageParam.setTotalPages(pageParam.getPageSize() == 0 ? 0 : (int) Math.ceil((double) total / pageParam.getPageSize()));
        List<PermissionVO> permissionList = roleMapper.getRolePageByFilter(filter, pageParam);
        List<UserDeptRoleVO> data = (permissionList == null || permissionList.isEmpty()) ?
            java.util.Collections.emptyList() :
            permissionList.stream().map(UserDeptRoleVO::fromPermission).filter(java.util.Objects::nonNull).toList();
        PageDomain<UserDeptRoleVO> pageDomain = new PageDomain<>(pageParam, data);
        return ResultDomain.success("分页查询角色成功", pageDomain);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getRoleListByDeptId(String deptId) {
        if (StringUtils.isBlank(deptId)) {
            return ResultDomain.failure(MSG_DEPT_ID_REQUIRED);
        }
        TbSysRoleDTO filter = new TbSysRoleDTO();
        filter.setOwnerDeptId(deptId);
        List<PermissionVO> permissionList = roleMapper.getRoleByFilter(filter);
        List<UserDeptRoleVO> result = (permissionList == null || permissionList.isEmpty()) ?
            java.util.Collections.emptyList() :
            permissionList.stream().map(UserDeptRoleVO::fromPermission).filter(java.util.Objects::nonNull).toList();
        return ResultDomain.success("根据部门获取角色成功", result);
    }

    @Override
    public ResultDomain<UserDeptRoleVO> getRoleListByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return ResultDomain.failure("用户ID不能为空");
        }
        TbSysUserRoleDTO filter = new TbSysUserRoleDTO();
        filter.setUserId(userId);
        List<UserDeptRoleVO> roleList = userRoleMapper.getUserRoleByFilter(filter);
        if (roleList == null) {
            roleList = Collections.emptyList();
        }
        return ResultDomain.success("根据用户获取角色成功", roleList);
    }

    @Override
    public ResultDomain<PermissionVO> setRolePermission(PermissionVO permissionVO) {
        if (permissionVO == null || StringUtils.isBlank(permissionVO.getRoleId())) {
            return ResultDomain.failure(MSG_ROLE_ID_REQUIRED);
        }
        rolePermissionMapper.delete(new QueryWrapper<TbSysRolePermissionDTO>()
            .eq("role_id", permissionVO.getRoleId()));
        List<String> permissionIds = permissionVO.getPermissionIdList();
        if (permissionIds != null && !permissionIds.isEmpty()) {
            Date now = new Date();
            for (String permissionId : permissionIds) {
                if (StringUtils.isBlank(permissionId)) {
                    continue;
                }
                TbSysRolePermissionDTO dto = new TbSysRolePermissionDTO();
                dto.setRoleId(permissionVO.getRoleId());
                dto.setPermissionId(permissionId);
                dto.setCreateTime(now);
                dto.setDeleted(false);
                rolePermissionMapper.insertRolePermission(dto);
            }
        }
        logger.info("角色权限设置成功, roleId={}, count={}", 
            permissionVO.getRoleId(),
            permissionIds == null ? 0 : permissionIds.size());
        return ResultDomain.success("设置角色权限成功", permissionVO);
    }

    @Override
    public ResultDomain<PermissionVO> getRolePermissionList(PermissionVO permissionVO) {
        TbSysRolePermissionDTO dto = new TbSysRolePermissionDTO();
        if (permissionVO != null) {
            dto.setRoleId(permissionVO.getRoleId());
            if (permissionVO.getPermissionIdList() != null && !permissionVO.getPermissionIdList().isEmpty()) {
                dto.setPermissionId(permissionVO.getPermissionIdList().get(0));
            } else {
                dto.setPermissionId(permissionVO.getPermissionId());
            }
            dto.setDeptPath(permissionVO.getDeptPath());
            dto.setDeleted(permissionVO.getDeleted());
        }
        List<PermissionVO> list = rolePermissionMapper.getRolePermissionByFilter(dto);
        if (list == null) {
            list = Collections.emptyList();
        }
        return ResultDomain.success("获取角色权限列表成功", list);
    }

    

}
