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

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.utils.TimeRangeUtil;
import com.hotwj.platform.config.companyBasicConfig.domain.bo.HotCompanyBasicConfigBo;
import com.hotwj.platform.config.companyBasicConfig.domain.vo.HotCompanyBasicConfigVo;
import com.hotwj.platform.config.companyBasicConfig.service.IHotCompanyBasicConfigService;
import com.hotwj.platform.config.hiddenDangerCheckConfig.domain.bo.HotHiddenDangerCheckConfigBo;
import com.hotwj.platform.config.hiddenDangerCheckConfig.domain.vo.HotHiddenDangerCheckConfigVo;
import com.hotwj.platform.config.hiddenDangerCheckConfig.service.IHotHiddenDangerCheckConfigService;
import com.hotwj.platform.driverManagement.driver.domain.bo.HotDriverBo;
import com.hotwj.platform.driverManagement.driver.domain.vo.HotDriverVo;
import com.hotwj.platform.driverManagement.driver.service.IHotDriverService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.bo.HotVehicleBo;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.vo.HotVehicleVo;
import com.hotwj.platform.resourceManagement.vehicleManagement.service.IHotVehicleService;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.HotHiddenDangerInspection;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.bo.HotHiddenDangerInspectionBo;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.mapper.HotHiddenDangerInspectionMapper;
import com.hotwj.platform.securityManagement.hiddenDangerInspection.service.IHotHiddenDangerInspectionService;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.domain.HotHiddenDangerPlan;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.domain.bo.HotHiddenDangerPlanBo;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.domain.vo.HotHiddenDangerPlanVo;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.mapper.HotHiddenDangerPlanMapper;
import com.hotwj.platform.securityManagement.hiddenDangerPlan.service.IHotHiddenDangerPlanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.IsoFields;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 隐患排查Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-30
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotHiddenDangerPlanServiceImpl implements IHotHiddenDangerPlanService {

    private final IHotHiddenDangerCheckConfigService checkConfigService;
    private final IHotCompanyBasicConfigService companyBasicConfigService;
    private final IHotVehicleService vehicleService;
    private final IHotDriverService driverService;
    private final IHotHiddenDangerInspectionService inspectionService;
    private final HotHiddenDangerInspectionMapper inspectionMapper;
    private final ISysCompanyService companyService;
    private final HotHiddenDangerPlanMapper baseMapper;
    private final HotCompanySafetyManagerMapper managerMapper;
    private final IHotSystemNotificationService notificationService;

    /**
     * 查询隐患排查
     *
     * @param id 主键
     * @return 隐患排查
     */
    @Override
    public HotHiddenDangerPlanVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

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

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

    /**
     * 生成隐患排查计划
     */
    @Override
    public void generatePlans() {
        // 1. 获取所有开启了隐患排查规则的公司配置
        HotCompanyBasicConfigBo companyConfigBo = new HotCompanyBasicConfigBo();
        companyConfigBo.setIsDeleted(0L);
        companyConfigBo.setRoleIsEnable(1L);
        List<HotCompanyBasicConfigVo> companyConfigs = companyBasicConfigService.queryList(companyConfigBo);

        if (companyConfigs == null || companyConfigs.isEmpty()) {
            return;
        }

        // 2. 获取所有启用的检查项配置，并按公司ID分组
        HotHiddenDangerCheckConfigBo configBo = new HotHiddenDangerCheckConfigBo();
        configBo.setIsDeleted(0L);
        List<HotHiddenDangerCheckConfigVo> allCheckConfigs = checkConfigService.queryList(configBo);

        Map<Long, List<HotHiddenDangerCheckConfigVo>> checkConfigsMap;
        if (allCheckConfigs != null && !allCheckConfigs.isEmpty()) {
            checkConfigsMap = allCheckConfigs.stream()
                    .filter(c -> c.getCompanyId() != null)
                    .collect(java.util.stream.Collectors.groupingBy(HotHiddenDangerCheckConfigVo::getCompanyId));
        } else {
            checkConfigsMap = new java.util.HashMap<>();
        }

        for (HotCompanyBasicConfigVo companyConfig : companyConfigs) {
            try {
                processCompanyPlan(companyConfig, checkConfigsMap);
            } catch (Exception e) {
                log.error("创建公司： {} 隐患排查计划失败", companyConfig.getCompanyId(), e);
            }
        }
    }

    /**
     * 生成指定企业的隐患排查计划
     *
     * @param companyId 企业ID
     */
    @Override
    public void generatePlan(Long companyId) {
        if (companyId == null) {
            throw new IllegalArgumentException("公司ID不能为空");
        }

        // 1. 获取企业配置
        HotCompanyBasicConfigBo companyConfigBo = new HotCompanyBasicConfigBo();
        companyConfigBo.setCompanyId(companyId);
        companyConfigBo.setIsDeleted(0L);
        companyConfigBo.setRoleIsEnable(1L);
        List<HotCompanyBasicConfigVo> companyConfigs = companyBasicConfigService.queryList(companyConfigBo);

        if (companyConfigs == null || companyConfigs.isEmpty()) {
            log.info("公司： {} 基本配置未找到或隐患排查角色已禁用，跳过计划生成", companyId);
            return;
        }
        HotCompanyBasicConfigVo companyConfig = companyConfigs.get(0);

        // 2. 获取检查项配置
        HotHiddenDangerCheckConfigBo configBo = new HotHiddenDangerCheckConfigBo();
        configBo.setCompanyId(companyId);
        configBo.setIsDeleted(0L);
        List<HotHiddenDangerCheckConfigVo> checkConfigs = checkConfigService.queryList(configBo);

        Map<Long, List<HotHiddenDangerCheckConfigVo>> checkConfigsMap = new java.util.HashMap<>();
        if (checkConfigs != null && !checkConfigs.isEmpty()) {
            checkConfigsMap.put(companyId, checkConfigs);
        }

        // 3. 处理
        processCompanyPlan(companyConfig, checkConfigsMap);
    }

    /**
     * 处理单个公司的排查计划
     */
    private void processCompanyPlan(HotCompanyBasicConfigVo companyConfig, Map<Long, List<HotHiddenDangerCheckConfigVo>> checkConfigsMap) {
        if (companyConfig == null || companyConfig.getCompanyId() == null) {
            return;
        }

        Long role = companyConfig.getHiddenDangerRole();
        boolean enable = Long.valueOf(1L).equals(companyConfig.getRoleIsEnable());
        if (role == null || !enable) {
            SysCompanyVo sysCompanyVo = companyService.queryById(companyConfig.getCompanyId());
            if (sysCompanyVo != null) {
                log.info("公司： {} 隐患排查角色未启用，跳过计划生成", sysCompanyVo.getCompanyName());
            } else {
                log.info("公司： {} 隐患排查角色未启用，跳过计划生成", companyConfig.getCompanyId());
            }
            return;
        }

        // 计算时间范围和计划名称
        PlanTimeInfo timeInfo = calculatePlanTimeInfo(role);
        if (timeInfo == null) {
            return;
        }


        // 获取有效的检查项配置
        HotHiddenDangerCheckConfigVo checkConfig = getEffectiveCheckConfig(companyConfig.getCompanyId(), checkConfigsMap);

        if (checkConfig == null) {
            return;
        }

        HotHiddenDangerPlan plan = findPlan(companyConfig.getCompanyId(), timeInfo);
        boolean isNewPlan = false;
        if (plan == null) {
            Long inspectId = checkConfig == null ? null : checkConfig.getId();
            String inspectName = checkConfig == null ? null : checkConfig.getTypeName();
            HotHiddenDangerPlanBo newPlan = createPlan(companyConfig.getCompanyId(), inspectId, inspectName, timeInfo);
            if (newPlan == null || newPlan.getId() == null) {
                log.error("创建公司： {} 隐患排查计划失败", companyConfig.getCompanyId());
                return;
            }
            plan = baseMapper.selectById(newPlan.getId());
            isNewPlan = true;
        } else if (checkConfig != null && plan.getInspectId() == null) {
            baseMapper.update(
                    null,
                    Wrappers.<HotHiddenDangerPlan>lambdaUpdate()
                            .set(HotHiddenDangerPlan::getInspectId, checkConfig.getId())
                            .set(HotHiddenDangerPlan::getInspectName, checkConfig.getTypeName())
                            .eq(HotHiddenDangerPlan::getId, plan.getId())
            );
        }


        String companyName = "企业";
        try {
            SysCompanyVo company = companyService.queryById(companyConfig.getCompanyId());
            if (company != null && StringUtils.isNotBlank(company.getCompanyName())) {
                companyName = company.getCompanyName();
            }
        } catch (Exception e) {
            log.warn("查询公司： {} 名称失败，异常信息： {}", companyConfig.getCompanyId(), e.getMessage());
        }

        if (isNewPlan) {
            String periodText = switch (companyConfig.getHiddenDangerRole() != null ? companyConfig.getHiddenDangerRole().intValue() : -1) {
                case 1 -> "本周";
                case 2 -> "本月";
                case 3 -> "本季";
                case 4 -> "本半年";
                case 5 -> "本年";
                default -> "本期";
            };
            List<HotCompanySafetyManager> managers = managerMapper.selectList(
                    Wrappers.<HotCompanySafetyManager>lambdaQuery()
                            .eq(HotCompanySafetyManager::getCompanyId, companyConfig.getCompanyId())
                            .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                            .eq(HotCompanySafetyManager::getIsResigned, 0L)
                            .eq(HotCompanySafetyManager::getStatus, 1L)
            );
            if (managers != null && !managers.isEmpty()) {
                List<String> receiverIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                String content = periodText + "隐患排查计划已创建，请及时进行排查。";
                HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                bos.setLevel("普通");
                bos.setContent(content);
                bos.setSourceType("隐患管理");
                bos.setSenderType("SYSTEM");
                bos.setReceiverType("管理员");
                bos.setReceiverIds(receiverIds);
                bos.setIsDeleted(0L);
                try {
                    notificationService.insertByBo(bos);
                } catch (Exception e) {
                    log.warn("创建公司： {} 隐患排查计划通知失败，周期： {}", companyConfig.getCompanyId(), periodText, e);
                }
            }
        }

        syncInspectionDetails(plan.getId(), companyConfig.getCompanyId(), checkConfig, companyName);
    }

    /**
     * 根据公司ID和计划时间信息查询隐患排查计划
     */
    private HotHiddenDangerPlan findPlan(Long companyId, PlanTimeInfo timeInfo) {
        if (companyId == null || timeInfo == null) {
            return null;
        }
        LambdaQueryWrapper<HotHiddenDangerPlan> lqw = Wrappers.lambdaQuery();
        lqw.eq(HotHiddenDangerPlan::getCompanyId, companyId);
        lqw.eq(HotHiddenDangerPlan::getIsDeleted, 0L);
        lqw.eq(HotHiddenDangerPlan::getPlanDateKey, timeInfo.getPlanDateKey());
        lqw.orderByDesc(HotHiddenDangerPlan::getCreateTime);
        lqw.last("LIMIT 1");
        return baseMapper.selectOne(lqw);
    }

    /**
     * 计算计划的时间范围和名称
     */
    private PlanTimeInfo calculatePlanTimeInfo(Long role) {
        TimeRangeUtil.TimeRange timeRange;
        String planName;
        String planDateKey;
        LocalDate now = LocalDate.now();

        // 1=周 2=月 3=季度 4=半年 5=年
        if (role == 1) {
            timeRange = TimeRangeUtil.getCurrentWeek();
            planName = TimeRangeUtil.formatDate(timeRange.getStartTime(), "yyyy年MM月dd日") +
                    " 至 " +
                    TimeRangeUtil.formatDate(timeRange.getEndTime(), "yyyy年MM月dd日") +
                    " 排查计划";
            int week = now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
            int year = now.get(IsoFields.WEEK_BASED_YEAR);
            planDateKey = String.format("%d-W%02d", year, week);
        } else if (role == 2) {
            timeRange = TimeRangeUtil.getCurrentMonth();
            planName = TimeRangeUtil.formatDate(timeRange.getStartTime(), "yyyy年MM月") + " 排查计划";
            planDateKey = now.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        } else if (role == 3) {
            timeRange = TimeRangeUtil.getCurrentQuarter();
            int season = TimeRangeUtil.getCurrentQuarterNumber();
            planName = TimeRangeUtil.formatDate(timeRange.getStartTime(), "yyyy年") + season + " 季度排查计划";
            planDateKey = String.format("%d-Q%d", now.getYear(), season);
        } else if (role == 4) {
            timeRange = TimeRangeUtil.getCurrentHalfYear();
            String halfYearDesc = TimeRangeUtil.getCurrentHalfYearDescription();
            planName = TimeRangeUtil.formatDate(timeRange.getStartTime(), "yyyy年") + " " + halfYearDesc + "排查计划";
            int half = now.getMonthValue() <= 6 ? 1 : 2;
            planDateKey = String.format("%d-H%d", now.getYear(), half);
        } else if (role == 5) {
            timeRange = TimeRangeUtil.getCurrentYear();
            planName = TimeRangeUtil.formatDate(timeRange.getStartTime(), "yyyy年") + " 排查计划";
            planDateKey = String.valueOf(now.getYear());
        } else {
            return null;
        }
        return new PlanTimeInfo(timeRange, planName, planDateKey);
    }

    /**
     * 获取有效的检查项配置
     */
    private HotHiddenDangerCheckConfigVo getEffectiveCheckConfig(Long companyId, Map<Long, List<HotHiddenDangerCheckConfigVo>> checkConfigsMap) {
        List<HotHiddenDangerCheckConfigVo> companyCheckConfigs = checkConfigsMap.get(companyId);
        if (companyCheckConfigs != null && !companyCheckConfigs.isEmpty()) {
            return companyCheckConfigs.stream()
                    .filter(c -> c.getIsDefault() != null && c.getIsDefault() == 1L)
                    .findFirst()
                    .orElse(companyCheckConfigs.get(0));
        }
        return null;
    }

    /**
     * 创建计划实体
     */
    private HotHiddenDangerPlanBo createPlan(Long companyId, Long inspectId, String inspectName, PlanTimeInfo timeInfo) {
        HotHiddenDangerPlanBo newPlan = new HotHiddenDangerPlanBo();
        newPlan.setCompanyId(companyId);
        newPlan.setInspectId(inspectId);
        newPlan.setInspectName(inspectName);
        newPlan.setPlanName(timeInfo.getPlanName());
        newPlan.setStartDate(timeInfo.getTimeRange().getStartTime());
        newPlan.setEndDate(timeInfo.getTimeRange().getEndTime());
        newPlan.setProgress(0L); // 0=待处理
        newPlan.setIsAutoGeneratedByBackend(1L);
        newPlan.setPlanDateKey(timeInfo.getPlanDateKey());
        newPlan.setRemark(inspectId == null ? "自动生成(待配置)" : "自动生成");

        this.insertByBo(newPlan);
        return newPlan;
    }

    /**
     * 同步计划详情
     */
    private void syncInspectionDetails(Long planId, Long companyId, HotHiddenDangerCheckConfigVo checkConfig, String companyName) {
        if (planId == null || companyId == null || checkConfig == null) {
            return;
        }

        List<HotHiddenDangerInspection> existing = inspectionMapper.selectList(
                Wrappers.<HotHiddenDangerInspection>lambdaQuery()
                        .eq(HotHiddenDangerInspection::getCompanyId, companyId)
                        .eq(HotHiddenDangerInspection::getPlanId, planId)
                        .eq(HotHiddenDangerInspection::getIsDeleted, 0L)
        );

        // 4. 缓存已存在的检查项
        Map<String, HotHiddenDangerInspection> existsMap = new HashMap<>();
        if (existing != null) {
            for (HotHiddenDangerInspection ins : existing) {
                if (ins == null || ins.getProjectType() == null) {
                    continue;
                }
                String projectId = StringUtils.isBlank(ins.getProjectId()) ? "0" : ins.getProjectId();
                existsMap.put(ins.getProjectType() + ":" + projectId, ins);
            }
        }

        String companyJson = checkConfig.getCompanyInspectJson();
        if (StringUtils.isNotBlank(companyJson)) {
            // key 规则：projectType:projectId
            // 其中 projectType: 1=公司 2=车辆 3=人员；公司项目没有具体 projectId，统一用 "0" 占位
            String key = "1:0";
            HotHiddenDangerInspection ins = existsMap.get(key);
            // 企业检查对象不存在则创建
            if (ins == null) {
                HotHiddenDangerInspectionBo inspectionBo = new HotHiddenDangerInspectionBo();
                inspectionBo.setCompanyId(companyId);
                inspectionBo.setPlanId(planId);
                inspectionBo.setProjectName(companyName);
                inspectionBo.setProjectType(1L);
                inspectionBo.setProjectId("0");
                inspectionBo.setCheckContentJson(companyJson);
                inspectionService.insertByBo(inspectionBo);
            } else {
                tryUpdateCheckContentJson(ins, companyJson);
            }
        }

        String vehicleJson = checkConfig.getVehicleInspectJson();
        if (StringUtils.isNotBlank(vehicleJson)) {
            HotVehicleBo vehicleBo = new HotVehicleBo();
            vehicleBo.setCompanyId(companyId);
            vehicleBo.setVehicleStatus(1L);
            vehicleBo.setOperationStatus(1L);
            List<HotVehicleVo> vehicles = vehicleService.queryList(vehicleBo);
            if (vehicles != null) {
                for (HotVehicleVo vehicle : vehicles) {
                    if (vehicle == null || vehicle.getId() == null) {
                        continue;
                    }
                    String key = "2:" + vehicle.getId();
                    HotHiddenDangerInspection ins = existsMap.get(key);
                    if (ins == null) {
                        HotHiddenDangerInspectionBo inspectionBo = new HotHiddenDangerInspectionBo();
                        inspectionBo.setCompanyId(companyId);
                        inspectionBo.setPlanId(planId);
                        inspectionBo.setProjectType(2L);
                        inspectionBo.setProjectName(vehicle.getPlateNumber() + " 隐患排查");
                        inspectionBo.setProjectId(String.valueOf(vehicle.getId()));
                        inspectionBo.setCheckContentJson(vehicleJson);
                        inspectionService.insertByBo(inspectionBo);
                    } else {
                        tryUpdateCheckContentJson(ins, vehicleJson);
                    }
                }
            }
        }

        String personJson = checkConfig.getPersonInspectJson();
        if (StringUtils.isNotBlank(personJson)) {
            HotDriverBo driverBo = new HotDriverBo();
            driverBo.setCompanyId(companyId);
            driverBo.setStatus(1L);
            driverBo.setAuditStatus(1);
            driverBo.setIsDeleted(0L);
            List<HotDriverVo> drivers = driverService.queryList(driverBo);
            if (drivers != null) {
                for (HotDriverVo driver : drivers) {
                    if (driver == null || StringUtils.isBlank(driver.getId())) {
                        continue;
                    }
                    String key = "3:" + driver.getId();
                    HotHiddenDangerInspection ins = existsMap.get(key);
                    if (ins == null) {
                        HotHiddenDangerInspectionBo inspectionBo = new HotHiddenDangerInspectionBo();
                        inspectionBo.setCompanyId(companyId);
                        inspectionBo.setPlanId(planId);
                        inspectionBo.setProjectType(3L);
                        inspectionBo.setProjectName(driver.getName() + " 隐患排查");
                        inspectionBo.setProjectId(driver.getId());
                        inspectionBo.setCheckContentJson(personJson);
                        inspectionService.insertByBo(inspectionBo);
                    } else {
                        tryUpdateCheckContentJson(ins, personJson);
                    }
                }
            }
        }
    }

    private void tryUpdateCheckContentJson(HotHiddenDangerInspection ins, String json) {
        if (ins == null || ins.getId() == null || StringUtils.isBlank(json)) {
            return;
        }
        if (StringUtils.isNotBlank(ins.getInstanceId()) || ins.getStatus() != null) {
            return;
        }
        if (json.equals(ins.getCheckContentJson())) {
            return;
        }
        inspectionMapper.update(
                null,
                Wrappers.<HotHiddenDangerInspection>lambdaUpdate()
                        .set(HotHiddenDangerInspection::getCheckContentJson, json)
                        .eq(HotHiddenDangerInspection::getId, ins.getId())
        );
    }

    private LambdaQueryWrapper<HotHiddenDangerPlan> buildQueryWrapper(HotHiddenDangerPlanBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotHiddenDangerPlan> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotHiddenDangerPlan::getCreateTime);
        lqw.eq(bo.getCompanyId() != null, HotHiddenDangerPlan::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getInspectId() != null, HotHiddenDangerPlan::getInspectId, bo.getInspectId());
        lqw.like(StringUtils.isNotBlank(bo.getPlanName()), HotHiddenDangerPlan::getPlanName, bo.getPlanName());
        lqw.eq(bo.getStartDate() != null, HotHiddenDangerPlan::getStartDate, bo.getStartDate());
        lqw.eq(bo.getEndDate() != null, HotHiddenDangerPlan::getEndDate, bo.getEndDate());
        lqw.eq(bo.getProgress() != null, HotHiddenDangerPlan::getProgress, bo.getProgress());
        lqw.eq(bo.getIsDeleted() != null, HotHiddenDangerPlan::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增隐患排查
     *
     * @param bo 隐患排查
     * @return 是否新增成功
     */
    @Override
    public Long insertByBo(HotHiddenDangerPlanBo bo) {
        HotHiddenDangerPlan add = MapstructUtils.convert(bo, HotHiddenDangerPlan.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if (add.getCompanyId() != null) {
                List<HotCompanySafetyManager> managers = managerMapper.selectList(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, add.getCompanyId())
                                .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                                .eq(HotCompanySafetyManager::getIsResigned, 0L)
                                .eq(HotCompanySafetyManager::getStatus, 1L)
                );
                if (managers != null && !managers.isEmpty()) {
                    List<String> receiverIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                    String planName = StringUtils.blankToDefault(add.getPlanName(), "隐患排查");
                    String content = planName + " 已创建，请及时进行排查。";
                    HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                    bos.setLevel("普通");
                    bos.setContent(content);
                    bos.setSourceType("隐患管理");
                    bos.setSenderType("SYSTEM");
                    bos.setReceiverType("管理员");
                    bos.setReceiverIds(receiverIds);
                    bos.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bos);
                    } catch (Exception e) {
                        log.warn("创建公司： {} 隐患排查计划通知失败，计划ID： {}", add.getCompanyId(), add.getId(), e);
                    }
                }
            }
        }
        return bo.getId();
    }

    /**
     * 修改隐患排查
     *
     * @param bo 隐患排查
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotHiddenDangerPlanBo bo) {
        HotHiddenDangerPlan before = null;
        if (bo.getId() != null) {
            before = baseMapper.selectById(bo.getId());
        }
        HotHiddenDangerPlan update = MapstructUtils.convert(bo, HotHiddenDangerPlan.class);
        validEntityBeforeSave(update);
        boolean ok = baseMapper.updateById(update) > 0;
        if (ok) {
            Long companyId = update.getCompanyId() != null ? update.getCompanyId() : (before != null ? before.getCompanyId() : null);
            if (companyId != null) {
                List<HotCompanySafetyManager> managers = managerMapper.selectList(
                        Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, companyId)
                                .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                                .eq(HotCompanySafetyManager::getIsResigned, 0L)
                                .eq(HotCompanySafetyManager::getStatus, 1L)
                );
                if (managers != null && !managers.isEmpty()) {
                    List<String> receiverIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                    String planName = StringUtils.blankToDefault(
                            update.getPlanName() != null ? update.getPlanName() : (before != null ? before.getPlanName() : null),
                            "隐患排查"
                    );
                    String content = planName + " 已更新，请及时进行排查。";
                    HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                    bos.setLevel("普通");
                    bos.setContent(content);
                    bos.setSourceType("隐患管理");
                    bos.setSenderType("SYSTEM");
                    bos.setReceiverType("管理员");
                    bos.setReceiverIds(receiverIds);
                    bos.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bos);
                    } catch (Exception e) {
                        log.warn("更新公司： {} 隐患排查计划通知失败，计划ID： {}", companyId, update.getId(), e);
                    }
                }
            }
        }
        return ok;
    }

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

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

    /**
     * 计划时间信息内部类
     */
    private static class PlanTimeInfo {
        private final TimeRangeUtil.TimeRange timeRange;
        private final String planName;
        private final String planDateKey;

        public PlanTimeInfo(TimeRangeUtil.TimeRange timeRange, String planName, String planDateKey) {
            this.timeRange = timeRange;
            this.planName = planName;
            this.planDateKey = planDateKey;
        }

        public TimeRangeUtil.TimeRange getTimeRange() {
            return timeRange;
        }

        public String getPlanName() {
            return planName;
        }

        public String getPlanDateKey() {
            return planDateKey;
        }
    }
}
