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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.resource.clientManage.controller.vo.UploadFileVo;
import com.zt.plat.module.qms.resource.record.common.RecordCommonUtils;
import com.zt.plat.module.qms.resource.record.constant.RecordConstants;
import com.zt.plat.module.qms.resource.record.controller.admin.recordfileattachment.vo.RecordFileAttachmentSaveReqVO;
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.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.recordfileattachment.RecordFileAttachmentService;
import com.zt.plat.module.qms.resource.record.service.recordpermission.RecordPermissionService;
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.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception0;
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;

    @Autowired
    private RecordCategoryService recordCategoryService;

    @Resource
    private RecordFileAttachmentService recordFileAttachmentService;

    // 验证分类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);// 是否新版本
        recordRecord.setSubmitFlag(0);
        try {
            RecordRecordDO recordRecordDO = judgeRootCategoryJson(recordRecord);
            recordRecordMapper.insert(recordRecordDO);
            recordRecordDO.setMainId(recordRecordDO.getId());
            recordRecordMapper.updateById(recordRecordDO);

            // 添加文件记录附件
            List<UploadFileVo> files = createReqVO.getFiles();
            createFileAttachment(files, recordRecordDO.getId());

        } catch (Exception e) {
            throw new RuntimeException("create record error");
        }
        // 返回
        return BeanUtils.toBean(recordRecord, RecordRecordRespVO.class);
    }

    // 删除附件，通过recordId
    public void deleteFileAttachment(Long recordId) {
        recordFileAttachmentService.deleteRecordFileAttachmentByRecord(recordId);
    }

    // 添加文件记录附件
    public void createFileAttachment(List<UploadFileVo> files, Long recordId) {
//        List<UploadFileVo> files = createReqVO.getFiles();
        if (!ObjectUtils.isEmpty(files)) {
            List<RecordFileAttachmentSaveReqVO> createAttachmentReqVOList = new ArrayList<>();
            for (UploadFileVo file : files) {
                RecordFileAttachmentSaveReqVO createAttachmentReqVO = new RecordFileAttachmentSaveReqVO();
                createAttachmentReqVO.setRecordId(recordId);
                createAttachmentReqVO.setFileId(file.getId());
                createAttachmentReqVO.setMainId(recordId);
                createAttachmentReqVO.setCurrentFlag(1);
                long l = System.currentTimeMillis();
                createAttachmentReqVO.setFileVersion(String.valueOf(l));
                createAttachmentReqVOList.add(createAttachmentReqVO);
            }

            recordFileAttachmentService.createRecordFileAttachmentBatch(createAttachmentReqVOList);
        }
    }

    /**
     * 计算记录状态
     *
     * @param effectiveDate  生效日期
     * @param expirationDate 过期日期
     * @return 记录状态：1-生效中，0-待生效，3-已过期
     */
    private int calculateRecordStatus(LocalDateTime effectiveDate, LocalDateTime expirationDate) {
        LocalDateTime now = LocalDateTime.now();

        // 如果生效日期为空，立即生效
        if (effectiveDate == null) {
            return 1;
        }

        // 当前日期 < 生效日期，待生效
        if (expirationDate == null && effectiveDate.isAfter(now)) {
            return 0;
        }

        // 生效日期 ≤ 当前日期，判断是否过期
        if (effectiveDate.isBefore(now)) {
            // 当前日期 < 过期日期，生效中
            if (expirationDate != null && expirationDate.isBefore(now)) {
                return 3; // 过期
            }
            // 当前日期 ≥ 过期日期，已过期
            return 1;
        }

        // 默认已过期
        return 0;
    }

    public RecordRecordRespVO saveDataWithNewVersion(RecordRecordDO createReqVO) {
        RecordRecordDO recordRecordDO = BeanUtils.toBean(createReqVO, RecordRecordDO.class);
        Long oldId = recordRecordDO.getId();
//        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.setExpirationStatus(0); // 0-正常，1-过期
            recordRecordDO = judgeRootCategoryJson(recordRecordDO);
            //创建新版本
            recordRecordDO.setId(null);
            recordRecordDO.setCurrentFlag(1);
            recordRecordDO.setMainId(createReqVO.getMainId());
            recordRecordDO.setVersion(recordRecordDO.getNewVersion());// 新版本号
            recordRecordMapper.insert(recordRecordDO);

            // 根据新版本文件的有效状态，来处理旧版本
            Integer recordStatus = recordRecordDO.getRecordStatus();
            RecordRecordDO oldRecordRecordDO = new RecordRecordDO();
            oldRecordRecordDO.setId(oldId);
            oldRecordRecordDO.setCurrentFlag(0);// 旧版本
            if (recordStatus == 1) {  // 作废旧版本文件
                oldRecordRecordDO.setCancelFlag(1); // 作废
            }
            recordRecordMapper.updateById(oldRecordRecordDO);
            // 添加文件记录附件
            createFileAttachment(createReqVO.getFiles(), recordRecordDO.getId());
            // 返回
            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");
        }
    }


    // 流程--查询记录列表 // TODO
//    @Override
//    public List<RecordRecordRespVO> getRecordList(RecordRecordPageReqVO pageReqVO) {
//
//        String appraisalFlag = pageReqVO.getAppraisalFlag();
//        Long categoryId = pageReqVO.getCategoryId();
//
//        Page<RecordRecordSaveReqVO> page = new Page<>(1, 999);
//
//        if (appraisalFlag.equals("1")) { // 评审获取所有需要参加评审的列表
//            // 查询所有 根分类上 appraisalFlag 为 1 的数据
//            String appraisal = "\"appraisalFlag\":" + 1 + ",";
//
//            List<RecordCategoryDO> recordCategoryDOS = recordCategoryService.selectCategoryAppraisalList(appraisal, null);
//            // 获取所有 分类id
//            List<String> categoryIdPath = new ArrayList<>();
//            recordCategoryDOS.forEach(item -> {
//                Long id = item.getId();
//                String idPath = "/0//" + id + "//"; // 根分类的路径
//                categoryIdPath.add(idPath);
//            });
//            if (ObjectUtils.isEmpty(categoryIdPath)) return new ArrayList<>();
//            // 查询 分类下面所有的记录
//            pageReqVO.setRecordStatus(1);
//            IPage<RecordRecordDO> recordRecordDOS = recordRecordMapper.selectRecordByIdPathLike(page, pageReqVO, categoryIdPath);
//            return BeanUtils.toBean(recordRecordDOS.getRecords(), RecordRecordRespVO.class);
//
//        }
//        // TODO 待删除
//        RecordCategoryDO recordCategoryDO = validateRecordCategoryExists(categoryId);
//        if (categoryId == null) CommonResult.error(RECORD_CATEGORY_NOT_EXISTS);
//
//        // 校验分类存在
//        if (ObjectUtils.isEmpty(recordCategoryDO)) return new ArrayList<>();
//        String idPath = recordCategoryDO.getIdPath();
//
//        if (ObjectUtils.isEmpty(idPath)) return new ArrayList<>();
//        Long rootCategoryId = getRootCategoryId(idPath);
//
//        // 判断是否有权限
//        // 判断是否有当前分类的父分类权限 （可编辑，可查看，管理员--> 任意条件）
//        RecordPermissionDO recordPermissionDO = new RecordPermissionDO();
//        recordPermissionDO.setSourceId(categoryId);
//        List<RecordPermissionDO> recordPermissionDOS = recordPermissionService.selectPermissionList(recordPermissionDO);
//
//        List<RecordRecordDO> recordRecordList;
//
//        if (recordPermissionDOS.isEmpty()) return new ArrayList<>();
//
//        boolean b = getRecordReviewList(rootCategoryId);
//        if (!b) return new ArrayList<>();
//
//        String businessType = pageReqVO.getBusinessType();
//        if (ObjectUtils.isEmpty(businessType)) return new ArrayList<>();
//
//        pageReqVO.setRecordStatus(1); // 查询当前有效和 即将生效的文件
//        pageReqVO.setCancelFlag(0); // 作废状态
//        pageReqVO.setExpirationStatus(0); // 过期状态
//
//
//        IPage<RecordRecordDO> iPage = recordRecordMapper.selectRecordWithApplyPage(page, pageReqVO);

    /// /        PageResult<RecordRecordDO> result = new PageResult<>(iPage.getRecords(), iPage.getTotal());
//        recordRecordList = iPage.getRecords();
//        return BeanUtils.toBean(recordRecordList, RecordRecordRespVO.class);
//
//    }

    // 文件提交，修改生效状态
//    @Override
//    public RecordRecordDO recordSubmitStatus(RecordRecordDO recordDO) {
//        Integer recordStatus = recordDO.getRecordStatus();
//        if (recordStatus != null && recordStatus == 1)
//            throw exception0(RECORD_APPLY_NOT_EXISTS.getCode(), "文件已提交，无法提交申请");
////        RecordCategoryDO recordCategory = recordCategoryService.getRecordCategory(recordDO.getCategoryId());
//        // 获取分类的根分类Id
////        String idPath = recordCategory.getIdPath();
////        Optional<String> segment = RecordCommonUtils.getSegment(idPath, 1);
////        String s = segment.orElse(null);
////        if (ObjectUtils.isEmpty(s))
////            throw exception(RECORD_APPLY_NOT_EXISTS);
////        RecordCategoryDO category = recordCategoryService.getRecordCategory(Long.valueOf(s));
////        String customConfig = category.getCustomConfig();
////        if (ObjectUtils.isEmpty(customConfig)) { // 空，直接判断是否到生效日期
//        // 判断是否到生效日期
////            RecordRecordDO effectiveRecordRecordDO = isEffective(recordDO);
////            this.updateRecordRecordById(effectiveRecordRecordDO);
////            return true;
////        }
////        JSONObject jsonObject = JSONObject.parseObject(customConfig);
////        Integer submitFlag = jsonObject.getInteger("submitFlag");
////        if (submitFlag == 0) {
//        // 不允许提交，直接修改文件记录状态
////            recordDO.setRecordStatus(1); // 已生效
//        RecordRecordDO effectiveRecordRecordDO = isEffective(recordDO);
//        this.updateRecordRecordById(effectiveRecordRecordDO);
//        return effectiveRecordRecordDO;
////            return true;
////        } else { // 需要走流程
////            recordDO.setSubmitFlag(1);
////            recordDO.setRecordStatus(0);
////            this.updateRecordRecordById(recordDO);
////        }
//
////        return false;
//    }
//
//    // 判断文件记录生效状态
//    public RecordRecordDO isEffective(RecordRecordDO recordDO) {
//        LocalDateTime effectiveDate = recordDO.getEffectiveDate();
//        if (effectiveDate == null) { // 没有生效日期，立即生效
//            recordDO.setRecordStatus(1);
//        } else {
//            recordDO.setRecordStatus(0); // 待生效
//            LocalDateTime now = LocalDateTime.now();
//            if (now.isAfter(effectiveDate) || now.isEqual(effectiveDate)) {
//                recordDO.setRecordStatus(1); // 已生效
//            }
//        }
//        return recordDO;
//    }


    //通过跟分类的自定义属性判断文件状态
    public RecordRecordDO judgeRootCategoryJson(RecordRecordDO recordDO) {
        RecordCategoryDO categoryDO = recordCategoryService.getRecordCategory(recordDO.getCategoryId());
        String idPath = categoryDO.getIdPath();
        Long rootCategoryId = getRootCategoryId(idPath);
        RecordCategoryDO category = recordCategoryService.getRecordCategory(rootCategoryId);
        String customConfig = category.getCustomConfig();
        LocalDateTime effectiveDate = recordDO.getEffectiveDate();
        LocalDateTime expirationDate = recordDO.getExpirationDate();

        if (ObjectUtils.isEmpty(customConfig)) { //不需要提交，判断状态
            int sts = calculateRecordStatus(effectiveDate, expirationDate);
            if (sts == 3) {
                recordDO.setExpirationStatus(1); //过期
                recordDO.setRecordStatus(0);// 状态无效
            } else recordDO.setRecordStatus(sts);
        } else {
            JSONObject jsonObject = JSONObject.parseObject(customConfig);
            Integer submitFlag = jsonObject.getInteger("submitFlag");
            if (submitFlag == null || submitFlag == 0) { // 不需要提交的，判断状态
                int sts = calculateRecordStatus(effectiveDate, expirationDate);
                if (sts == 3) recordDO.setExpirationStatus(1); //过期
                else recordDO.setRecordStatus(sts);
            }
        }
        return recordDO;
    }

    @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)) { // 不是新版本，直接更新
            RecordRecordDO recordRecordDO = judgeRootCategoryJson(updateObj);
            recordRecordMapper.updateById(recordRecordDO);

            //删除附件
            //TODO
            deleteFileAttachment(updateObj.getId());
            // 保存附件
            List<UploadFileVo> files = updateObj.getFiles();
            createFileAttachment(files, updateObj.getId());
        } else {// 新版本
            // 是否回收
//            Integer collectionFlag = updateReqVO.getCollectionFlag();
//            if (collectionFlag != null && collectionFlag == 1) { // 不为null, 回收旧版本权限
            recordPermissionRecycle(updateObj.getId());  // 回收旧版本权限
//            }
            // 创建新版本
            return saveDataWithNewVersion(updateObj);
        }
        // 更新
        businessFileService.deleteBusinessFileList(updateReqVO.getDeleteFileIdList());
        return BeanUtils.toBean(updateReqVO, RecordRecordRespVO.class);
    }

    //    回收文件权限
    public void recordPermissionRecycle(Long recordId) {
        // 回收文件权限 - 直接更新，无需先查询
        LambdaUpdateWrapper<RecordPermissionDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RecordPermissionDO::getSourceType, RecordConstants.PermissionSourceType.RECORD);
        updateWrapper.eq(RecordPermissionDO::getSourceId, recordId);
        updateWrapper.set(RecordPermissionDO::getCancelFlag, "1");

        recordPermissionService.updatePermission(updateWrapper);
    }

    @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 RecordRecordDO validateRecordRecordExists(Long id) {
        RecordRecordDO recordRecordDO = recordRecordMapper.selectById(id);
        if (recordRecordDO == null) {
            throw exception(RECORD_RECORD_NOT_EXISTS);
        }
        return recordRecordDO;
    }

    private RecordCategoryDO validateRecordCategoryExists(Long id) {
        RecordCategoryDO recordCategoryDO = recordCategoryService.selectById(id);
        if (recordCategoryDO == null) {
            return new RecordCategoryDO();
        }
        return recordCategoryDO;
    }


    @Override
    public RecordRecordDO getRecordRecord(Long id) {
        RecordRecordDO recordRecordDO = recordRecordMapper.selectById(id);
        if (!ObjectUtils.isEmpty(recordRecordDO)) {
            Long categoryId = recordRecordDO.getCategoryId();
            RecordCategoryDO recordCategoryDO = recordCategoryService.selectById(categoryId);
            recordRecordDO.setCategoryName(recordCategoryDO.getName());
        }
        return recordRecordDO;
    }

    // 获取当前分类的根分类Id
    public Long getRootCategoryId(String idPath) {
        Optional<String> segment = RecordCommonUtils.getSegment(idPath, 1); // /0//11/122546211/
        String s = segment.orElse(null);
        if (ObjectUtils.isEmpty(s))
            throw exception(RECORD_APPLY_NOT_EXISTS);
//        Long parentId = recordCategoryDO.getParentId(); // 获取根分类
        return Long.valueOf(s); // 获取根分类
    }

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

    public PageResult<RecordRecordDO> addCustomConfig(Long rootCategoryId, PageResult<RecordRecordDO> result) {
        Object finalParse = customConfigParseJson(rootCategoryId);
        result.getList().forEach(record -> {
            try {
                record.setCustomConfig(finalParse);
            } catch (Exception e) {
                throw exception(RECORD_RECORD_NOT_EXISTS);
            }
        });
        return result;
    }

    public List<Long> selectCategoryIds(Long categoryId) {
        // 判断当前分类上有没有子分类
        String categoryIdPath = "/" + categoryId;
        List<RecordCategoryDO> recordCategoryDOS = recordCategoryService.selectListByCategoryIdIdPath(categoryIdPath);
        // 通过分类Id获取文件记录分页
        return recordCategoryDOS.stream().map(RecordCategoryDO::getId).toList();
    }

    /**
     * 查询文件记录分页
     *
     * @param pageReqVO  分页参数
     * @param categoryId 分类Id
     * @param recordIds  (非必传)
     * @return
     */
    public PageResult<RecordRecordDO> selectRecordPage(RecordRecordPageReqVO pageReqVO, Long categoryId,
                                                       List<Long> recordIds) {
        List<Long> categoryIds = selectCategoryIds(categoryId);
        LambdaQueryWrapper<RecordRecordDO> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.in(RecordRecordDO::getCategoryId, categoryIds);
        if(!ObjectUtils.isEmpty(pageReqVO.getCancelFlag()))  // 作废
            lambdaQueryWrapper.eq(RecordRecordDO::getCancelFlag, pageReqVO.getCancelFlag());
        if (!ObjectUtils.isEmpty(pageReqVO.getExpirationStatus())) // 过期
            lambdaQueryWrapper.eq(RecordRecordDO::getExpirationStatus, pageReqVO.getExpirationStatus());
        if (!ObjectUtils.isEmpty(pageReqVO.getCurrentFlag()))
            lambdaQueryWrapper.like(RecordRecordDO::getCurrentFlag, pageReqVO.getCurrentFlag());// 查询最新版本/旧版本
        if (!ObjectUtils.isEmpty(pageReqVO.getName()))
            lambdaQueryWrapper.like(RecordRecordDO::getName, pageReqVO.getName());
        if (!ObjectUtils.isEmpty(pageReqVO.getCode()))
            lambdaQueryWrapper.like(RecordRecordDO::getCode, pageReqVO.getCode());
        if (!ObjectUtils.isEmpty(recordIds)) lambdaQueryWrapper.in(RecordRecordDO::getId, recordIds); // 获取指定文件记录
        return recordRecordMapper.selectPage(pageReqVO, lambdaQueryWrapper);
    }

    @Override
    public PageResult<RecordRecordDO> getRecordRecordPage(RecordRecordPageReqVO pageReqVO) {
        Long categoryId = pageReqVO.getCategoryId();
        RecordCategoryDO recordCategoryDO = validateRecordCategoryExists(categoryId);
        if (recordCategoryDO.getId() == null) return PageResult.empty();

        // 判断是否有自定义字段
        String idPath = recordCategoryDO.getIdPath();
        Long parentId = getRootCategoryId(idPath);

        // 如果是最高管理员,super admin
        boolean b = recordPermissionService.judgeIsSuperAdmin();
        if (b) {
            PageResult<RecordRecordDO> recordRecordDOPageResult = selectRecordPage(pageReqVO, categoryId, null);
            return addCustomConfig(parentId, recordRecordDOPageResult);
        }

        // 判断是否有当前分类的父分类权限 （可编辑，可查看，管理员--> 任意条件）
        RecordPermissionDO recordPermissionDO = new RecordPermissionDO();
        recordPermissionDO.setSourceId(parentId);
        List<RecordPermissionDO> recordPermissionDOS = recordPermissionService.selectPermissionList(recordPermissionDO);

        // 没有分类的权限，判断是否有文件记录的权限，并获取记录列表
        if (ObjectUtils.isEmpty(recordPermissionDOS)) {

//            RecordPermissionDO permissionDO = new RecordPermissionDO();
//            permissionDO.setCancelFlag("0"); // 作废
//            permissionDO.setExpirationStatus("0"); // 过期
            List<RecordPermissionDO> permissionDOList = recordPermissionService.selectRecordPermissionList();
            if (ObjectUtils.isEmpty(permissionDOList)) return PageResult.empty();

            //获取有权限的记录Id
            List<Long> recordIds = permissionDOList.stream().map(RecordPermissionDO::getSourceId).toList();
            PageResult<RecordRecordDO> result = selectRecordPage(pageReqVO, categoryId, recordIds);
            return result;
        }

        PageResult<RecordRecordDO> result = selectRecordPage(pageReqVO, categoryId, null);

        String admin = RecordConstants.PermissionType.ADMIN;
        //判断 recordPermissionDOS 中是否有管理员权限，customConfig（仅管理员权限时填充）
        if (recordPermissionDOS.stream().anyMatch(item -> item.getPermission().equals(admin))) {
            return addCustomConfig(parentId, result);
        }

        return result;
    }

    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();
        pageReqVO.setCurrentFlag(0); // 查询历史版本
        if (ObjectUtils.isEmpty(mainId)) throw exception(RECORD_RECORD_NOT_EXISTS);
        return recordRecordMapper.selectPage(pageReqVO);
    }

    /**
     * 定时任务：将生效日期已到的，并且是有效的记录状态，更新为已生效（recordStatus = 1）
     * 筛选条件：effectiveDate <= 当前时间 <= 过期日期 且 recordStatus != 1
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateRecordStatus() {
        RecordRecordDO recordDO = new RecordRecordDO();
        // 查询审批之后待生效的记录
        recordDO.setSubmitFlag(0);
        List<RecordRecordDO> recordRecordDOS = updateSubmitEffectRecordStatus(recordDO);// 不需要提交
// 去除上一个的条件
//        lambdaUpdateWrapper.eq(RecordRecordDO::getSubmitFlag, 0).clear();
        recordDO.setSubmitFlag(1);
        recordDO.setApplyStatus(QmsCommonConstant.COMPLETED);
        List<RecordRecordDO> recordRecordDOList = updateSubmitEffectRecordStatus(recordDO);// 需要提交

        // 新文件生效，作废旧版本文件
        recordRecordDOS.addAll(recordRecordDOList);
        List<Long> mainIds = recordRecordDOS.stream().map(RecordRecordDO::getMainId).toList();
        LambdaUpdateWrapper<RecordRecordDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(RecordRecordDO::getMainId, mainIds); // 所有版本
        lambdaUpdateWrapper.eq(RecordRecordDO::getCurrentFlag, 0); // 旧版本
        lambdaUpdateWrapper.eq(RecordRecordDO::getCancelFlag, 0); //未作废的
        lambdaUpdateWrapper.set(RecordRecordDO::getCancelFlag, 1); // 作废
        lambdaUpdateWrapper.set(RecordRecordDO::getRecordStatus, 0); // 无效
        recordRecordMapper.update(lambdaUpdateWrapper);


        return recordRecordDOS.size();
    }

    // 跟新不需要提交，文件记录生效状态
//    public Integer updateNotSubmitEffectRecordStatus(LambdaUpdateWrapper<RecordRecordDO> lambdaUpdateWrapper) {
//        lambdaUpdateWrapper.eq(RecordRecordDO::getSubmitFlag, 0);
//        return recordRecordMapper.update(lambdaUpdateWrapper);
//    }

    // 跟新不需要提交，文件记录生效状态
    public List<RecordRecordDO> updateSubmitEffectRecordStatus(RecordRecordDO recordDO) {
        LambdaQueryWrapper<RecordRecordDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RecordRecordDO::getRecordStatus, 0); // 待生效
        lambdaQueryWrapper.lt(RecordRecordDO::getEffectiveDate, LocalDateTime.now());
        lambdaQueryWrapper.ge(RecordRecordDO::getExpirationDate, LocalDateTime.now());
//        lambdaUpdateWrapper.set(RecordRecordDO::getRecordStatus, 1);

        lambdaQueryWrapper.eq(RecordRecordDO::getSubmitFlag, recordDO.getSubmitFlag());
        String applyStatus = recordDO.getApplyStatus();
        if (!ObjectUtils.isEmpty(applyStatus))lambdaQueryWrapper.eq(RecordRecordDO::getApplyStatus, applyStatus); // 审核完成的
        return recordRecordMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 查询生效的记录(包括需要提交，和不提交的数据)
     *
     * @param submitFlag
     * @param pageReqVO
     * @return
     */
    public PageResult<RecordRecordDO> selectEffectRecordList(int submitFlag, RecordRecordPageReqVO pageReqVO) {
        Page<RecordRecordSaveReqVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        if (submitFlag == 1) { // 不需要提交数据
            pageReqVO.setSubmitFlag(1);
            IPage<RecordRecordDO> recordRecordDOPageResult = recordRecordMapper.getEffectRecordPage(page, pageReqVO);
            return new PageResult<>(recordRecordDOPageResult.getRecords(), recordRecordDOPageResult.getTotal());
        } else { // 需要提交数据
            pageReqVO.setSubmitFlag(0);
            IPage<RecordRecordDO> submitEffectRecordPage = recordRecordMapper.getEffectRecordPage(page, pageReqVO);
            return new PageResult<>(submitEffectRecordPage.getRecords(), submitEffectRecordPage.getTotal());
        }
    }


    @Override
    public PageResult<RecordRecordDO> getEffectiveRecordPage(RecordRecordPageReqVO pageReqVO) {
        Long categoryId = pageReqVO.getCategoryId();
        RecordCategoryDO recordCategoryDO = validateRecordCategoryExists(categoryId);
        if (categoryId == null) CommonResult.error(RECORD_CATEGORY_NOT_EXISTS);

        // 校验分类存在
        if (ObjectUtils.isEmpty(recordCategoryDO)) return PageResult.empty();
        String idPath = recordCategoryDO.getIdPath();
        if (ObjectUtils.isEmpty(idPath)) return PageResult.empty();

        Long parentId = getRootCategoryId(idPath);
        if (parentId == null) return PageResult.empty();
        RecordCategoryDO categoryDO = recordCategoryService.selectById(parentId);

        boolean b = recordPermissionService.judgeIsSuperAdmin(); // 判断是否是超级管理员

        if (!b) {
            // 判断是否有当前分类的父分类权限 （可编辑，可查看，管理员--> 任意条件）
            RecordPermissionDO recordPermissionDO = new RecordPermissionDO();
            recordPermissionDO.setSourceId(parentId);
            List<RecordPermissionDO> recordPermissionDOS = recordPermissionService.selectPermissionList(recordPermissionDO);
            if (ObjectUtils.isEmpty(recordPermissionDOS)) return PageResult.empty();
        }

        List<Long> categoryIds = selectCategoryIds(categoryId); // 获取所有子分类

        String customConfig = categoryDO.getCustomConfig();
        String appraisalFlag = pageReqVO.getAppraisalFlag();

        pageReqVO.setCategoryIds(categoryIds);

        // 判断是否需要提交（json）
        Integer submitFlag = 0;
        if (!ObjectUtils.isEmpty(customConfig)) {
            JSONObject jsonObject = JSONObject.parseObject(customConfig);
            submitFlag = jsonObject.getInteger("submitFlag"); // 提交标志
            if (submitFlag == null) submitFlag = 0;
        }
        // 需要评审的文件
        if (!ObjectUtils.isEmpty(appraisalFlag) && appraisalFlag.equals("1")) {
            // 查询所有 根分类上 appraisalFlag 为 1 的数据
            RecordCategoryDO recordCategoryDOS = recordCategoryService.selectCategoryAppraisalDO(parentId);
            // 不需要评审，直接返回null
            if (ObjectUtils.isEmpty(recordCategoryDOS)) return PageResult.empty();

            // 查询有效，或者提交审批完成，将来生效的记录 (recordStatus = 1 or (applyStatus = 'completed' and now() > effectiveDate))
            // 需要评审，且需要提交的数据
            return selectEffectRecordList(submitFlag, pageReqVO);
        }

        // 通用查询，查询，有效，或将来有效的记录
        return selectEffectRecordList(submitFlag, pageReqVO);

    }

    @Override
    public PageResult<RecordRecordRespVO> getLookRecordList(RecordRecordPageReqVO pageReqVO) {
        Long categoryId = pageReqVO.getCategoryId();
        if (categoryId == null) return PageResult.empty();
        PageResult<RecordRecordDO> recordRecordDOPageResult = selectRecordPage(pageReqVO, categoryId, null);
        return BeanUtils.toBean(recordRecordDOPageResult, RecordRecordRespVO.class);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateExpireRecordJob() {
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<RecordRecordDO> updateWrapper = Wrappers.lambdaQuery();
        updateWrapper.eq(RecordRecordDO::getExpirationStatus, 0) // 未过期
                .eq(RecordRecordDO::getRecordStatus, 1) // 已生效
                .lt(RecordRecordDO::getExpirationDate, now); // 过期时间小于当前时间
        List<RecordRecordDO> recordRecordDOS = recordRecordMapper.selectList(updateWrapper);
        if (ObjectUtils.isEmpty(recordRecordDOS)) return 0;
        List<Long> recordIds = new ArrayList<>();
        recordRecordDOS.forEach(item -> {
            recordIds.add(item.getId());
            item.setExpirationStatus(1); // 过期
//            item.setCancelFlag(1);
        });
        recordRecordMapper.updateBatch(recordRecordDOS);

        // 回收权限
        LambdaUpdateWrapper<RecordPermissionDO> update = Wrappers.lambdaUpdate();
        update.eq(RecordPermissionDO::getSourceType, RecordConstants.PermissionSourceType.RECORD);
        update.in(RecordPermissionDO::getTargetId, recordIds);
        update.set(RecordPermissionDO::getExpirationStatus, 1); // 过期
        recordPermissionService.updatePermission(update);
        return recordRecordDOS.size();
    }

    @Override
    public int updateRecord(LambdaUpdateWrapper<RecordRecordDO> updateWrapper) {
        return recordRecordMapper.update(updateWrapper);
    }

    @Override
    public PageResult<RecordRecordRespVO> selectRecordRecordPage(RecordRecordPageReqVO pageReqVO) {
        Long categoryId = pageReqVO.getCategoryId();
        pageReqVO.setCurrentFlag(1);// 当前版本
        if (categoryId == null) return PageResult.empty();
        PageResult<RecordRecordDO> recordRecordDOPageResult = selectRecordPage(pageReqVO, categoryId, null);
        return BeanUtils.toBean(recordRecordDOPageResult, RecordRecordRespVO.class);
    }
}