package com.zt.plat.module.qms.resource.record.service.recordrecord;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.qms.common.dic.dal.dataobject.DictionaryBusinessDO;
import com.zt.plat.module.qms.common.dic.service.DictionaryBusinessService;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.record.constant.RecordConstants;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordRecordPageReqVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordRecordRespVO;
import com.zt.plat.module.qms.resource.record.controller.admin.recordrecord.vo.RecordRecordSaveReqVO;
//import com.zt.plat.module.qms.resource.record.dal.dao.recordrecord.RecordRecordMapper;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordcategory.RecordCategoryDO;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordpermission.RecordPermissionDO;
import com.zt.plat.module.qms.resource.record.dal.dataobject.recordrecord.RecordRecordDO;
import com.zt.plat.module.qms.resource.record.dal.mapper.RecordRecordMapper;
import com.zt.plat.module.qms.resource.record.service.recordcategory.RecordCategoryService;
import com.zt.plat.module.qms.resource.record.service.recordpermission.RecordPermissionService;
import com.zt.plat.module.system.api.dept.DeptApi;
import com.zt.plat.module.system.api.dept.dto.DeptRespDTO;
import com.zt.plat.module.system.api.permission.PermissionApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 文件、模板、记录 Service 实现类
 *
 * @author 后台管理
 */
@Slf4j
@Service("recordRecordService")
@Validated
public class RecordRecordServiceImpl implements RecordRecordService {

    @Resource
    private RecordRecordMapper recordRecordMapper;

    @Resource
    private BusinessFileService businessFileService;

    @Resource
    private RecordPermissionService recordPermissionService;

    @Resource
    private DeptApi deptApi;

    @Resource
    private PermissionApi permissionApi;

//    @Resource
//    private RecordApplyService recordApplyService;
//
//    @Resource
//    private RecordApplyDetailService recordApplyDetailService;
//
//    @Resource
//    private BpmProcessInstanceApi bpmProcessInstanceApi;
//    @Resource
//    private DataKeyCheckService dataKeyCheckService;
//    @Resource
//    private DataOpinionService dataOpinionService;

    @Autowired
    private DictionaryBusinessService dictionaryBusinessService; // 字典服务

    private List<DictionaryBusinessDO> dictionaryBusinessDOS = new ArrayList<>();

    private List<DictionaryBusinessDO> businessDOList = new ArrayList<>();
    @Autowired
    private RecordCategoryService recordCategoryService;

    // 验证分类ID 是否存在
    private RecordCategoryDO validateRecordCategoryIdExists(Long categoryId) {
        RecordCategoryDO recordCategoryDO = recordCategoryService.selectById(categoryId);
        if (ObjectUtils.isEmpty(recordCategoryDO)) throw exception(RCD_CTGR_NOT_EXISTS);
        else return recordCategoryDO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecordRecordRespVO createRecordRecord(RecordRecordSaveReqVO createReqVO) {
        // 插入
        RecordRecordDO recordRecord = BeanUtils.toBean(createReqVO, RecordRecordDO.class);
        // 判断文件记录分类ID 是否存在
        Long categoryId = recordRecord.getCategoryId();
        RecordCategoryDO recordCategoryDO = validateRecordCategoryIdExists(categoryId);
        // 判断父级是否为根节点，是 --> 不允许创建记录明细
        Long parentId = recordCategoryDO.getParentId();
        if (parentId != null && parentId == 0) throw new RuntimeException("根节点不允许直接添加文件记录信息！");
        recordRecord.setCurrentFlag(1);// 是否新版本
        try {
            recordRecordMapper.insert(recordRecord);
            recordRecord.setMainId(recordRecord.getId());
            recordRecordMapper.updateById(recordRecord);
        } catch (Exception e) {
            throw new RuntimeException("create record error");
        }
        // 返回
        return BeanUtils.toBean(recordRecord, RecordRecordRespVO.class);
    }

    public RecordRecordRespVO saveDataWithNewVersion(RecordRecordDO createReqVO) {
        RecordRecordDO recordRecordDO = BeanUtils.toBean(createReqVO, RecordRecordDO.class);
        recordRecordDO.setCurrentFlag(0);
        try {
            LambdaQueryWrapper<RecordRecordDO> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(RecordRecordDO::getMainId, recordRecordDO.getMainId()); // 所以main_id 和 current_flag = 1 的数据
            lambdaQueryWrapper.eq(RecordRecordDO::getCurrentFlag, 1); // 0，旧版本
            recordRecordMapper.update(recordRecordDO, lambdaQueryWrapper);

            //创建新版本
            recordRecordDO.setId(null);
            recordRecordDO.setCurrentFlag(1);
            recordRecordDO.setMainId(createReqVO.getMainId());
            recordRecordDO.setVersion(recordRecordDO.getNewVersion());// 新版本号
            recordRecordMapper.insert(recordRecordDO);
            // 返回
            return BeanUtils.toBean(recordRecordDO, RecordRecordRespVO.class);
        } catch (Exception e) {
            throw new RuntimeException("save new version error");
        }
    }

    @Override
    public RecordRecordRespVO updateRecordRecordById(RecordRecordDO recordDO) {
        try {
            recordRecordMapper.updateById(recordDO);
            return BeanUtils.toBean(recordDO, RecordRecordRespVO.class);
        } catch (Exception e) {
            throw new RuntimeException("update record error");
        }
    }

    @Override
    public void updateRecordRecordListByIds(List<RecordRecordDO> recordRecordDOS) {
        try {
            recordRecordMapper.updateBatch(recordRecordDOS);
        } catch (Exception e) {
            throw new RuntimeException("update record list error");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RecordRecordRespVO updateRecordRecord(RecordRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateRecordRecordExists(updateReqVO.getId());
        RecordRecordDO updateObj = BeanUtils.toBean(updateReqVO, RecordRecordDO.class);
        String newVersion = updateObj.getNewVersion();// 新版本
        if (ObjectUtils.isEmpty(newVersion)) { // 不是新版本，直接更新
            recordRecordMapper.updateById(updateObj);
        } else {// 新版本
            // 是否回收
            Integer collectionFlag = updateReqVO.getCollectionFlag();
            if (collectionFlag != null) { // 不为null, 回收旧版本权限
                // TODO
            }
            // 创建新版本
            return saveDataWithNewVersion(updateObj);
        }
        // 更新
        businessFileService.deleteBusinessFileList(updateReqVO.getDeleteFileIdList());
        return BeanUtils.toBean(updateReqVO, RecordRecordRespVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRecordRecord(Long id) {
        // 校验存在
        RecordRecordDO recordRecordDO = recordRecordMapper.selectById(id);
        if (ObjectUtils.isEmpty(recordRecordDO)) throw exception(RECORD_RECORD_NOT_EXISTS);
        // 删除
        recordRecordMapper.deleteById(id);
        /*
         删除成功，需要判断是否有历史版本，
            1.有：需要把上一版变成最新版
            2.没有：不操作
         */
        LambdaQueryWrapper<RecordRecordDO> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(RecordRecordDO::getMainId, recordRecordDO.getMainId());
        lambdaQueryWrapper.orderByDesc(RecordRecordDO::getCreateTime); // 根据时间倒叙排序，取第一个
        List<RecordRecordDO> recordRecordDOS = recordRecordMapper.selectList(lambdaQueryWrapper);
        log.info("recordRecordDOS--:{}", recordRecordDOS);
        if (ObjectUtils.isEmpty(recordRecordDOS)) return;
        // 修改状态为当前最新版本
        // TODO 需要去判断文件作废状态
        recordRecordDO = recordRecordDOS.get(0);
        recordRecordDO.setCurrentFlag(1);
        recordRecordMapper.updateById(recordRecordDO);
    }

    @Override
    public void deleteRecordRecordListByIds(List<Long> ids) {
        // 校验存在
        validateRecordRecordExists(ids);
        // 删除
        recordRecordMapper.deleteByIds(ids);
    }

    private void validateRecordRecordExists(List<Long> ids) {
        List<RecordRecordDO> list = recordRecordMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(RECORD_RECORD_NOT_EXISTS);
        }
    }

    private void validateRecordRecordExists(Long id) {
        if (recordRecordMapper.selectById(id) == null) {
            throw exception(RECORD_RECORD_NOT_EXISTS);
        }
    }

    // 判断记录的操作权限
    @Override
    public CommonResult<String> justRecordPermission(Long id) {

        RecordRecordDO recordRecordDO = recordRecordMapper.selectById(id);
        hasPermissionByCategoryId(recordRecordDO.getCategoryId());
        if (!ObjectUtils.isEmpty(recordRecordDO)) {
            Long categoryId = recordRecordDO.getCategoryId();
            RecordCategoryDO recordCategoryDO = recordCategoryService.selectById(categoryId);
            Long parentId = recordCategoryDO.getParentId();

            String dept = RecordConstants.TargetType.DEPT;
            String role = RecordConstants.TargetType.ROLE;

            // 判断管理员权限
            List<RecordPermissionDO> permissionDOList = judgeIsAdmin(parentId,dept,role);

            // 判断当前用户的管理员权限
            LambdaQueryWrapper<RecordPermissionDO> lambdaQueryWrapper = Wrappers.lambdaQuery();
            lambdaQueryWrapper.eq(RecordPermissionDO::getTargetId, id);
            List<RecordPermissionDO> recordPermissionDOS = recordPermissionService.selectList(lambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(recordPermissionDOS))
                return CommonResult.success(RecordConstants.PermissionType.ADMIN);
            String s = hasPermissionByCategoryId(parentId);
            return CommonResult.success(s);
        }
        return CommonResult.success(null);
    }

    @Override
    public RecordRecordDO getRecordRecord(Long id) {
        RecordRecordDO recordRecordDO = recordRecordMapper.selectById(id);
        hasPermissionByCategoryId(recordRecordDO.getCategoryId());
        if (!ObjectUtils.isEmpty(recordRecordDO)) {
            Long categoryId = recordRecordDO.getCategoryId();
            RecordCategoryDO recordCategoryDO = recordCategoryService.selectById(categoryId);
            recordRecordDO.setCategoryName(recordCategoryDO.getName());
            // 判断当前操作记录可执行的权限
            Long parentId = recordCategoryDO.getParentId();
            String dept = RecordConstants.TargetType.DEPT;
            String role = RecordConstants.TargetType.ROLE;
            List<RecordPermissionDO> permissionDOList = judgeIsAdmin(parentId,dept,role);
            if (!ObjectUtils.isEmpty(permissionDOList)){
                // 查询 category 的父级Id
                if (ObjectUtils.isEmpty(parentId)) throw exception(RECORD_RECORD_NOT_EXISTS);
                Object finalParse = customConfigParseJson(parentId);
                recordRecordDO.setCustomConfig(finalParse);
            }

        }
        return recordRecordDO;
    }

    @Override
    public RecordRecordDO getRecordById(Long id) {
        return recordRecordMapper.selectById(id);
    }

    public String getDictValueByKey(List<DictionaryBusinessDO> businessDOList, String targetKey) {
        return businessDOList.stream()
                .filter(item -> item.getKey().equals(targetKey))
                .findFirst()
                .map(DictionaryBusinessDO::getValue)
                .orElse(null);
    }

    // 查询字典列表，通过key
    public List<DictionaryBusinessDO> selectDictTargetTypeByKey(String targetKey) {
        return dictionaryBusinessDOS = dictionaryBusinessService.queryDictItemsByKey(targetKey);
    }

    public List<DictionaryBusinessDO> selectDictPermissionByKey(String targetKey) {
        return businessDOList = dictionaryBusinessService.queryDictItemsByKey(targetKey);
    }
//
//    //判断当前用户是不是最高管理员
//    public List<RecordPermissionDO> isAdmin(){
//
//    }
//

    // 判断当前用户管理员权限(用户，角色，部门)，返回权限列表
    public List<RecordPermissionDO> judgeIsAdmin(Long parentCategoryId, String dept,String role) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long userId = loginUser.getId();
        RecordPermissionDO recordPermissionDO = new RecordPermissionDO();

        businessDOList = selectDictPermissionByKey(RecordConstants.PermissionType.PERMISSION_KEY);
        String permissionAdmin = getDictValueByKey(businessDOList, RecordConstants.PermissionType.ADMIN);// 管理员权限
        dictionaryBusinessDOS = selectDictTargetTypeByKey(RecordConstants.TargetType.TARGET_KEY);
        String targetUser = getDictValueByKey(dictionaryBusinessDOS, RecordConstants.TargetType.USER);// 用户权限

        recordPermissionDO.setTargetType(targetUser);// 用户
        recordPermissionDO.setTargetId(userId.toString()); // 用户ID
        recordPermissionDO.setPermission(permissionAdmin); // 管理员

        // 判断是否是最高管理员权限
        recordPermissionDO.setSourceType(RecordConstants.TargetType.ADMIN); //admin
        List<RecordPermissionDO> recordPermissionDOS = recordPermissionService.selectRecordPermission(recordPermissionDO);
        if (!ObjectUtils.isEmpty(recordPermissionDOS)) return recordPermissionDOS;

        // 判断是普通管理员权限
        recordPermissionDO.setSourceType(null);
        recordPermissionDO.setSourceId(parentCategoryId);
        if (!ObjectUtils.isEmpty(dept)){
            recordPermissionDO.setTargetType(dept);
            // 当前用户部门ID
            Long visitDeptId = loginUser.getVisitDeptId();
            recordPermissionDO.setTargetId(visitDeptId.toString());
            List<RecordPermissionDO> permissionDOList = recordPermissionService.selectRecordPermission(recordPermissionDO);
            if (!ObjectUtils.isEmpty(permissionDOList)) return permissionDOList;
        }
        if (!ObjectUtils.isEmpty(role)) {
            recordPermissionDO.setTargetType(role);
            // 当前角色Id
            Set<Long> userRoleIdList = permissionApi.getUserRoleIdListByUserId(userId).getData();
            if (userRoleIdList.size() == 1) {
                recordPermissionDO.setTargetId(userRoleIdList.stream().findFirst().get().toString());
            }else {
                // Set 转 permissionDOList
                List<RecordPermissionDO> permissionDOList = new ArrayList<>();
                for (Long roleId : userRoleIdList) {
                    RecordPermissionDO rolePermissionDO = new RecordPermissionDO();
                    rolePermissionDO.setSourceType(null);
                    rolePermissionDO.setSourceId(parentCategoryId);
                    rolePermissionDO.setTargetType(role);
                    rolePermissionDO.setTargetId(roleId.toString());
                    rolePermissionDO.setPermission(permissionAdmin);
                    permissionDOList.add(rolePermissionDO);
                }
            }
        }
        return recordPermissionService.selectRecordPermission(recordPermissionDO);
    }

    // 根据当前用户部门获取所有子部门列表
    public List<DeptRespDTO> getParentDepts() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long currentDeptId = loginUser.getVisitDeptId();
        List<DeptRespDTO> childDepts = new ArrayList<>();
        
        // 添加当前部门
        CommonResult<DeptRespDTO> deptResult = deptApi.getDept(currentDeptId);
        DeptRespDTO currentDept = deptResult.getData();
        childDepts.add(currentDept);
        
        // 获取所有子部门
        CommonResult<List<DeptRespDTO>> childDeptListResult = deptApi.getChildDeptList(currentDeptId);
        if (childDeptListResult.isSuccess()) {
            List<DeptRespDTO> childDeptList = childDeptListResult.getData();
            if (CollUtil.isNotEmpty(childDeptList)) {
                childDepts.addAll(childDeptList);
            }
        }
        
        return childDepts;
    }

    /**
     * 权限优先级顺序（由高到低）：管理员 > 可编辑 > 可查看
     */
    private static final List<String> PERMISSION_PRIORITY = List.of(
            RecordConstants.PermissionType.ADMIN,
            RecordConstants.PermissionType.EDIT,
            RecordConstants.PermissionType.VIEW
    );

    /**
     * 通过 recordCategory 的 categoryId 连接 recordPermission 的 sourceId，
     * 查询当前用户在该分类上命中的最高权限类型。
     * 匹配条件：当前部门、所有父级部门、角色，满足任一条件即算命中。
     *
     * @param parentCategoryId 分类ID
     * @return 命中的最高权限值（管理员/可编辑/可查看），无权限时返回 null
     */
    public String hasPermissionByCategoryId(Long parentCategoryId) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long userId = loginUser.getId();

        // 1. 查询该分类下所有权限配置（以 sourceId = categoryId 为条件）
        RecordPermissionDO query = new RecordPermissionDO();
        query.setSourceId(parentCategoryId);
        List<RecordPermissionDO> permissionList = recordPermissionService.selectAllList(query);
//        log.info("分类ID: {}，对应权限配置数量: {}", parentCategoryId, permissionList == null ? 0 : permissionList.size());
        if (ObjectUtils.isEmpty(permissionList)) {
            return null;
        }

        // 2. 加载字典：授权目标类型（用户/部门/角色）
        List<DictionaryBusinessDO> targetTypeDicts = dictionaryBusinessService.queryDictItemsByKey(RecordConstants.TargetType.TARGET_KEY);
        String targetDeptValue = getDictValueByKey(targetTypeDicts, RecordConstants.TargetType.DEPT);   // 部门
        String targetRoleValue = getDictValueByKey(targetTypeDicts, RecordConstants.TargetType.ROLE);   // 角色

        // 3. 获取当前用户所在部门及所有父级部门列表
        List<DeptRespDTO> allDepts = getParentDepts(); // 包含当前部门和所有父级部门
//        log.info("当前用户部门链（含父级）: {}", allDepts);

        // 4. 获取当前用户的角色ID集合
        Set<Long> userRoleIds = null;
        try {
            userRoleIds = permissionApi.getUserRoleIdListByUserId(userId).getData();
//            log.info("当前用户角色ID集合: {}", userRoleIds);
        } catch (Exception e) {
            log.warn("获取用户角色ID失败，将跳过角色权限校验: {}", e.getMessage());
        }
        final Set<Long> finalUserRoleIds = userRoleIds;

        // 5. 收集当前用户命中的所有权限值
        List<String> matchedPermissions = new ArrayList<>();
        for (RecordPermissionDO perm : permissionList) {
            String targetType = perm.getTargetType();
            String targetId = perm.getTargetId();
            String permission = perm.getPermission();

            // 5.1 部门条件：当前部门或任意父级部门匹配
            if (targetDeptValue != null && targetDeptValue.equals(targetType)) {
                boolean deptMatch = allDepts.stream()
                        .anyMatch(dept -> dept.getId() != null && dept.getId().toString().equals(targetId));
                if (deptMatch) {
//                    log.info("部门权限命中，部门ID: {}，权限类型: {}", targetId, permission);
                    matchedPermissions.add(permission);
                }
            }

            // 5.2 角色条件：当前用户的任意角色匹配
            if (targetRoleValue != null && targetRoleValue.equals(targetType)
                    && finalUserRoleIds != null) {
                boolean roleMatch = finalUserRoleIds.stream()
                        .anyMatch(roleId -> roleId.toString().equals(targetId));
                if (roleMatch) {
//                    log.info("角色权限命中，角色ID: {}，权限类型: {}", targetId, permission);
                    matchedPermissions.add(permission);
                }
            }
        }

        // 6. 按照优先级（管理员 > 可编辑 > 可查看）返回最高权限
        for (String level : PERMISSION_PRIORITY) {
            if (matchedPermissions.contains(level)) {
//                log.info("分类ID: {} 最终命中最高权限: {}", parentCategoryId, level);
                return level;
            }
        }

//        log.info("分类ID: {} 权限校验未通过，当前用户不满足任何授权条件", parentCategoryId);
        return null;
    }

    @Override
    public PageResult<RecordRecordDO> getRecordRecordPage(RecordRecordPageReqVO pageReqVO) {
        LambdaQueryWrapper<RecordRecordDO> wrapper = Wrappers.lambdaQuery(RecordRecordDO.class);
//                .apply("ID = MAIN_ID");
        // 添加其他查询条件
        Long categoryId = pageReqVO.getCategoryId();
        if (!ObjectUtils.isEmpty(pageReqVO.getCategoryId())) wrapper.eq(RecordRecordDO::getCategoryId, categoryId);
        if (!ObjectUtils.isEmpty(pageReqVO.getCode())) wrapper.eq(RecordRecordDO::getCode, pageReqVO.getCode());
        if (!ObjectUtils.isEmpty(pageReqVO.getName())) wrapper.like(RecordRecordDO::getName, pageReqVO.getName());
        wrapper.eq(RecordRecordDO::getCurrentFlag, 1); // 默认查询最新版
        wrapper.orderByAsc(RecordRecordDO::getCreateTime);
//        log.info("pageReqVO:{}", pageReqVO);

        PageResult<RecordRecordDO> recordRecordDOPageResult;

        //不是管理员，判断部门、角色权限
        // 获取分类ID 的父节点，并校验当前用户是否有权限
        RecordCategoryDO recordCategoryDO = recordCategoryService.selectById(categoryId);
        if (ObjectUtils.isEmpty(recordCategoryDO)) return new PageResult<RecordRecordDO>().setTotal(0L);
        Long parentId = recordCategoryDO.getParentId();

        String dept = RecordConstants.TargetType.DEPT;
        String role = RecordConstants.TargetType.ROLE;

        List<RecordPermissionDO> permissionDOList = judgeIsAdmin(parentId,dept,role);
        if (!ObjectUtils.isEmpty(permissionDOList)) {
            recordRecordDOPageResult = recordRecordMapper.selectPage(pageReqVO, wrapper);
            // 通过 categoryId 查询所属分类的 customConfig（存储为JSON字符串），解析后追加到每条记录中
            // 使用 Map 缓存已查询的分类，避免同分类重复查库
//        Map<Long, RecordCategoryDO> categoryCache = new HashMap<>();
            Object finalParse = customConfigParseJson(parentId);
            recordRecordDOPageResult.getList().forEach(record -> {
                try {
                    record.setCustomConfig(finalParse);
                } catch (Exception e) {
                    throw exception(RECORD_RECORD_NOT_EXISTS);
                }
            });
            return recordRecordDOPageResult;
        }
//        log.info("permissionDOList:{}", permissionDOList);

        String permission = hasPermissionByCategoryId(parentId);
//        log.info("分类ID: {} 当前用户命中权限: {}", categoryId, permission);
        if (permission == null) throw exception(RECORD_PERMISSION_NOT_ALLOW);
        return recordRecordMapper.selectPage(pageReqVO, wrapper);
    }

    private Object customConfigParseJson(Long parentId) {
        RecordCategoryDO categoryDOByParent = recordCategoryService.selectById(parentId);
        log.info("categoryDOByParent:{}", categoryDOByParent);
        if (ObjectUtils.isEmpty(categoryDOByParent)) throw exception(RECORD_CATEGORY_NOT_EXISTS);
        Object parse=new Object();
        if (!ObjectUtils.isEmpty(categoryDOByParent.getCustomConfig())) {
            String customConfig = categoryDOByParent.getCustomConfig();
            parse = JSON.parse(customConfig);
        }
        return parse;
    }


    // 查询历史分页
    @Override
    public PageResult<RecordRecordDO> getRecordHistoryPage(RecordRecordPageReqVO pageReqVO) {
        Long mainId = pageReqVO.getMainId();
        if (ObjectUtils.isEmpty(mainId)) throw exception(RECORD_RECORD_NOT_EXISTS);
        return recordRecordMapper.selectPage(pageReqVO);
    }

    /**
     * 根据 categoryId 查询 recordPermission 中关联 sourceId 的所有权限记录，
     * 并通过当前用户的部门（含所有父级部门）、角色进行过滤，返回满足条件的权限列表。
     *
     * @param categoryId 分类ID（对应 recordPermission.sourceId）
     * @return 当前用户命中的权限记录列表（包含管理员/可编辑/可查看等所有类型）
     */
    @Override
    public List<RecordPermissionDO> getMatchedPermissionList(Long categoryId) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long userId = loginUser.getId();
        
        // 如果是最高管理员（条件：sourceType：admin；targetId：当前用户；targetType：用户），直接返回该分类下的所有权限记录，
        // 无需过滤，按照sourceId 跟 permission 字段进行分类
        List<RecordPermissionDO> adminCheckResult = judgeIsAdmin(categoryId, null, null);
        if (!ObjectUtils.isEmpty(adminCheckResult)) {
            // 用户是最高管理员，直接返回该分类下的所有权限记录
            RecordPermissionDO query = new RecordPermissionDO();
            query.setSourceId(categoryId);
            List<RecordPermissionDO> allPermissions = recordPermissionService.selectAllList(query);
            return ObjectUtils.isEmpty(allPermissions) ? new ArrayList<>() : allPermissions;
        }

        // 1. 查询该分类下所有权限配置（sourceId = categoryId）
        RecordPermissionDO query = new RecordPermissionDO();
        query.setSourceId(categoryId);
        List<RecordPermissionDO> permissionList = recordPermissionService.selectAllList(query);
        if (ObjectUtils.isEmpty(permissionList)) {
            return new ArrayList<>();
        }

        // 2. 加载字典：授权目标类型（部门/角色）
        List<DictionaryBusinessDO> targetTypeDicts = dictionaryBusinessService.queryDictItemsByKey(RecordConstants.TargetType.TARGET_KEY);
        String targetDeptValue = getDictValueByKey(targetTypeDicts, RecordConstants.TargetType.DEPT); // 部门
        String targetRoleValue = getDictValueByKey(targetTypeDicts, RecordConstants.TargetType.ROLE); // 角色

        // 3. 获取当前用户所在部门及所有父级部门列表
        List<DeptRespDTO> allDepts = getParentDepts(); // 包含当前部门和所有父级部门

        // 4. 获取当前用户的角色ID集合
        Set<Long> userRoleIds = null;
        try {
            userRoleIds = permissionApi.getUserRoleIdListByUserId(userId).getData();
        } catch (Exception e) {
            log.warn("获取用户角色ID失败，将跳过角色权限过滤: {}", e.getMessage());
        }
        final Set<Long> finalUserRoleIds = userRoleIds;

        // 5. 过滤出当前用户命中的所有权限记录
        List<RecordPermissionDO> recordPermissionDOS = judgeIsAdmin(categoryId,null,null);
        List<RecordPermissionDO> matchedList = new ArrayList<>(recordPermissionDOS);
        for (RecordPermissionDO perm : permissionList) {
            String targetType = perm.getTargetType();
            String targetId = perm.getTargetId();

            // 5.1 部门条件：当前部门或任意父级部门匹配
            if (targetDeptValue != null && targetDeptValue.equals(targetType)) {
                boolean deptMatch = allDepts.stream()
                        .anyMatch(dept -> dept.getId() != null && dept.getId().toString().equals(targetId));
                if (deptMatch) {
                    matchedList.add(perm);
                    continue; // 已命中，无需再判断角色
                }
            }

            // 5.2 角色条件：当前用户的任意角色匹配
            if (targetRoleValue != null && targetRoleValue.equals(targetType) && finalUserRoleIds != null) {
                boolean roleMatch = finalUserRoleIds.stream()
                        .anyMatch(roleId -> roleId.toString().equals(targetId));
                if (roleMatch) {
                    matchedList.add(perm);
                }
            }
        }

        log.info("分类ID: {} 共命中权限记录数: {}", categoryId, matchedList.size());
        return matchedList;
    }

}