package com.hotwj.platform.securityManagement.hiddenDangerInspection.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.common.helper.DriverLoginContextHelper;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.flow.service.ISysFlowService;
import com.hotwj.platform.integration.ocr.SignatureVerifyService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.HotHiddenDangerInspection;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.HotHiddenDangerInspectionAuditHistory;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.bo.HotHiddenDangerInspectionBo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.vo.HotHiddenDangerInspectionAuditHistoryVo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.vo.HotHiddenDangerInspectionVo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.mapper.HotHiddenDangerInspectionAuditHistoryMapper;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.mapper.HotHiddenDangerInspectionMapper;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.service.IHotHiddenDangerInspectionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
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.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.YearMonth;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 隐患排查-排查项目Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-31
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotHiddenDangerInspectionServiceImpl implements IHotHiddenDangerInspectionService {

    private final HotHiddenDangerInspectionMapper baseMapper;
    private final HotHiddenDangerInspectionAuditHistoryMapper historyMapper;
    private final ISysFlowService flowService;
    private final IHotSystemNotificationService notificationService;
    private final SignatureVerifyService signatureVerifyService;

    /**
     * 查询隐患排查-排查项目
     *
     * @param id 主键
     * @return 隐患排查-排查项目
     */
    @Override
    public HotHiddenDangerInspectionVo queryById(Long id) {
        HotHiddenDangerInspectionVo vo = baseMapper.selectVoById(id);
        if (vo == null) {
            return null;
        }
        vo.setRejectHistoryList(queryRejectHistoryList(id));
        fillTaskId(vo, LoginHelper.getBusinessUserId());
        return vo;
    }

    /**
     * 分页查询隐患排查-排查项目列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 隐患排查-排查项目分页列表
     */
    @Override
    public TableDataInfo<HotHiddenDangerInspectionVo> queryPageList(HotHiddenDangerInspectionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotHiddenDangerInspection> lqw = buildQueryWrapper(bo);
        Page<HotHiddenDangerInspectionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        fillFlowExtras(result.getRecords());

        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<HotHiddenDangerInspectionVo> queryMobilePlanPage(String keyword, PageQuery pageQuery) {
        Long companyId = LoginHelper.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("当前登录用户无公司信息");
        }
        boolean isDriver = DriverLoginContextHelper.isDriverPort();
        String driverId = null;
        String vehicleId = null;
        if (isDriver) {
            HotDriver driver = DriverLoginContextHelper.getCurrentDriver();
            driverId = driver.getId();
            vehicleId = driver.getVehicleId();
        }
        String currentMonth = YearMonth.now().toString();
        Page<HotHiddenDangerInspectionVo> page = pageQuery.build();
        List<HotHiddenDangerInspectionVo> rows = baseMapper.selectMobilePlanPage(
                page,
                companyId,
                !isDriver,
                driverId,
                vehicleId,
                StringUtils.trimToNull(keyword),
                currentMonth
        );
        page.setRecords(rows);
        fillFlowExtras(rows);
        return TableDataInfo.build(page);
    }

    /**
     * 查询符合条件的隐患排查-排查项目列表
     *
     * @param bo 查询条件
     * @return 隐患排查-排查项目列表
     */
    @Override
    public List<HotHiddenDangerInspectionVo> queryList(HotHiddenDangerInspectionBo bo) {
        LambdaQueryWrapper<HotHiddenDangerInspection> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotHiddenDangerInspection> buildQueryWrapper(HotHiddenDangerInspectionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotHiddenDangerInspection> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(HotHiddenDangerInspection::getId);
        lqw.eq(bo.getCompanyId() != null, HotHiddenDangerInspection::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getPlanId() != null, HotHiddenDangerInspection::getPlanId, bo.getPlanId());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), HotHiddenDangerInspection::getProjectName, bo.getProjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectId()), HotHiddenDangerInspection::getProjectId, bo.getProjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckContentJson()), HotHiddenDangerInspection::getCheckContentJson, bo.getCheckContentJson());
        lqw.eq(StringUtils.isNotBlank(bo.getDangerDesc()), HotHiddenDangerInspection::getDangerDesc, bo.getDangerDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachmentUrl()), HotHiddenDangerInspection::getAttachmentUrl, bo.getAttachmentUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckerId()), HotHiddenDangerInspection::getCheckerId, bo.getCheckerId());
        lqw.like(StringUtils.isNotBlank(bo.getCheckerName()), HotHiddenDangerInspection::getCheckerName, bo.getCheckerName());
        if (StringUtils.isNotBlank(bo.getKeyword())) {
            String keyword = bo.getKeyword().trim();
            lqw.like(HotHiddenDangerInspection::getProjectName, keyword);
        }
        lqw.eq(bo.getCheckDate() != null, HotHiddenDangerInspection::getCheckDate, bo.getCheckDate());
        lqw.eq(bo.getApproverId() != null, HotHiddenDangerInspection::getApproverId, bo.getApproverId());
        lqw.like(StringUtils.isNotBlank(bo.getApproverName()), HotHiddenDangerInspection::getApproverName, bo.getApproverName());
        lqw.eq(bo.getStatus() != null, HotHiddenDangerInspection::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getSignImgUrl()), HotHiddenDangerInspection::getSignImgUrl, bo.getSignImgUrl());
        lqw.eq(bo.getIsDeleted() != null, HotHiddenDangerInspection::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    private void fillFlowExtras(List<HotHiddenDangerInspectionVo> records) {
        if (records == null || records.isEmpty()) {
            return;
        }
        String userId = LoginHelper.getBusinessUserId();
        for (HotHiddenDangerInspectionVo vo : records) {
            if (vo == null) {
                continue;
            }
            fillTaskId(vo, userId);
            if (StringUtils.isBlank(vo.getFlowStatus())) {
                if ("REJECT".equalsIgnoreCase(vo.getAuditResult())) {
                    vo.setFlowStatus("REJECTED");
                } else if (vo.getStatus() == null || vo.getStatus() == 0L || vo.getStatus() == 1L) {
                    vo.setFlowStatus("TODO");
                } else if (vo.getStatus() == 3L || vo.getStatus() == 9L) {
                    vo.setFlowStatus("DONE");
                } else {
                    vo.setFlowStatus("PROCESSING");
                }
            }
        }
    }

    /**
     * 新增隐患排查-排查项目
     *
     * @param bo 隐患排查-排查项目
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotHiddenDangerInspectionBo bo) {
        HotHiddenDangerInspection add = MapstructUtils.convert(bo, HotHiddenDangerInspection.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改隐患排查-排查项目
     *
     * @param bo 隐患排查-排查项目
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(HotHiddenDangerInspectionBo bo) {
        HotHiddenDangerInspection original = baseMapper.selectById(bo.getId());
        if (original == null) {
            throw new ServiceException("排查记录不存在");
        }
        HotHiddenDangerInspection update = MapstructUtils.convert(bo, HotHiddenDangerInspection.class);
        validEntityBeforeSave(update);
        String signImgUrl = bo.getSignImgUrl();
        if (DriverLoginContextHelper.isDriverPort() && StringUtils.isNotBlank(signImgUrl)) {
            String checkerName = bo.getCheckerName();

            if (StringUtils.isBlank(checkerName)) {
                throw new ServiceException("排查人姓名不能为空");
            }
            signatureVerifyService.validateSelfSignature(parseSignatureOssId(signImgUrl), checkerName);
        }
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag && shouldResumeRejectedFlow(original)) {
            resumeRejectedFlow(original);
        } else if (flag && shouldStartAuditFlow(original)) {
            String initiator = String.valueOf(LoginHelper.getBusinessUserId());
            String approverId = bo.getApproverId() != null ? String.valueOf(bo.getApproverId()) : null;
            if (StringUtils.isBlank(approverId)) {
                throw new ServiceException("请选择审核人");
            }
            Long nextSubmitVersion = buildNextSubmitVersion(original);
            String instanceId = flowService.startFlow(
                    "HIDDEN_DANGER_CHECK",
                    String.valueOf(original.getId()),
                    original.getCompanyId(),
                    initiator,
                    approverId
            );
            baseMapper.update(
                null,
                Wrappers.<HotHiddenDangerInspection>lambdaUpdate()
                    .eq(HotHiddenDangerInspection::getId, original.getId())
                    .set(HotHiddenDangerInspection::getStatus, 2L)
                    .set(HotHiddenDangerInspection::getInstanceId, instanceId)
                    .set(HotHiddenDangerInspection::getFlowStatus, "SUBMITTED")
                    .set(HotHiddenDangerInspection::getSubmitVersion, nextSubmitVersion)
                    .set(HotHiddenDangerInspection::getAuditDate, null)
                    .set(HotHiddenDangerInspection::getAuditConclusion, null)
                    .set(HotHiddenDangerInspection::getApproverSignImgUrl, null)
                    .set(HotHiddenDangerInspection::getAuditHasDanger, null)
                    .set(HotHiddenDangerInspection::getAuditResult, null)
                    .set(HotHiddenDangerInspection::getEvaluatorId, null)
                    .set(HotHiddenDangerInspection::getEvaluatorName, null)
                    .set(HotHiddenDangerInspection::getLastRejectReason, null)
                    .set(HotHiddenDangerInspection::getLastRejectTime, null)
                    .set(HotHiddenDangerInspection::getLastRejectById, null)
                    .set(HotHiddenDangerInspection::getLastRejectByName, null)
            );

            try {
                HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                bos.setLevel("普通");
                bos.setContent("你有一条隐患排查需要处理。");
                bos.setSourceType("隐患管理");
                bos.setSenderType("SYSTEM");
                bos.setReceiverType("管理员");
                bos.setReceiverIds(java.util.Collections.singletonList(approverId));
                bos.setIsDeleted(0L);
                notificationService.insertByBo(bos);
            } catch (Exception e) {
                log.warn("Hidden danger inspection assign notify failed approverId={} inspectionId={}", approverId, update.getId(), e);
            }
        }
        return flag;
    }

    private Long parseSignatureOssId(String signImgUrl) {
        String first = signImgUrl.split(",")[0].trim();
        if (!first.matches("^\\d+$")) {
            throw new ServiceException("签名文件格式错误");
        }
        return Long.parseLong(first);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(HotHiddenDangerInspectionBo bo) {
        if (StringUtils.isBlank(bo.getTaskId())) {
            throw new ServiceException("流程任务ID不能为空");
        }
        if (bo.getId() == null) {
            throw new ServiceException("排查记录ID不能为空");
        }
        HotHiddenDangerInspection original = baseMapper.selectById(bo.getId());
        if (original == null) {
            throw new ServiceException("排查记录不存在");
        }
        String auditResult = normalizeAuditResult(bo);
        String auditConclusion = StringUtils.trimToNull(bo.getAuditConclusion());
        Date auditDate = bo.getAuditDate() != null ? bo.getAuditDate() : new Date();
        if ("PASS".equals(auditResult)) {
            if (bo.getAuditHasDanger() == null) {
                throw new ServiceException("请选择是否存在隐患");
            }
            if (bo.getAuditHasDanger() == 1L && bo.getEvaluatorId() == null) {
                throw new ServiceException("请选择评估人");
            }
            baseMapper.update(
                null,
                Wrappers.<HotHiddenDangerInspection>lambdaUpdate()
                    .eq(HotHiddenDangerInspection::getId, original.getId())
                    .set(HotHiddenDangerInspection::getApproverId, bo.getApproverId())
                    .set(HotHiddenDangerInspection::getApproverName, bo.getApproverName())
                    .set(HotHiddenDangerInspection::getAuditDate, auditDate)
                    .set(HotHiddenDangerInspection::getAuditConclusion, auditConclusion)
                    .set(HotHiddenDangerInspection::getApproverSignImgUrl, bo.getApproverSignImgUrl())
                    .set(HotHiddenDangerInspection::getAuditHasDanger, bo.getAuditHasDanger())
                    .set(HotHiddenDangerInspection::getEvaluatorId, bo.getEvaluatorId())
                    .set(HotHiddenDangerInspection::getEvaluatorName, bo.getEvaluatorName())
                    .set(HotHiddenDangerInspection::getAuditResult, "PASS")
            );
            flowService.audit(
                bo.getTaskId(),
                true,
                auditConclusion,
                LoginHelper.getBusinessUserId()
            );
            return;
        }
        if (StringUtils.isBlank(auditConclusion)) {
            throw new ServiceException("审核不通过原因不能为空");
        }

        long nextRejectCount = original.getRejectCount() == null ? 1L : original.getRejectCount() + 1L;
        baseMapper.update(
            null,
            Wrappers.<HotHiddenDangerInspection>lambdaUpdate()
                .eq(HotHiddenDangerInspection::getId, original.getId())
                .set(HotHiddenDangerInspection::getApproverId, bo.getApproverId())
                .set(HotHiddenDangerInspection::getApproverName, bo.getApproverName())
                    .set(HotHiddenDangerInspection::getStatus, 10L)
                .set(HotHiddenDangerInspection::getFlowStatus, "REJECTED")
                .set(HotHiddenDangerInspection::getAuditDate, auditDate)
                .set(HotHiddenDangerInspection::getAuditConclusion, auditConclusion)
                .set(HotHiddenDangerInspection::getApproverSignImgUrl, bo.getApproverSignImgUrl())
                .set(HotHiddenDangerInspection::getAuditHasDanger, null)
                .set(HotHiddenDangerInspection::getEvaluatorId, null)
                .set(HotHiddenDangerInspection::getEvaluatorName, null)
                .set(HotHiddenDangerInspection::getAuditResult, "REJECT")
                .set(HotHiddenDangerInspection::getRejectCount, nextRejectCount)
                .set(HotHiddenDangerInspection::getLastRejectReason, auditConclusion)
                .set(HotHiddenDangerInspection::getLastRejectTime, auditDate)
                .set(HotHiddenDangerInspection::getLastRejectById, bo.getApproverId())
                .set(HotHiddenDangerInspection::getLastRejectByName, bo.getApproverName())
        );
        bo.setAuditConclusion(auditConclusion);
        saveRejectHistory(original, bo, nextRejectCount, auditDate);
        flowService.audit(
            bo.getTaskId(),
            false,
            auditConclusion,
            LoginHelper.getBusinessUserId()
        );
    }

    private boolean shouldStartAuditFlow(HotHiddenDangerInspection original) {
        if (original == null || StringUtils.isNotBlank(original.getInstanceId())) {
            return false;
        }
        Long status = original.getStatus();
        return status == null || status == 0L || status == 1L || status == 10L || "REJECTED".equalsIgnoreCase(original.getFlowStatus());
    }

    private boolean shouldResumeRejectedFlow(HotHiddenDangerInspection original) {
        if (original == null || StringUtils.isBlank(original.getInstanceId())) {
            return false;
        }
        Long status = original.getStatus();
        return status != null && status == 10L && "REJECTED".equalsIgnoreCase(original.getFlowStatus());
    }

    private void resumeRejectedFlow(HotHiddenDangerInspection original) {
        String currentUserId = LoginHelper.getBusinessUserId();
        String taskId = flowService.getTaskId(original.getInstanceId(), currentUserId);
        if (StringUtils.isBlank(taskId)) {
            taskId = flowService.getTaskIdByBusinessId("HIDDEN_DANGER_CHECK", String.valueOf(original.getId()), currentUserId);
        }
        if (StringUtils.isBlank(taskId)) {
            taskId = flowService.getCurrentTaskIdByBusinessId("HIDDEN_DANGER_CHECK", String.valueOf(original.getId()));
        }
        if (StringUtils.isBlank(taskId)) {
            throw new ServiceException("当前记录未找到待处理任务，无法重新提交");
        }
        String submitOperatorId = currentUserId;
        var task = flowService.getTaskById(taskId);
        if (task == null) {
            throw new ServiceException("当前记录未找到待处理任务，无法重新提交");
        }
        if (!StringUtils.equals(task.getApproverId(), currentUserId)) {
            if (!DriverLoginContextHelper.isDriverPort() && !canResubmitRejectedRecord(original, currentUserId)) {
                throw new ServiceException("当前用户无权重新提交该记录");
            }
            submitOperatorId = task.getApproverId();
        }
        baseMapper.update(
            null,
            Wrappers.<HotHiddenDangerInspection>lambdaUpdate()
                .eq(HotHiddenDangerInspection::getId, original.getId())
                .set(HotHiddenDangerInspection::getStatus, 2L)
                .set(HotHiddenDangerInspection::getFlowStatus, "SUBMITTED")
                .set(HotHiddenDangerInspection::getAuditDate, null)
                .set(HotHiddenDangerInspection::getAuditConclusion, null)
                .set(HotHiddenDangerInspection::getApproverSignImgUrl, null)
                .set(HotHiddenDangerInspection::getAuditHasDanger, null)
                .set(HotHiddenDangerInspection::getAuditResult, null)
                .set(HotHiddenDangerInspection::getEvaluatorId, null)
                .set(HotHiddenDangerInspection::getEvaluatorName, null)
        );
        flowService.audit(taskId, true, "重新提交", submitOperatorId);
    }

    private boolean canResubmitRejectedRecord(HotHiddenDangerInspection original, String currentUserId) {
        if (original == null || StringUtils.isBlank(currentUserId)) {
            return false;
        }
        if (StringUtils.equals(original.getCheckerId(), currentUserId)) {
            return true;
        }
        if (original.getCreateBy() != null && StringUtils.equals(String.valueOf(original.getCreateBy()), currentUserId)) {
            return true;
        }
        if (DriverLoginContextHelper.isDriverPort()) {
            try {
                HotDriver currentDriver = DriverLoginContextHelper.getCurrentDriver();
                if (currentDriver != null && StringUtils.equals(currentDriver.getId(), original.getCheckerId())) {
                    return true;
                }
                if (currentDriver != null && original.getCreateBy() != null
                        && StringUtils.equals(currentDriver.getId(), String.valueOf(original.getCreateBy()))) {
                    return true;
                }
            } catch (Exception e) {
                log.warn("Resolve current driver for hidden danger resubmit failed, inspectionId={}", original.getId(), e);
            }
        }
        return false;
    }

    private Long buildNextSubmitVersion(HotHiddenDangerInspection original) {
        if (original == null || original.getSubmitVersion() == null || original.getSubmitVersion() < 1L) {
            return 1L;
        }
        return original.getSubmitVersion() + 1L;
    }

    private String normalizeAuditResult(HotHiddenDangerInspectionBo bo) {
        if (StringUtils.isNotBlank(bo.getAuditResult())) {
            return bo.getAuditResult().trim().toUpperCase();
        }
        if (bo.getAuditHasDanger() != null && bo.getAuditHasDanger() == 0L) {
            return "PASS";
        }
        return "REJECT";
    }

    private void saveRejectHistory(HotHiddenDangerInspection original, HotHiddenDangerInspectionBo bo, Long auditRound, Date auditDate) {
        HotHiddenDangerInspectionAuditHistory history = new HotHiddenDangerInspectionAuditHistory();
        history.setInspectionId(original.getId());
        history.setCompanyId(original.getCompanyId());
        history.setPlanId(original.getPlanId());
        history.setProjectName(original.getProjectName());
        history.setProjectId(original.getProjectId());
        history.setProjectType(original.getProjectType());
        history.setSubmitVersion(original.getSubmitVersion() == null ? 1L : original.getSubmitVersion());
        history.setAuditRound(auditRound);
        history.setAuditResult("REJECT");
        history.setRejectReason(bo.getAuditConclusion());
        history.setAuditDate(auditDate);
        history.setApproverId(bo.getApproverId());
        history.setApproverName(bo.getApproverName());
        history.setApproverSignImgUrl(bo.getApproverSignImgUrl());
        history.setAuditHasDanger(bo.getAuditHasDanger());
        history.setSubmitSnapshotJson(buildSubmitSnapshotJson(original));
        history.setCheckContentJson(original.getCheckContentJson());
        history.setDangerDesc(original.getDangerDesc());
        history.setAttachmentUrl(original.getAttachmentUrl());
        history.setSignImgUrl(original.getSignImgUrl());
        history.setCheckerId(original.getCheckerId());
        history.setCheckerName(original.getCheckerName());
        history.setCheckDate(original.getCheckDate());
        historyMapper.insert(history);
    }

    private String buildSubmitSnapshotJson(HotHiddenDangerInspection original) {
        Map<String, Object> snapshot = new LinkedHashMap<>();
        snapshot.put("inspectionId", original.getId());
        snapshot.put("companyId", original.getCompanyId());
        snapshot.put("planId", original.getPlanId());
        snapshot.put("projectName", original.getProjectName());
        snapshot.put("projectId", original.getProjectId());
        snapshot.put("projectType", original.getProjectType());
        snapshot.put("submitVersion", original.getSubmitVersion());
        snapshot.put("checkContentJson", original.getCheckContentJson());
        snapshot.put("dangerDesc", original.getDangerDesc());
        snapshot.put("attachmentUrl", original.getAttachmentUrl());
        snapshot.put("signImgUrl", original.getSignImgUrl());
        snapshot.put("checkerId", original.getCheckerId());
        snapshot.put("checkerName", original.getCheckerName());
        snapshot.put("checkDate", original.getCheckDate());
        return JSONUtil.toJsonStr(snapshot);
    }

    private List<HotHiddenDangerInspectionAuditHistoryVo> queryRejectHistoryList(Long inspectionId) {
        return historyMapper.selectVoList(
            Wrappers.<HotHiddenDangerInspectionAuditHistory>lambdaQuery()
                .eq(HotHiddenDangerInspectionAuditHistory::getInspectionId, inspectionId)
                .eq(HotHiddenDangerInspectionAuditHistory::getIsDeleted, 0L)
                .orderByDesc(HotHiddenDangerInspectionAuditHistory::getAuditRound)
                .orderByDesc(HotHiddenDangerInspectionAuditHistory::getCreateTime)
        );
    }

    private void fillTaskId(HotHiddenDangerInspectionVo vo, String userId) {
        if (vo == null || StringUtils.isBlank(userId)) {
            return;
        }
        String taskId = null;
        if (StringUtils.isNotBlank(vo.getInstanceId())) {
            taskId = flowService.getTaskId(vo.getInstanceId(), userId);
        }
        if (StringUtils.isBlank(taskId) && vo.getId() != null) {
            taskId = flowService.getTaskIdByBusinessId("HIDDEN_DANGER_CHECK", String.valueOf(vo.getId()), userId);
        }
        if (StringUtils.isBlank(taskId) && vo.getId() != null) {
            taskId = flowService.getCurrentTaskIdByBusinessId("HIDDEN_DANGER_CHECK", String.valueOf(vo.getId()));
        }
        vo.setTaskId(taskId);
    }

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

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