package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.SysMenu;
import org.dromara.system.domain.SysRolePermission;
import org.dromara.system.domain.bo.SysRolePermissionBo;
import org.dromara.system.domain.vo.SysRolePermissionVo;
import org.dromara.system.mapper.SysMenuMapper;
import org.dromara.system.mapper.SysRolePermissionMapper;
import org.dromara.system.service.ISysRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色和菜单关联Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-24
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysRolePermissionServiceImpl implements ISysRolePermissionService {

    private final SysRolePermissionMapper baseMapper;
    private final SysMenuMapper menuMapper;

    /**
     * 查询角色和菜单关联
     *
     * @param roleId 主键
     * @return 角色和菜单关联
     */
    @Override
    public SysRolePermissionVo queryById(Long roleId) {
        return baseMapper.selectVoById(roleId);
    }

    /**
     * 分页查询角色和菜单关联列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 角色和菜单关联分页列表
     */
    @Override
    public TableDataInfo<SysRolePermissionVo> queryPageList(SysRolePermissionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysRolePermission> lqw = buildQueryWrapper(bo);
        Page<SysRolePermissionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的角色和菜单关联列表
     *
     * @param bo 查询条件
     * @return 角色和菜单关联列表
     */
    @Override
    public List<SysRolePermissionVo> queryList(SysRolePermissionBo bo) {
        LambdaQueryWrapper<SysRolePermission> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysRolePermission> buildQueryWrapper(SysRolePermissionBo bo) {
        LambdaQueryWrapper<SysRolePermission> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysRolePermission::getRoleId);
        lqw.orderByAsc(SysRolePermission::getMenuId);
        return lqw;
    }

    /**
     * 新增角色和菜单关联
     *
     * @param bo 角色和菜单关联
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysRolePermissionBo bo) {
        Long roleId = bo.getRoleId();
        List<Long> menuIds = bo.getMenuIds();
        if (CollUtil.isNotEmpty(menuIds)) {
            baseMapper.delete(Wrappers.<SysRolePermission>lambdaQuery()
                    .eq(SysRolePermission::getRoleId, roleId));
            List<SysRolePermission> list = menuIds.stream()
                    .filter(Objects::nonNull)
                    .distinct()
                    .map(menuId -> {
                        SysRolePermission e = new SysRolePermission();
                        e.setRoleId(roleId);
                        e.setMenuId(menuId);
                        return e;
                    })
                    .toList();
            return CollUtil.isNotEmpty(list) && baseMapper.insertBatch(list);
        } else {
            throw new RuntimeException("请选择菜单");
        }
    }

    /**
     * 修改角色和菜单关联
     *
     * @param bo 角色和菜单关联
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysRolePermissionBo bo) {
        SysRolePermission update = MapstructUtils.convert(bo, SysRolePermission.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysRolePermission entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除角色和菜单关联信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Set<String> getPermissionCodesByCompanyId(Long userId, Long companyId, String loginPort) {
        List<String> list = menuMapper.selectObjs(
                new LambdaQueryWrapper<SysMenu>()
                        .select(SysMenu::getPerms)
                        .inSql(SysMenu::getMenuId, """
                                    select menu_id from sys_role_permission where role_id in (
                                        select sur.role_id from sys_user_role sur
                                            left join sys_role sr on sr.role_id = sur.role_id
                                            where sur.user_id = %d and sur.company_id = %d and sur.login_port = '%s' and sr.status = '0'
                                    )
                                """.formatted(userId, companyId, loginPort))
                        .isNotNull(SysMenu::getPerms)
        );
        return new HashSet<>(StreamUtils.filter(list, StringUtils::isNotBlank));
    }

    @Override
    public Set<String> getPermissionCodesByRoleId(Long roleId) {
        List<String> list = menuMapper.selectObjs(
                new LambdaQueryWrapper<SysMenu>()
                        .select(SysMenu::getPerms)
                        .inSql(SysMenu::getMenuId, """
                                    select menu_id from sys_role_permission where role_id = %d
                                """.formatted(roleId))
                        .isNotNull(SysMenu::getPerms)
        );
        return new HashSet<>(StreamUtils.filter(list, StringUtils::isNotBlank));
    }

    @Override
    public List<Long> selectMenuIdsByRoleId(Long roleId) {
        List<Object> objs = baseMapper.selectObjs(
                new LambdaQueryWrapper<SysRolePermission>()
                        .select(SysRolePermission::getMenuId)
                        .eq(SysRolePermission::getRoleId, roleId)
        );
        return objs.stream().map(Convert::toLong).toList();
    }
}
