package com.scpyun.platform.jilinsscgsdp.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.scpyun.base.bean.Page;
import com.scpyun.base.bean.User;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.utils.*;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.base.utils.DateUtils;
import com.scpyun.platform.jilinsscgsdp.bean.bo.EventWarningSettingBo;
import com.scpyun.platform.jilinsscgsdp.bean.dto.RiskComparisonDTO;
import com.scpyun.platform.jilinsscgsdp.bean.entity.*;
import com.scpyun.platform.jilinsscgsdp.bean.vo.*;
import com.scpyun.platform.jilinsscgsdp.check.EventCheckUtils;
import com.scpyun.platform.jilinsscgsdp.check.EventFlowLogCheckUtils;
import com.scpyun.platform.jilinsscgsdp.check.EventUserCheckUtils;
import com.scpyun.platform.jilinsscgsdp.constant.NotesConstant;
import com.scpyun.platform.jilinsscgsdp.constant.NumberConstant;
import com.scpyun.platform.jilinsscgsdp.enums.HierarchyTypeEnums;
import com.scpyun.platform.jilinsscgsdp.enums.WarningLevelEnum;
import jodd.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.scpyun.platform.jilinsscgsdp.bean.dto.RiskComparisonDTO.findHighestRisk;


@Api("事件上报")
@Service("eventService")
@Validated
public class EventServiceImpl {

    @Autowired
    CommonService commonService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    private final String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.event.";
    private final String nameSpaceSafeSound = "com.scpyun.platform.standard.jilinsscgsdp.safeSoundDao.";
    private final String nameSpaceUser = "com.scpyun.platform.standard.jilinsscgsdp.eventuser.";
    private final String nameSpaceSys = "com.scpyun.platform.standard.jilinsscgsdp.sys.";
    private final String nameSpaceFlow = "com.scpyun.platform.standard.jilinsscgsdp.eventflow.";
    private final String nameSpaceWaiting = "com.scpyun.platform.standard.jilinsscgsdp.eventwaiting.";
    private final String nameSpaceAttach = "com.scpyun.platform.standard.jilinsscgsdp.attach.";
    private final String nameSpaceOpinion = "com.scpyun.platform.standard.jilinsscgsdp.opinion.";
    private final String nameSpaceEventRiskFactor = "com.scpyun.platform.standard.jilinsscgsdp.eventriskfactor.";
    private final String supplementEventNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.eventSupplement.";
    private String murderManagementNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.murderManagement.";
    private String dictNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.SysDict.";
    private static final Logger log = LoggerFactory.getLogger(EventServiceImpl.class);


    @ApiOperation(value = "", desc = "")
    public Page<Map<String, String>> findEventTriggerList(Page<Map<String, String>> page) throws InterruptedException {
        Page<Map<String, String>> restPage = commonService.findPage(nameSpaceWaiting + "findEventTriggerList", page);
        if (CollectionUtils.isNotEmpty(restPage.getResults())) {
            restPage.getResults().forEach(v -> {
                v.put("cityName", commonService.getObject(nameSpaceSys + "getName", v.get("cityId")));
                v.put("areaName", commonService.getObject(nameSpaceSys + "getName", v.get("areaId")));
            });
        }
        return restPage;
    }

    @ApiOperation(value = "群体性事件预警历史", desc = "群体性事件预警历史")
    public Page<Map<String, String>> findEventTriggerHistoryPageList(Page<Map<String, String>> page) throws InterruptedException {
        Page<Map<String, String>> restPage = commonService.findPage(nameSpaceWaiting + "findEventTriggerHistoryPageList", page);
        if (CollectionUtils.isNotEmpty(restPage.getResults())) {
            restPage.getResults().forEach(v -> {
                v.put("cityName", commonService.getObject(nameSpaceSys + "getName", v.get("cityId")));
                v.put("areaName", commonService.getObject(nameSpaceSys + "getName", v.get("areaId")));
            });
        }
        return restPage;
    }

    @ApiOperation(value = "重点事件数量统计", desc = "")
    public Map<String, Object> countEventTrigger(EventTrigger eventTrigger) throws InterruptedException {
        return commonService.getObject(nameSpaceWaiting + "countEventTrigger", eventTrigger);
    }

    private void vaid(String cityId, String areaId, String streetId, String communityId) {
        if (StringUtils.isEmpty(cityId) || "".equals(cityId)) {
            throw new CustomException("城市不能为空");
        }
        if (StringUtils.isEmpty(areaId) || "".equals(areaId)) {
            throw new CustomException("区不能为空");
        }
        if (StringUtils.isEmpty(streetId) || "".equals(streetId)) {
            throw new CustomException("街道不能为空");
        }
        if (StringUtils.isEmpty(communityId) || "".equals(communityId)) {
            throw new CustomException("社区不能为空");
        }
    }

    @ApiOperation(value = "新增事件上报", desc = "新增事件上报")
    public String insertEvent(@Valid ReqEventInsertVo vo) throws InterruptedException {
        vaid(vo.getCityId(), vo.getAreaId(), vo.getStreetId(), vo.getCommunityId());
        String eventId = IdUtil.randomUUID();
        vo.setId(eventId);
        EventWarningSettingBo ewb = commonService.getObject(nameSpaceWaiting + "getWarnDealTime", vo);
        vo.setEarlyWarningTime(ewb.getEarlyWarningTime());
        vo.setAlarmTime(ewb.getAlarmTime());
        vo.setEventCode(this.eventCode(vo));
        vo.setStatus(NumberConstant.TWO_STRING);
        vo.setIsSpecialTasks(NumberConstant.TWO_STRING);
        vo.setReportingName(vo.get_user().getName());
        vo.setReportingUnit(vo.get_user().getCompany_name());
        // 查询
        vo.setReportingUnitCode(vo.get_user().getCompany_id());
        //添加事件
        if (commonService.insert(nameSpace + "insertEvent", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.INSERT_EXCEPTION);
        }
//        log.info("插入事件完成");
        // 保存纠纷类型（其他）
        if (StringUtils.isNotEmpty(vo.getEvent_category_other_name()) || StringUtils.isNotEmpty(vo.getEvent_category_mini_other_name())) {
            commonService.insert(nameSpace + "insertEventCategoryOther", vo);
        }
        //添加图片
//        log.info("图片集合" + JSONUtil.toJsonStr(vo.getUrlList()));
        List<ReqEventAttachInsertVo> urlList = vo.getUrlList();
        if (!CollectionUtils.isEmpty(urlList)) {
            for (ReqEventAttachInsertVo sub : urlList) {
//                log.info("图片对象" + JSONUtil.toJsonStr(vo.getUrlList()));
                sub.setId(vo.getId());
                if (commonService.insert(nameSpaceAttach + "insertEventAttach", sub) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.INSERT_EXCEPTION);
                }
            }
        }
        List<ReqEventUserInsertVo> userList = vo.getUserList();
        for (ReqEventUserInsertVo user : userList) {
            if (user.getEventUserType().equals(NumberConstant.FOUR_STRING)) {
                if (StringUtils.isNotEmpty(user.getEventCardno())) {
                    if (!IdcardUtil.isValidCard(user.getEventCardno())) {
                        throw new CustomException("证件号码错误！");
                    }
                }
            }

            user.setEventId(vo.getId());
            user.set_user(vo.get_user());
            //添加当事人
            if (commonService.insert(nameSpaceUser + "insertEventUserKey", user) != NumberConstant.ONE_INT) {
                throw new CustomException(user.getEventUserName() + NotesConstant.INSERT_EXCEPTION);
            }
            // 重点人判断
            recordTriggerEvent(user);
        }


        User user = vo.get_user();
        String jobDuty = commonService.getObject(nameSpaceSys + "getJobDuty", vo);
        if (vo.getLogType().equals(NumberConstant.ONE_STRING)) { //上报
            if (NumberConstant.ONE_STRING.equals(jobDuty)) {//网格员
                vo.setHierarchy(NumberConstant.ONE_INT);
                vo.setGradeUserId(user.getId());
                vo.setGradeD(NumberConstant.ZERO_STRING);
                vo.setEventFlowSettingType(NumberConstant.ONE_STRING);
                this.insertLogTypeOne(vo);
            } else {//非网格员
                vo.setHierarchy(HierarchyTypeEnums.hierarchyEnumGrad.getHierarchyGrade(user.getCompany_grade()));
                vo.setGradeUserId(NumberConstant.ONE_STRING);
                vo.setGradeD(NumberConstant.ONE_STRING);
                vo.setEventFlowSettingType(NumberConstant.ONE_STRING);
                this.insertLogTypeOne(vo);
            }
        } else if (vo.getLogType().equals(NumberConstant.SIX_STRING)) {//下派
            vo.setHierarchy(HierarchyTypeEnums.hierarchyEnumGrad.getHierarchyGrade(user.getCompany_grade()));
            vo.setGradeUserId(NumberConstant.ONE_STRING);
            vo.setGradeD(NumberConstant.ONE_STRING);
            vo.setEventFlowSettingType(NumberConstant.TWO_STRING);
            this.insertLogTypeOne(vo);
        } else { //横传
            vo.setHierarchy(HierarchyTypeEnums.hierarchyEnumGrad.getHierarchyGrade(user.getCompany_grade()));
            vo.setEventFlowSettingType(NumberConstant.ONE_STRING);
            this.insertLogTypeCross(vo);
        }
        Date occurrenceTime = DateUtils.parseDate(vo.getOccurrenceTime());
        Date createTime = new Date();
        if (com.scpyun.platform.jilinsscgsdp.utils.DateUtil.compareMonthsAcrossYears(occurrenceTime, createTime) != 0) {//计算补入
            SupplementEvent supplementEvent = new SupplementEvent();
            supplementEvent.setEventId(eventId);
            supplementEvent.setCreateTime(createTime);
            supplementEvent.setIsAreasOcus(0);
            supplementEvent.setAreaId(vo.getAreaId());
            supplementEvent.setCityId(vo.getCityId());
            supplementEvent.setOccurrenceTime(DateUtils.convertDate2String("yyyy-MM", occurrenceTime));
            supplementEvent.setEventCategoryId(vo.getEventCategoryId());
            commonService.insert(supplementEventNameSpace + "insertEventSupplementInfo", supplementEvent);
        }

        // 重点事异步处理
        // 矛盾纠纷事件发生地点相同（社区）且属于易引发群体性事件的矛盾纠纷类型、发生时间跨度在30日以内，且矛盾纠纷大类相同、矛盾纠纷小类相同并达到5次以上
        threadPoolExecutor.execute(() -> {
            try {
                Thread.sleep(10000L);
                DataSourceSwitcher.setMaster();
                DataSourceSwitcher.setSharding("all");
                recordEventTrigger(vo);
            } catch (Exception e) {
                log.error("重点事件异步执行发生异常 eventId:{}，异常信息：", vo.getEventId(), e);
            }
        });
        return NotesConstant.SAVE_SUCCESS;
    }

    public void recordTriggerEvent( ReqEventUserInsertVo user) {
        if (StringUtils.isNotEmpty(user.getEventCardno())) {
            // 选择自然人的时候插入预警
            if (StringUtils.isNotEmpty(user.getIsKeynote()) && user.getIsKeynote().equals(NumberConstant.ONE_STRING)) {//2:矛盾纠纷  user.getIsKeynote():是否重点人群，1：是，2：否
//                    log.info("属于重点人群,记录重点人：{}", JSONUtil.toJsonStr(user));
                if (commonService.insert(nameSpaceUser + "insertTriggerEvent", user) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.RISK_EXCEPTION);
                }
            } else { // 如果某个自然人 提出的矛盾纠纷，并且是处理中状态的 超过3次，则进入风险预警
                Integer num = commonService.getObject(nameSpaceUser + "getUserEventNumber", user);
                if (num >= 3) {
//                        log.info("矛盾超过3次,记录重点人：{}", JSONUtil.toJsonStr(user));
                    if (commonService.insert(nameSpaceUser + "insertTriggerEvent", user) != NumberConstant.ONE_INT) {
                        throw new CustomException(NotesConstant.RISK_EXCEPTION);
                    }
                }
            }
        }
    }

    public void recordEventTrigger(ReqEventInsertVo vo) {
        Integer groupRiskLevel;
        Integer riskFactorLevel;
        Integer stakeholderLevel;
        // 判断 群体性事件风险等级
        groupRiskLevel = getGroupRiskLevel(vo);
        // 判断 风险因子风险等级
        riskFactorLevel = getRiskFactorLevel(vo);
        // 判断 涉众时间风险等级
        stakeholderLevel = getStakeholderLevel(vo);
        // 比较风险等级
        RiskComparisonDTO.RiskLevel groupEvent = new RiskComparisonDTO.RiskLevel(RiskComparisonDTO.RiskType.GROUP_EVENT, groupRiskLevel); // 群体性事件 - 等级
        RiskComparisonDTO.RiskLevel riskFactor = new RiskComparisonDTO.RiskLevel(RiskComparisonDTO.RiskType.RISK_FACTOR, riskFactorLevel); // 风险因子 - 等级
        RiskComparisonDTO.RiskLevel stakeholder = new RiskComparisonDTO.RiskLevel(RiskComparisonDTO.RiskType.STAKEHOLDER, stakeholderLevel); // 涉众 - 等级
        List<RiskComparisonDTO.RiskLevel> risks = Arrays.asList(groupEvent, riskFactor, stakeholder);

        // 找出最高风险等级
        List<RiskComparisonDTO.RiskLevel> highestRisks = findHighestRisk(risks);
        if (highestRisks == null) {
            return;
        }
        // 输出结果 只有一个最高等级
        if (highestRisks.size() == 1) {
            RiskComparisonDTO.RiskLevel risk = highestRisks.get(0);
//                    log.info("最高风险等级：{}", risk.getRiskType().getDescription() + " - 等级：" + risk.getLevel());
            if (risk.getRiskType() == RiskComparisonDTO.RiskType.GROUP_EVENT) {
                saveGroupEvent(vo, risk.getLevel());
                // 风险因子条件触发 则保存 等级为空
                if (riskFactorLevel != 99) {
                    saveRiskFactorEvent(vo, null);
                }
                // 风险因子条件触发 则保存 等级为空
                if (stakeholderLevel != 99) {
                    saveStakeholderEvent(vo, null);
                }
            } else if (risk.getRiskType() == RiskComparisonDTO.RiskType.RISK_FACTOR) {
                // 保存 风险因子高等级
                saveRiskFactorEvent(vo, risk.getLevel());
                // 其他非高等级 保存
                if (groupRiskLevel != 99) {
                    saveGroupEvent(vo, null);
                }
                if (stakeholderLevel != 99) {
                    saveStakeholderEvent(vo, null);
                }
            } else {
                // 保存涉众高等级
                saveStakeholderEvent(vo, risk.getLevel());
                // 其他非高等级 保存
                if (groupRiskLevel != 99) {
                    saveGroupEvent(vo, null);
                }
                if (riskFactorLevel != 99) {
                    saveRiskFactorEvent(vo, null);
                }
            }
        } else {
            //多个风险等级相同，均为最高
            List<RiskComparisonDTO.RiskType> type = new ArrayList<>();
//                    log.info("多个风险等级相同，均为最高，{}", JSONUtil.toJsonStr(highestRisks));
            for (RiskComparisonDTO.RiskLevel risk : highestRisks) {
                type.add(risk.getRiskType());
                if (risk.getRiskType() == RiskComparisonDTO.RiskType.GROUP_EVENT) {
                    saveGroupEvent(vo, risk.getLevel());
                } else if (risk.getRiskType() == RiskComparisonDTO.RiskType.RISK_FACTOR) {
                    // 保存 风险因子高等级
                    saveRiskFactorEvent(vo, risk.getLevel());
                } else {
                    // 保存涉众高等级
                    saveStakeholderEvent(vo, risk.getLevel());
                }
            }
            // 找出不是最高等级的数据 进行保存
            // 排除所有在 type 中存在的 RiskType 的 RiskLevel
            List<RiskComparisonDTO.RiskLevel> filteredRisks = risks.stream()
                    .filter(risk -> !type.contains(risk.getRiskType()))
                    .collect(Collectors.toList());
//                    log.info("找出不是最高等级的数据 进行保存：{}", JSONUtil.toJsonStr(filteredRisks));
            // 只能有一个 理论上
            for (RiskComparisonDTO.RiskLevel filteredRisk : filteredRisks) {
                if (filteredRisk.getRiskType().equals(RiskComparisonDTO.RiskType.GROUP_EVENT)) {
                    if (groupRiskLevel != 99) {
                        saveGroupEvent(vo, null);
                    }
                } else if (filteredRisk.getRiskType().equals(RiskComparisonDTO.RiskType.RISK_FACTOR)) {
                    if (riskFactorLevel != 99) {
                        saveRiskFactorEvent(vo, null);
                    }
                } else {
                    if (stakeholderLevel != 99) {
                        saveStakeholderEvent(vo, null);
                    }
                }
            }
        }
    }

    private void saveStakeholderEvent(ReqEventInsertVo vo, Integer level) {
        String uuid = UUIDUtil.getUUID();
        EventTrigger eventTrigger = new EventTrigger();
        eventTrigger.setId(uuid);
        eventTrigger.setTriggerType("3");// 涉众类型
        eventTrigger.setEventCategoryId(vo.getEventCategoryId());
        eventTrigger.setEventTypeId(vo.getEventTypeId());
        eventTrigger.set_user(vo.get_user());
        eventTrigger.setCityId(vo.getCityId());
        eventTrigger.setAreaId(vo.getAreaId());
        eventTrigger.setStreetId(vo.getStreetId());
        eventTrigger.setCommunityId(vo.getCommunityId());
        eventTrigger.setEventId(vo.getId());
        eventTrigger.setAlarmLevel(level);
        vo.setTriggerType("3");
        /*EventTrigger eventTriggerInfo = commonService.getObject(nameSpaceUser + "getEventTriggerInfo", vo);*/
        /*if (eventTriggerInfo == null) {*/
            // log.info("保存涉众重点事件：{}", JSONUtil.toJsonStr(eventTrigger));
        commonService.insert(nameSpaceUser + "insertEventTriggerForRisk", eventTrigger);
      /*  }*/
    }

    private void saveRiskFactorEvent(ReqEventInsertVo vo, Integer level) {
        EventRiskFactor eventRiskFactor = new EventRiskFactor();
        String eventTriggerId = UUIDUtil.getUUID();
        eventRiskFactor.setId(eventTriggerId);
        eventRiskFactor.setEventCategoryId(vo.getEventCategoryId());
        eventRiskFactor.setEventTypeId(vo.getEventTypeId());
        eventRiskFactor.set_user(vo.get_user());
        eventRiskFactor.setCityId(vo.getCityId());
        eventRiskFactor.setAreaId(vo.getAreaId());
        eventRiskFactor.setStreetId(vo.getStreetId());
        eventRiskFactor.setCommunityId(vo.getCommunityId());
        eventRiskFactor.setEventId(vo.getId());
        eventRiskFactor.setAlarmLevel(level);
        int insert = commonService.insert(nameSpaceEventRiskFactor + "insertEventRiskFactor", eventRiskFactor);
        // log.info("保存风险因子重点事件：{}", JSONUtil.toJsonStr(eventRiskFactor));
        if (insert != NumberConstant.ONE_INT) { // 重点事件预警
            throw new CustomException(NotesConstant.INSERT_EXCEPTION);
        }
    }

    private void saveGroupEvent(ReqEventInsertVo vo, Integer level) {
        // 保存
        Date currentOccurrenceDate = DateUtil.parse(vo.getOccurrenceTime(), "yyyy-MM-dd");
        vo.setOccurrenceTime(DateUtil.format(currentOccurrenceDate, "yyyy-MM-dd"));

        String uuid = UUIDUtil.getUUID();
        EventTrigger eventTrigger = new EventTrigger();
        eventTrigger.setId(uuid);
        eventTrigger.setTriggerType("2");// 群体性事假 类型
        eventTrigger.setEventCategoryId(vo.getEventCategoryId());
        eventTrigger.setEventTypeId(vo.getEventTypeId());
        eventTrigger.set_user(vo.get_user());
        eventTrigger.setCityId(vo.getCityId());
        eventTrigger.setAreaId(vo.getAreaId());
        eventTrigger.setStreetId(vo.getStreetId());
        eventTrigger.setCommunityId(vo.getCommunityId());
        eventTrigger.setAlarmLevel(level);
        // 查询是否已存在重点事件
        vo.setTriggerType("2");
        // 判断大类小类 如果为其他 不计入预警统计
        String eventCategoryId = vo.getEventCategoryId();
        String eventCategoryLabel = commonService.getObject(dictNameSpace + "getNameByEventCategoryId", eventCategoryId);
        if (eventCategoryLabel!=null && eventCategoryLabel.equals("其他")) {
            return;
        }
        String eventTypeId = vo.getEventTypeId();
        String eventTypeLabel = commonService.getObject(dictNameSpace + "getNameByEventTypeId", eventTypeId);
        if (eventTypeLabel!=null && eventTypeLabel.equals("其他")) {
            return;
        }

        EventTrigger eventTriggerInfo = commonService.getObject(nameSpaceUser + "getEventTriggerInfo", vo);
        if (eventTriggerInfo == null) {
            // log.info("保存群发性重点事件：{}", JSONUtil.toJsonStr(eventTrigger));
            commonService.insert(nameSpaceUser + "insertEventTriggerForRisk", eventTrigger);
        } else {
            // 更新预警等级
            eventTrigger.setId(eventTriggerInfo.getId());
            commonService.update(nameSpaceUser + "updateEventTriggerForRisk", eventTrigger);
            // log.info("更新群发性重点事件预警等级：{}", JSONUtil.toJsonStr(eventTrigger));
        }
    }

    private Integer getStakeholderLevel(ReqEventInsertVo vo) {
        Integer level = 99;
        if (Objects.equals(vo.getIs_involve_everyone(), NumberConstant.ONE_STRING)) {

            if (Objects.equals(vo.getIs_involve_everyone_count(), NumberConstant.ZERO_STRING)) {
                level = WarningLevelEnum.THREE_LEVEL.getStatus();
            } else if (Objects.equals(vo.getIs_involve_everyone_count(), NumberConstant.ONE_STRING)) {
                level = WarningLevelEnum.TWO_LEVEL.getStatus();
            } else {
                level = WarningLevelEnum.FIRST_LEVEL.getStatus();
            }
        }
        return level;
    }

    private Integer getRiskFactorLevel(ReqEventInsertVo vo) {
        Integer level = 99;
        String riskName = vo.getRiskName();
        String[] lengths = riskName != null ? riskName.split(",") : new String[0];
        if (lengths != null && lengths.length >= 3) {// 当存在风险因子>3 才会进行插入
            // 判断预警等级
            if (lengths.length == 3) {
                // 矛盾纠纷事件存在3个风险因子
                level = WarningLevelEnum.THREE_LEVEL.getStatus();
            } else if (lengths.length == 4) {
                //矛盾纠纷事件存在4个风险因子
                level = WarningLevelEnum.TWO_LEVEL.getStatus();
            } else {
                //矛盾纠纷事件存在4个及以上风险因子
                level = WarningLevelEnum.FIRST_LEVEL.getStatus();
            }
        }
        return level;
    }


    private Integer getGroupRiskLevel(ReqEventInsertVo vo) {
        Integer level = 99;
        List<ReqEventInsertVo> list = new ArrayList<>();
        EventCategory eventCategory = new EventCategory();
        eventCategory.setValue(vo.getEventTypeId());
        EventCategory category = commonService.getObject("com.scpyun.platform.standard.jilinsscgsdp.EventCategoryDao.selectEventCategory", eventCategory);
        if (category != null && Objects.equals(category.getIs_easy(), NumberConstant.ONE_STRING)) {
            Date currentOccurrenceDate = DateUtil.parse(vo.getOccurrenceTime(), "yyyy-MM-dd");
            vo.setOccurrenceTime(DateUtil.format(currentOccurrenceDate, "yyyy-MM-dd"));
            list = commonService.findList("com.scpyun.platform.standard.jilinsscgsdp.event.find30DayEvent", vo);
            // log.info("当前事件数量：{}", list.size());
           /* if (!list.isEmpty() && list.size() >= 5) {
                //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到5—30次的
                if (list.size() >= 5 && list.size() <= 30) {
                    // log.info("当前事件数量：{}", list.size());
                    level = WarningLevelEnum.THREE_LEVEL.getStatus();
                } else if (list.size() > 30 && list.size() <= 300) {
                    //  不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到31—300次
                    level = WarningLevelEnum.TWO_LEVEL.getStatus();
                } else {
                    //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到300次以上的
                    level = WarningLevelEnum.FIRST_LEVEL.getStatus();
                }
            }*/

            if (!list.isEmpty() && list.size() >= 3) {
                //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到5—30次的
                if (list.size() >= 3 && list.size() <= 5) {
                    // log.info("当前事件数量：{}", list.size());
                    level = WarningLevelEnum.THREE_LEVEL.getStatus();
                } else if (list.size() > 5 && list.size() <= 10) {
                    //  不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到31—300次
                    level = WarningLevelEnum.TWO_LEVEL.getStatus();
                } else {
                    //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到300次以上的
                    level = WarningLevelEnum.FIRST_LEVEL.getStatus();
                }
            }
        }
        return level;
    }


    /**
     * 保存重点事逻辑
     *
     * @param vo
     * @param list
     */
    private Integer saveEventTrigger(ReqEventInsertVo vo, List<ReqEventInsertVo> list) {
        // log.info("当前事件数量：{}", list.size());
        if (!list.isEmpty() && list.size() >= 4) {
            String uuid = UUIDUtil.getUUID();
            EventTrigger eventTrigger = new EventTrigger();
            eventTrigger.setId(uuid);
            eventTrigger.setTriggerType("2");// 群体性事假 类型
            eventTrigger.setEventCategoryId(vo.getEventCategoryId());
            eventTrigger.setEventTypeId(vo.getEventTypeId());
            eventTrigger.set_user(vo.get_user());
            eventTrigger.setCityId(vo.getCityId());
            eventTrigger.setAreaId(vo.getAreaId());
            eventTrigger.setStreetId(vo.getStreetId());
            eventTrigger.setCommunityId(vo.getCommunityId());
            //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到5—30次的
            if (list.size() >= 4 && list.size() <= 29) {
                eventTrigger.setAlarmLevel(WarningLevelEnum.THREE_LEVEL.getStatus());
                // log.info("群体性事件,5-30次：{}", JSONUtil.toJsonStr(eventTrigger));
            } else if (list.size() > 29 && list.size() <= 299) {
                //  不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到31—300次
                eventTrigger.setAlarmLevel(WarningLevelEnum.TWO_LEVEL.getStatus());
                // log.info("群体性事件,31—300次：{}", JSONUtil.toJsonStr(eventTrigger));
            } else {
                //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到300次以上的
                eventTrigger.setAlarmLevel(WarningLevelEnum.FIRST_LEVEL.getStatus());
                // log.info("群体性事件,300次以上：{}", JSONUtil.toJsonStr(eventTrigger));
            }

            // 查询是否已存在重点事件
            EventTrigger eventTriggerInfo = commonService.getObject(nameSpaceUser + "getEventTriggerInfo", vo);
            if (eventTriggerInfo == null) {
                // log.info("保存群发性重点事件：{}", JSONUtil.toJsonStr(eventTrigger));
                commonService.insert(nameSpaceUser + "insertEventTriggerForRisk", eventTrigger);
            } else {
                // 更新预警等级
                eventTrigger.setId(eventTriggerInfo.getId());
                commonService.update(nameSpaceUser + "updateEventTriggerForRisk", eventTrigger);
                // log.info("更新群发性重点事件预警等级：{}", JSONUtil.toJsonStr(eventTrigger));
            }
            for (ReqEventInsertVo reqEventInsertVo : list) {
                EventTriggerContradictoryDisputes eventTriggerContradictoryDisputes = new EventTriggerContradictoryDisputes();
                eventTriggerContradictoryDisputes.setId(UUIDUtil.getUUID());
                eventTriggerContradictoryDisputes.setJlEventId(reqEventInsertVo.getId());
                if (eventTriggerInfo == null) {
                    eventTriggerContradictoryDisputes.setJlEventTrigger(uuid);
                } else {
                    eventTriggerContradictoryDisputes.setJlEventTrigger(eventTriggerInfo.getId());
                }
                int insert = commonService.insert("com.scpyun.platform.standard.jilinsscgsdp.event.insertEventTriggerContradictoryDisputes", eventTriggerContradictoryDisputes);
            }
            return eventTrigger.getAlarmLevel();
        }
        return 0;
    }

    @ApiOperation(value = "事件上报下一步", desc = "事件上报下一步")
    public String insertEventFlowLog(@Valid ReqEventFlowLogInsertVo vo, Map<String, Object> map) {
//        vaid(vo.getCityId(),vo.getAreaId(),vo.getStreetId(),vo.getCommunityId());
        if (StringUtils.isNotEmpty(map.get("is_return_resubmit")) && map.get("is_return_resubmit").equals("1")) {// 退回重新上报，更新事件相关信息
            commonService.update(nameSpace + "updateEvent", map);
            // 清空当事人信息
            commonService.delete(nameSpace + "deleteClearEventUser", map);
            // 保存当事人信息
            List<ReqEventUserInsertVo> userList = vo.getUserList();
            for (ReqEventUserInsertVo user : userList) {
                if (user.getEventUserType().equals(NumberConstant.FOUR_STRING)) {
                    if (StringUtils.isNotEmpty(user.getEventCardno())) {
                        if (!IdcardUtil.isValidCard(user.getEventCardno())) {
                            throw new CustomException("证件号码错误！");
                        }
                    }
                }

                user.setEventId(vo.getId());
                user.set_user(vo.get_user());
                //添加当事人
                if (commonService.insert(nameSpaceUser + "insertEventUserKey", user) != NumberConstant.ONE_INT) {
                    throw new CustomException(user.getEventUserName() + NotesConstant.INSERT_EXCEPTION);
                }
                if (StringUtils.isNotEmpty(user.getEventCardno())) {
                    // 选择自然人的时候插入预警
                    if (vo.getEventType().equals("2") && StringUtils.isNotEmpty(user.getIsKeynote()) && user.getIsKeynote().equals(NumberConstant.ONE_STRING)) {//2:矛盾纠纷  user.getIsKeynote():是否重点人群，1：是，2：否
                        // log.info("属于重点人群,记录重点人：{}", JSONUtil.toJsonStr(user));
                        if (commonService.insert(nameSpaceUser + "insertTriggerEvent", user) != NumberConstant.ONE_INT) {
                            throw new CustomException(NotesConstant.RISK_EXCEPTION);
                        }
                    } else { // 如果某个自然人 提出的矛盾纠纷，并且是处理中状态的 超过3次，则进入风险预警
                        Integer num = commonService.getObject(nameSpaceUser + "getUserEventNumber", user);
                        if (num >= 3) {
                            // log.info("矛盾超过3次,记录重点人：{}", JSONUtil.toJsonStr(user));
                            if (commonService.insert(nameSpaceUser + "insertTriggerEvent", user) != NumberConstant.ONE_INT) {
                                throw new CustomException(NotesConstant.RISK_EXCEPTION);
                            }
                        }
                    }
                }
            }
            // 保存纠纷类型（其他）
            if (StringUtils.isNotEmpty(vo.getEvent_category_other_name()) || StringUtils.isNotEmpty(vo.getEvent_category_mini_other_name())) {
                commonService.insert(nameSpace + "insertEventCategoryOther", vo);
            }

            // todo 解除预警

        }

        if (!vo.getLogType().equals(NumberConstant.FOUR_STRING)) {
            if (StringUtils.isEmpty(vo.getIsSpecialTasks())) {
                throw new CustomException("专项任务类别不可为空！");
            }
            if (StringUtils.isEmpty(vo.getId())) {
                throw new CustomException("事件id不可为空！");
            }
            if (StringUtils.isEmpty(vo.getStatus())) {
                throw new CustomException("事件状态不可为空！");
            }
        }

        //添加图片
        // log.info("图片集合" + JSONUtil.toJsonStr(vo.getUrlList()));
        List<ReqEventAttachInsertVo> urlList = vo.getUrlList();
        if (!CollectionUtils.isEmpty(urlList)) {
            for (ReqEventAttachInsertVo sub : urlList) {
                // log.info("图片对象" + JSONUtil.toJsonStr(vo.getUrlList()));
                sub.setId(vo.getId());
                if (commonService.insert(nameSpaceAttach + "insertEventAttach", sub) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.INSERT_EXCEPTION);
                }
            }
        }

        JlEventFlowSetting eventFlowSettingMap = new JlEventFlowSetting();
        ReqEventInsertVo settingMap = new ReqEventInsertVo();
        Integer num = 0;
        ReqEventFlowLogInsertVo eventMap = commonService.getObject(nameSpace + "getEventLogByCompanyId", vo);
        vo.setEventId(eventMap.getEventId());
        vo.setId(eventMap.getId());
        eventFlowSettingMap.setId(eventMap.getFlowId());
        //vo.setEventFlowSettingType(NumberConstant.ONE_STRING);//old
        String grid = NumberConstant.ONE_STRING;
        //查询当前流程id的版本号
        eventFlowSettingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSettingByID", eventFlowSettingMap);
        vo.setEventFlowSettingType(eventFlowSettingMap.getType());//new
        switch (vo.getLogType()) {
            case NumberConstant.ONE_STRING: //上报
                vo.setHierarchy(eventFlowSettingMap.getHierarchy() + NumberConstant.ONE_INT);
                vo.setVersion(eventFlowSettingMap.getVersion());
                settingMap.setHierarchy(vo.getHierarchy());
                settingMap.setEventFlowSettingType(vo.getEventFlowSettingType());
                settingMap.setVersion(vo.getVersion());
                settingMap.set_user(vo.get_user());
                //获取当前条的id及版本号
                settingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", settingMap);
                String userType = commonService.getObject(nameSpaceSys + "getJobDuty", vo);
                if (NumberConstant.ONE_STRING.equals(userType)) {
                    vo.setOfficeId(vo.get_user().getCompany_id());
                } else {
                    //获取上级office_id
                    //vo.setOfficeId(commonService.getObject(nameSpaceSys + "getOfficeByCompany", vo));

                    // 判断上报用户是否是横向部门，如果是横向部门，则上报到同级别综治中心
                    String fax = commonService.getObject(nameSpace + "getFax", vo.get_user().getCompany_id());
                    if (StringUtils.isNotEmpty(fax)) {// 是横向部门
                        // 获取该横向部门所属的综治中心
                        String office_id = commonService.getObject(nameSpace + "getOfficeId", vo.get_user().getCompany_id());
                        vo.setOfficeId(office_id);
                        vo.setHierarchy(vo.getHierarchy() - 1);
                    } else {
                        vo.setOfficeId(commonService.getObject(nameSpaceSys + "getOfficeByCompany", vo));
                    }
                }
                vo.setFlowId(settingMap.getId());
                vo.setFlowVersion(settingMap.getVersion());
                vo.setIsResolve(NumberConstant.TWO_STRING);
                break;
            case NumberConstant.TWO_STRING://办结
                if (!NumberConstant.ONE_STRING.equals(vo.getIsResolve())) {
                    throw new CustomException(NotesConstant.DEFUSE_EXCEPTION);
                }
                ReqSysOfficeVo fax = commonService.getObject(nameSpaceSys + "getFaxById", vo);
                if (NumberConstant.ONE_STRING.equals(fax.getNum())) {
                    //num = commonService.getObject(nameSpaceFlow + "getUnitCompanyByEventId", vo);
                    // 判断之前是否已经有横向部门办结，如果有则不推送下一步数据（num>1），反之则设置num<1
                    /*int getHasResolveCount = commonService.getObject(nameSpaceFlow + "getHasResolveCount", vo);
                    if(getHasResolveCount>0){
                        num=2;
                    }else{
                        num=0;
                    }*/

                    int getHasNoResolveCount = commonService.getObject(nameSpaceFlow + "getHasNoResolveCount", vo);// 未处置部门数量
                    //int getHasBackCount = commonService.getObject(nameSpaceFlow + "getHasBackCount", vo);// 执行退回操作部门数量
                    if (getHasNoResolveCount > 1) {
                        num = 2;
                    } else {
                        num = 0;
                    }
                }
                ReqEventFlowLogInsertVo grad = commonService.getObject(nameSpaceFlow + "getFlowLogOfficeIdTimeAsc", vo);
                //获取网格员id
                User userMap = vo.get_user();
                if (grad.getCreateBy().equals(userMap.getId())) {
                    grid = NumberConstant.TWO_STRING;
                } else {
                    vo.setOfficeId(grad.getOfficeId());
                    if (NumberConstant.ONE_STRING.equals(grad.getGradeUserId())) {
                        vo.setGradeUserId(grad.getCreateBy());
                    }
                    vo.setFlowId(grad.getFlowId());
                    vo.setFlowVersion(grad.getFlowVersion());
                }
                break;
            case NumberConstant.FOUR_STRING://退回
                vo.setIsResolve(NumberConstant.TWO_STRING);
                // 获取当前用户是否是横向部门，如果是横向部门则退回到所属综治中心
                String faxValue = commonService.getObject(nameSpace + "getFax", vo.get_user().getCompany_id());
                if (StringUtils.isNotEmpty(faxValue)) {// 横向部门
                    vo.setHierarchy(eventFlowSettingMap.getHierarchy());

                    // 判断是否都已办结完毕，如果横向部门都已办结完毕，则推送待办至矛盾创建人（矛盾创建人可进行办结操作）
                    /*int getHasNoResolveCount = commonService.getObject(nameSpaceFlow + "getHasNoResolveCount", vo);// 未处置部门数量
                    if(getHasNoResolveCount==1){
                        // 获取该矛盾事件的创建人及所属机构
                        Map<String,Object> eventCreateAndOffice = commonService.getObject(nameSpace + "getEventCreateAndOffice", vo);
                        ReqEventInsertVo param=new ReqEventInsertVo();
                        param.setEventId(vo.getEventId());
                        param.setOfficeId((String) eventCreateAndOffice.get("office_id"));
                        param.setGradeUserId((String) eventCreateAndOffice.get("grade_user_id"));
                        param.setFlowVersion(eventCreateAndOffice.get("flow_version")+"");
                        param.setFlowId((String) eventCreateAndOffice.get("flow_id"));
                        param.setStatus("2");
                        param.setLogType("2");
                        param.setRiskLevel(vo.getRiskLevel());
                        param.setResolveTime(vo.getResolveTime());
                        param.setIsResolve("1");
                        param.set_user(vo.get_user());
                        int insert = commonService.insert(nameSpaceFlow + "insertEventFlowLog", param);
                        //num=2;
                    }*/
                } else {
                    if (eventFlowSettingMap.getType().equals("2")) { // 下派-退回
                        vo.setHierarchy(eventFlowSettingMap.getHierarchy() + NumberConstant.ONE_INT);
                    } else {
                        vo.setHierarchy(eventFlowSettingMap.getHierarchy() - NumberConstant.ONE_INT);
                    }
                }
                vo.setVersion(eventFlowSettingMap.getVersion());
                //获取当前条的id及版本号
                settingMap.setHierarchy(vo.getHierarchy());
                settingMap.setEventFlowSettingType(vo.getEventFlowSettingType());
                settingMap.setVersion(vo.getVersion());
//                settingMap.setId(eventFlowSettingMap.getId());
                settingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", settingMap);
                settingMap.setEventId(vo.getEventId());

                if (eventFlowSettingMap.getType().equals("2")) { // 下派-退回
                    vo.setFlowId(settingMap.getId());
                    vo.setFlowVersion(settingMap.getVersion());
                    // 获取被下派单位的 上级单位
                    String officeId = commonService.getObject(nameSpace + "getOfficeIdByLogId", vo.getId());
                    vo.setOfficeId(officeId);
                } else {
                    ReqEventInsertVo officeOrderMap = commonService.getObject(nameSpaceFlow + "getFlowLogOfficeIdTime", settingMap);
                    if (!"-1".equals(officeOrderMap.getGradeUserId())) {
                        vo.setGradeUserId(officeOrderMap.getGradeUserId());
                    }
                    if (StringUtils.isNotEmpty(faxValue)) {// 横向部门
                        String officeId = commonService.getObject(nameSpace + "getOfficeId", vo.get_user().getCompany_id());
                        vo.setOfficeId(officeId);
                    } else {
                        vo.setOfficeId(officeOrderMap.getOfficeId());
                    }
                    vo.setFlowId(settingMap.getId());
                    vo.setFlowVersion(settingMap.getVersion());
                    //如果分派数据退回则分派状态设为待确认
                    if (officeOrderMap.getLogType().equals(NumberConstant.THREE_STRING) || officeOrderMap.getLogType().equals(NumberConstant.FOUR_STRING)) {
                        officeOrderMap.setAssignmentType(NumberConstant.THREE_STRING);
                    }
                }
                break;
            case NumberConstant.SIX_STRING://下派
                vo.setEventFlowSettingType(NumberConstant.TWO_STRING);
                vo.setHierarchy(eventFlowSettingMap.getHierarchy() - NumberConstant.ONE_INT);
                vo.setVersion(eventFlowSettingMap.getVersion());
                //获取当前条的id及版本号
                settingMap.setHierarchy(vo.getHierarchy());
                settingMap.setEventFlowSettingType(vo.getEventFlowSettingType());
                settingMap.setVersion(vo.getVersion());
                settingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", settingMap);
                //获取上级office_id
                vo.setOfficeId(vo.getCrossOfficeId());
                vo.setFlowId(settingMap.getId());
                vo.setFlowVersion(settingMap.getVersion());
                vo.setIsResolve(NumberConstant.TWO_STRING);
                if (StringUtils.isNotEmpty(vo.getGridType()) && vo.getGridType().equals(NumberConstant.ONE_STRING)) {
                    vo.setGradeUserId(vo.getCrossOfficeId());
                    vo.setOfficeId(vo.get_user().getCompany_id());
                } else {
                    vo.setOfficeId(vo.getCrossOfficeId());
                }
                break;
            default:
                throw new CustomException(NotesConstant.LOG_EXCEPTION);
        }
        //修改当前条日志为完成状态
        vo.setStatus(NumberConstant.THREE_STRING);
        if (commonService.update(nameSpaceFlow + "updateEventFlowLogStatus", vo) < NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.EVENT_LOG_EXCEPTION);
        }
        if (num > NumberConstant.ONE_INT) {
            return NotesConstant.SAVE_SUCCESS;
        }
        if (grid.equals(NumberConstant.ONE_STRING)) {
            //新增待处理日志信息
            if (vo.getLogType().equals(NumberConstant.TWO_STRING)) {
                vo.setStatus(NumberConstant.TWO_STRING);
            }/*else if(vo.getLogType().equals(NumberConstant.FOUR_STRING)){
                vo.setLogType(NumberConstant.ONE_STRING);
                vo.setStatus(NumberConstant.ONE_STRING);
            }*/ else {
                vo.setStatus(NumberConstant.ONE_STRING);
            }
            // 清空处置结果
            vo.setLogResult("");
            /*vo.setIsResolve("");*/
            vo.setResolveName("");
            vo.setResolveUnit("");
            vo.setResolveHierarchy("");
            vo.setResolveWay("");
            vo.setIsSatisfaction("");
            vo.setResolveProcess("");
            if (commonService.update(nameSpaceFlow + "insertEventFlowLog", vo) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
            }
        }
        // 更改 jl_event 主表的 risk_level 以及 risk_name
        if (StringUtils.isNotEmpty(vo.getId())) {
            commonService.update(nameSpace + "updateEventRiskLevel", vo);// 更新jl_event表的risk_level以及is_scanned
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "分派任务", desc = "分派任务")
    public String insertEventFlowLogAssignment(@Valid ReqEventFlowLogInsertVo vo) {
        List<String> officeIdList = EventFlowLogCheckUtils.eventFlowLogAssignmentCheck(vo);
        ReqEventInsertVo eventFlowSettingMap = new ReqEventInsertVo();
        ReqEventFlowLogInsertVo eventMap = commonService.getObject(nameSpace + "getEventLogById", vo);
        vo.setEventId(eventMap.getEventId());
        vo.setId(eventMap.getId());
        //修改当前条日志为完成状态
        vo.setStatus(NumberConstant.THREE_STRING);
        vo.setIsResolve(NumberConstant.TWO_STRING);
        if (commonService.update(nameSpaceFlow + "updateEventFlowLogStatus", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.EVENT_LOG_EXCEPTION);
        }
        ReqSysOfficeVo sysVo = new ReqSysOfficeVo();
        for (int i = 0; i < officeIdList.size(); i++) {
            vo.setOfficeId(officeIdList.get(i));
            sysVo.setOfficeId(officeIdList.get(i));
            //获取对应的审批流程层级
            Integer hierarchy = commonService.getObject(nameSpaceSys + "getHierarchy", sysVo);
            if (hierarchy == 0) {
                throw new CustomException(NotesConstant.LOG_EXCEPTION);
            }
            eventFlowSettingMap.setHierarchy(hierarchy);
            eventFlowSettingMap.setVersion(eventMap.getFlowVersion());
            eventFlowSettingMap.setId(eventMap.getFlowId());
            eventFlowSettingMap.setEventFlowSettingType(NumberConstant.ONE_STRING);
            //获取当前条的id及版本号
            eventFlowSettingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", eventFlowSettingMap);
            if (null == eventFlowSettingMap) {
                throw new CustomException("未获取到层级为[" + hierarchy + "]的审批流程设置");
            }
            vo.setFlowId(eventFlowSettingMap.getId());
            vo.setFlowVersion(eventFlowSettingMap.getVersion());
            //新增待处理日志信息
            vo.setStatus(NumberConstant.ONE_STRING);
            ReqEventInsertVo employee = new ReqEventInsertVo();
            employee.copyFrom(vo);
            employee.setIs_dispatch_office("1");
            if (commonService.update(nameSpaceFlow + "insertEventFlowLog", employee) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
            }
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "办结", desc = "办结")
    public String updateEventCompletion(@Valid ReqEventFlowLogInsertVo vo, Map<String, Object> map) {

        if (StringUtils.isNotEmpty(map.get("is_return_resubmit")) && map.get("is_return_resubmit").equals("1")) {// 退回重新上报，更新事件相关信息
            commonService.update(nameSpace + "updateEvent", map);
            // 清空当事人信息
            commonService.delete(nameSpace + "deleteClearEventUser", map);
            // 保存当事人信息
            List<ReqEventUserInsertVo> userList = vo.getUserList();
            for (ReqEventUserInsertVo user : userList) {
                if (user.getEventUserType().equals(NumberConstant.FOUR_STRING)) {
                    if (StringUtils.isNotEmpty(user.getEventCardno())) {
                        if (!IdcardUtil.isValidCard(user.getEventCardno())) {
                            throw new CustomException("证件号码错误！");
                        }
                    }
                }

                user.setEventId(vo.getId());
                user.set_user(vo.get_user());
                //添加当事人
                if (commonService.insert(nameSpaceUser + "insertEventUserKey", user) != NumberConstant.ONE_INT) {
                    throw new CustomException(user.getEventUserName() + NotesConstant.INSERT_EXCEPTION);
                }
                if (StringUtils.isNotEmpty(user.getEventCardno())) {
                    // 选择自然人的时候插入预警
                    if (vo.getEventType().equals("2") && StringUtils.isNotEmpty(user.getIsKeynote()) && user.getIsKeynote().equals(NumberConstant.ONE_STRING)) {//2:矛盾纠纷  user.getIsKeynote():是否重点人群，1：是，2：否
                        // log.info("属于重点人群,记录重点人：{}", JSONUtil.toJsonStr(user));
                        if (commonService.insert(nameSpaceUser + "insertTriggerEvent", user) != NumberConstant.ONE_INT) {
                            throw new CustomException(NotesConstant.RISK_EXCEPTION);
                        }
                    } else { // 如果某个自然人 提出的矛盾纠纷，并且是处理中状态的 超过3次，则进入风险预警
                        Integer num = commonService.getObject(nameSpaceUser + "getUserEventNumber", user);
                        if (num >= 3) {
                            // log.info("矛盾超过3次,记录重点人：{}", JSONUtil.toJsonStr(user));
                            if (commonService.insert(nameSpaceUser + "insertTriggerEvent", user) != NumberConstant.ONE_INT) {
                                throw new CustomException(NotesConstant.RISK_EXCEPTION);
                            }
                        }
                    }
                }
            }
            // 保存纠纷类型（其他）
            if (StringUtils.isNotEmpty(vo.getEvent_category_other_name()) || StringUtils.isNotEmpty(vo.getEvent_category_mini_other_name())) {
                commonService.insert(nameSpace + "insertEventCategoryOther", vo);
            }
            // todo 解除预警
        }

        ReqEventFlowLogInsertVo eventMap = commonService.getObject(nameSpace + "getEventLogByCreateId", vo);
        if (StringUtils.isEmpty(eventMap.getEventType())) {
            eventMap = commonService.getObject(nameSpace + "getEventLogById", vo);
        }
        vo.setEventId(eventMap.getEventId());
        vo.setId(eventMap.getId());
        vo.setStatus(NumberConstant.THREE_STRING);
        if (commonService.update(nameSpaceFlow + "updateEventFlowLogStatusEnd", vo) < NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.LOG_EXCEPTION);
        }
        if (commonService.update(nameSpace + "updateEventStatusById", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.EVENT_LOG_EXCEPTION);
        }
        List<JlEventUser> userList = commonService.findList(nameSpaceUser + "selectUserByEventIdList", vo);
        // 解除重点人
        for (JlEventUser user : userList) {
            ReqEventUserInsertVo userVo = new ReqEventUserInsertVo();
            userVo.setEventCardno(user.getEventCardno());
            Integer num = commonService.getObject(nameSpaceUser + "getUserEventNumber", userVo);
            Integer triggerNum = commonService.getObject(nameSpaceUser + "getTriggerEventUserNumber", user);
            if (num < 3 && triggerNum > 0) {
                if (commonService.update(nameSpaceUser + "updateTriggerEventType", user) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.RISK_EXCEPTION);
                }
                // 记录重点人 解除历史  姓名 身份证号 最近解除时间
                TriggerEventHistory history = new TriggerEventHistory();
                history.setId(UUIDUtil.getUUID());
                history.setName(user.getEventUserName());
                history.setCardno(user.getEventCardno());
                history.setCityId(eventMap.getCityId());
                history.setAreaId(eventMap.getAreaId());
                history.setStreetId(eventMap.getStreetId());
                history.setCommunityId(eventMap.getCommunityId());
                history.setEventId(eventMap.getEventId());
                if (commonService.insert(nameSpaceUser + "insertTriggerEventHistory", history) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
                }
            }
        }
        // 判断风险因子表,群体性表 不符合重点事件条件   则删除重点事件
        final ReqEventFlowLogInsertVo s = eventMap;
        threadPoolExecutor.execute(() -> {
            deleteEvent(s);
        });
        return NotesConstant.SAVE_SUCCESS;
    }

    private void deleteEvent(ReqEventFlowLogInsertVo eventMap) {
        try {
            Thread.sleep(10000L);
            // log.info("解除重点事参数：{}", JSONUtil.toJsonStr(eventMap));
            EventRiskFactor eventRiskFactor = new EventRiskFactor();
            eventRiskFactor.setEventId(eventMap.getEventId());
            DataSourceSwitcher.setMaster();
            DataSourceSwitcher.setSharding("all");
            commonService.update(nameSpaceEventRiskFactor + "delEventRiskFactor", eventRiskFactor);


            ReqEventInsertVo stakeholdersEvent = new ReqEventInsertVo();
            stakeholdersEvent.setEventId(eventMap.getEventId());
            DataSourceSwitcher.setMaster();
            DataSourceSwitcher.setSharding("all");
            commonService.update(nameSpace + "delStakeholderEventTrigger", stakeholdersEvent);

            ReqEventInsertVo event = new ReqEventInsertVo();
            event.setEventCategoryId(eventMap.getEventCategoryName());
            event.setEventTypeId(eventMap.getEventTypeName());
            event.setCityId(eventMap.getCityId());
            event.setAreaId(eventMap.getAreaId());
            event.setStreetId(eventMap.getStreetId());
            event.setCommunityId(eventMap.getCommunityId());
            event.setTriggerType("2");
            // 解除重点事 相同发生地 相同大类小类 是否存在重点事 如果存在 则判断在发生日期30天前 是否存在大于5次的同类型的事件
            EventTrigger eventTriggerInfo = commonService.getObject(nameSpaceUser + "getEventTriggerInfo", event);
            if (eventTriggerInfo != null) {
                Date currentOccurrenceDate = DateUtil.parse(eventMap.getOccurrenceTime(), "yyyy-MM-dd");
                event.setOccurrenceTime(DateUtil.format(currentOccurrenceDate, "yyyy-MM-dd"));
                List<ReqEventInsertVo> list = commonService.findList("com.scpyun.platform.standard.jilinsscgsdp.event.find30DayEvent", event);
                Integer level;
                // log.info("相同发生地 存在事件：{}", JSONUtil.toJsonStr(list));
                /*if (list != null && list.size() < 5) {
                    // log.info("相同发生地 存在事件小于5次,解除 参数：{}", JSONUtil.toJsonStr(event));
                    // 删除重点事 按照地区和类型
                    if (commonService.update(nameSpace + "delEventTrigger", event) != NumberConstant.ONE_INT) {
                        throw new CustomException(NotesConstant.UPDATE_EXCEPTION);
                    }
                }else if (list != null && list.size() >= 5){
                    // 判断 群体性事件风险等级
                    if (list.size() >= 5 && list.size() <= 30) {
                        // log.info("当前事件数量：{}", list.size());
                        level = WarningLevelEnum.THREE_LEVEL.getStatus();
                    } else if (list.size() > 30 && list.size() <= 300) {
                        //  不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到31—300次
                        level = WarningLevelEnum.TWO_LEVEL.getStatus();
                    } else {
                        //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到300次以上的
                        level = WarningLevelEnum.FIRST_LEVEL.getStatus();
                    }

                    // 更新为历史
                    commonService.update(nameSpace + "delEventTrigger", event);
                    // 添加新的等级
                    String uuid = UUIDUtil.getUUID();
                    EventTrigger eventTrigger = new EventTrigger();
                    eventTrigger.setId(uuid);
                    eventTrigger.setTriggerType("2");// 群体性事假 类型
                    eventTrigger.setEventCategoryId(event.getEventCategoryId());
                    eventTrigger.setEventTypeId(event.getEventTypeId());
                    eventTrigger.set_user(event.get_user());
                    eventTrigger.setCityId(event.getCityId());
                    eventTrigger.setAreaId(event.getAreaId());
                    eventTrigger.setStreetId(event.getStreetId());
                    eventTrigger.setCommunityId(event.getCommunityId());
                    eventTrigger.setAlarmLevel(level);
                    commonService.insert(nameSpaceUser + "insertEventTriggerForRisk", eventTrigger);
                }*/
                if (list != null && list.size() < 3) {
                     log.info("相同发生地 存在事件小于5次,解除 参数：{}", JSONUtil.toJsonStr(event));
                    // 删除重点事 按照地区和类型
                    if (commonService.update(nameSpace + "delEventTrigger", event) != NumberConstant.ONE_INT) {
                        throw new CustomException(NotesConstant.UPDATE_EXCEPTION);
                    }
                }else if (list != null && list.size() >= 3){
                    // 判断 群体性事件风险等级
                    if (list.size() >= 3 && list.size() <= 5) {
                        // log.info("当前事件数量：{}", list.size());
                        level = WarningLevelEnum.THREE_LEVEL.getStatus();
                    } else if (list.size() > 5 && list.size() <= 10) {
                        //  不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到31—300次
                        level = WarningLevelEnum.TWO_LEVEL.getStatus();
                    } else {
                        //不同当事人涉及的矛盾纠纷大类、小类相同，且属于易引发群体性事件矛盾纠纷类型，矛盾纠纷发生地相同，发生时间跨度在30日内，并达到300次以上的
                        level = WarningLevelEnum.FIRST_LEVEL.getStatus();
                    }

                    // 更新为历史
                    commonService.update(nameSpace + "delEventTrigger", event);
                    // 添加新的等级
                    String uuid = UUIDUtil.getUUID();
                    EventTrigger eventTrigger = new EventTrigger();
                    eventTrigger.setId(uuid);
                    eventTrigger.setTriggerType("2");// 群体性事假 类型
                    eventTrigger.setEventCategoryId(event.getEventCategoryId());
                    eventTrigger.setEventTypeId(event.getEventTypeId());
                    eventTrigger.set_user(event.get_user());
                    eventTrigger.setCityId(event.getCityId());
                    eventTrigger.setAreaId(event.getAreaId());
                    eventTrigger.setStreetId(event.getStreetId());
                    eventTrigger.setCommunityId(event.getCommunityId());
                    eventTrigger.setAlarmLevel(level);

                    // 判断是否存在
                    event.setAlarmLevel(level);
                    EventTrigger existEventTrigger = commonService.getObject(nameSpaceUser + "getEventTriggerInfo", event);
                    if (existEventTrigger == null) {
                        commonService.insert(nameSpaceUser + "insertEventTriggerForRisk", eventTrigger);
                    }
                }
            }
        } catch (Exception e) {
            log.error("删除事件异常 eventId：{}", eventMap.getEventId(), e);
        }
    }

    @ApiOperation(value = "", desc = "")
    public List<FollowUpRecords> selectFollowUpRecordsList(FollowUpRecords followUpRecords) {
        if (StringUtils.isEmpty(followUpRecords.getEventCode())) {
            throw new CustomException("事件编码不可为空！");
        }
        List<FollowUpRecords> list = commonService.findList(nameSpace + "findFollowUpRecordsList", followUpRecords);
        for (FollowUpRecords upRecords : list) {
            FollowUpRecordsFiles followUpRecordsFiles = new FollowUpRecordsFiles();
            followUpRecordsFiles.setJlFollowUpRecordsId(upRecords.getId());
            upRecords.setFiles(commonService.findList(nameSpace + "findFollowUpRecordsListFile", followUpRecordsFiles));
        }
        return list;
    }

    @Autowired
    UploadServiceImpl uploadService;

    @ApiOperation(value = "增加回访记录附件", desc = "")
    public FollowUpRecordsFiles insertFollowUpRecordsFiles(FollowUpRecordsFiles followUpRecordsFiles, MultipartFile file) {
        if (StringUtils.isEmpty(followUpRecordsFiles.getId())) {
            throw new CustomException("id ?");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("business_type", "followUpRecordsListUploadFile");
        map = uploadService.uploadFile(map, file);
        followUpRecordsFiles.setJlFollowUpRecordsId(followUpRecordsFiles.getId());
        followUpRecordsFiles.setObsKey(map.get("uuid").toString());
        followUpRecordsFiles.setFileName(map.get("originalFilename").toString());
        followUpRecordsFiles.setId(UUIDUtil.getUUID());
        commonService.insert(nameSpace + "insertFollowUpRecordsFiles", followUpRecordsFiles);
        followUpRecordsFiles.set_user(new User());
        return followUpRecordsFiles;
    }

    @ApiOperation(value = "", desc = "")
    public Integer deleteFollowUpRecords(FollowUpRecords followUpRecords) {
        if (StringUtils.isEmpty(followUpRecords.getId())) {
            throw new CustomException("id ?");
        }
        return commonService.update(nameSpace + "deleteFollowUpRecords", followUpRecords);
    }

    @ApiOperation(value = "", desc = "")
    public Integer insertFollowUpRecords(FollowUpRecords followUpRecords) {
        if (StringUtils.isEmpty(followUpRecords.getEventCode())) {
            throw new CustomException("事件编码不可为空！");
        }
        followUpRecords.setId(UUIDUtil.getUUID());
        return commonService.insert(nameSpace + "insertFollowUpRecords", followUpRecords);
    }

    @ApiOperation(value = "", desc = "")
    public Integer updateFollowUpRecords(FollowUpRecords followUpRecords) {
        if (StringUtils.isEmpty(followUpRecords.getEventCode())) {
            throw new CustomException("事件编码不可为空！");
        }
        return commonService.update(nameSpace + "updateFollowUpRecords", followUpRecords);
    }

    @ApiOperation(value = "事件查询", desc = "事件查询")
    public Page<ReqEventFlowLogInsertVo> findEventLogByOfficeStatusList(Page<ReqEventFlowLogInsertVo> page) throws ParseException {
        Page<ReqEventFlowLogInsertVo> eventList = commonService.findPage(nameSpace + "findEventLogByOfficeStatusList", page);
        //设置超时信息
        setTimeout(eventList);
        return setEarlyWarning(eventList);
    }

    @ApiOperation(value = "网格员事件查询", desc = "网格员事件查询")
    public Page<ReqEventFlowLogInsertVo> findEventLogByCreateList(Page<ReqEventFlowLogInsertVo> page) throws ParseException {
        Page<ReqEventFlowLogInsertVo> eventList = commonService.findPage(nameSpace + "findEventLogByCreateList", page);
        //设置超时信息
        setTimeout(eventList);
        return setEarlyWarning(eventList);
    }

    private void setTimeout(Page<ReqEventFlowLogInsertVo> eventList) throws ParseException {
        for (ReqEventFlowLogInsertVo vo : eventList.getResults()) {
            vo.setWarningLight(false);//不预警
            if (StringUtils.isEmpty(vo.getCompleteTime())) {
                //未办结
                vo.setWarningState("不涉及");
            } else {
                //申请不回访
                if ("1".equals(vo.getReturnVisit())) {
                    vo.setWarningState("不回访");
                } else {
                    //获取回访记录
                    FollowUpRecords followUpRecords = new FollowUpRecords();
                    followUpRecords.setEventCode(vo.getEventCode());
                    List<FollowUpRecords> list = commonService.findList(nameSpace + "findFollowUpRecordsList", followUpRecords);
                    String today = DateUtils.setDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
                    long day = daysBetween(vo.getCompleteTime(), today);
                    //7日内是否完成
                    boolean finish7 = visitTimeout(list, -1, 7, vo.getCompleteTime());
                    //30日内是否完成
                    boolean finish30 = visitTimeout(list, 7, 30, vo.getCompleteTime());
                    //90日内是否完成
                    boolean finish90 = visitTimeout(list, 30, 90, vo.getCompleteTime());
                    String riskLevel = vo.getRiskLevel();//风险等级 无 ,一般矛盾纠纷 ,复杂矛盾纠纷 ,重大矛盾纠纷
                    //涉及(事件已办结但未超时)、不涉及(事件未办结)、未完成(复杂或者重大完成一次及以上填报)、已完成(已完成填报)已超时(未按时间进行填报)
                    switch (riskLevel) {
                        case "一般矛盾纠纷":
                            if (finish7) {
                                vo.setWarningState("已完成");
                            } else {
                                if (day > 7) {
                                    vo.setWarningLight(true);//预警
                                    vo.setWarningState("已超时");
                                } else {
                                    vo.setWarningState("涉及");
                                }
                            }
                            break;
                        case "复杂矛盾纠纷":
                            if (finish7 && finish30) {
                                vo.setWarningState("已完成");
                            } else {
                                if (finish7) {
                                    if (day > 30) {
                                        vo.setWarningLight(true);//预警
                                        vo.setWarningState("已超时");
                                    } else {
                                        vo.setWarningState("未完成");
                                    }
                                } else {
                                    if (day > 7) {
                                        vo.setWarningLight(true);//预警
                                        vo.setWarningState("已超时");
                                    } else {
                                        vo.setWarningState("涉及");
                                    }
                                }
                            }
                            break;
                        case "重大矛盾纠纷":
                            if (finish7 && finish30 && finish90) {
                                vo.setWarningState("已完成");
                            } else {
                                if (finish7 && finish30) {
                                    if (day > 90) {
                                        vo.setWarningLight(true);//预警
                                        vo.setWarningState("已超时");
                                    } else {
                                        vo.setWarningState("未完成");
                                    }
                                } else {
                                    if (finish7) {
                                        if (day > 30) {
                                            vo.setWarningLight(true);//预警
                                            vo.setWarningState("已超时");
                                        } else {
                                            vo.setWarningState("涉及");
                                        }
                                    } else {
                                        if (day > 7) {
                                            vo.setWarningLight(true);//预警
                                            vo.setWarningState("已超时");
                                        } else {
                                            vo.setWarningState("涉及");
                                        }
                                    }
                                }
                            }
                            break;
                    }
                }
            }
        }
    }

    /**
     * 判断回访完成
     *
     * @param list
     * @param beginDay
     * @param endDay
     * @param completeTime
     * @return
     */
    private Boolean visitTimeout(List<FollowUpRecords> list, int beginDay, int endDay, String completeTime) {
        for (FollowUpRecords records : list) {
            if (daysBetween(completeTime, records.getCreateTime()) <= endDay && daysBetween(completeTime, records.getCreateTime()) > beginDay) {
                return true;
            }
        }
        return false;
    }

    public static long daysBetween(String da1, String day2) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate today = LocalDate.parse(da1, formatter);
        LocalDate xDate = LocalDate.parse(day2, formatter);
        return ChronoUnit.DAYS.between(today, xDate);
    }

    //    @ApiOperation(value = "修改事件信息", desc = "修改事件信息")
    public String updateEvent(Map<String, Object> map) {
        EventCheckUtils.eventUpdateCheck(map);
        //事件
        Map<String, Object> eventMap = (Map<String, Object>) map.get("eventMap");
        EventCheckUtils.eventCheck(eventMap);
        //日志
        Map<String, Object> eventFlowLogMap = (Map<String, Object>) map.get("eventFlowLogMap");
        EventFlowLogCheckUtils.eventFlowLogCheck(eventFlowLogMap);
        eventMap.put("_user", map.get("_user"));
        eventFlowLogMap.put("_user", map.get("_user"));
        Integer count = commonService.getObject(nameSpaceFlow + "getFlowLogCount", eventFlowLogMap);
        if (count == 0) {
            throw new CustomException(NotesConstant.UPDATE_EVENT_EXCEPTION);
        }
        List<Map<String, Object>> userList = (List<Map<String, Object>>) map.get("userList");
        for (Map<String, Object> user : userList) {
            EventUserCheckUtils.eventUserCheck(user);
            user.put("_user", map.get("_user"));
            //添加当事人
            if (commonService.insert(nameSpaceUser + "insertEventUserKey", user) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.USER_EXCEPTION);
            }
        }
        if (commonService.update(nameSpace + "updateEvent", eventMap) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.EVENT_LOG_EXCEPTION);
        }
        if (commonService.update(nameSpaceFlow + "updateEventFlowLog", eventFlowLogMap) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.EVENT_LOG_EXCEPTION);
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "网格员待办结列表", desc = "网格员待办结列表")
    public List<ReqEventFlowLogInsertVo> selectAgencySettlementList(ReqEventFlowLogInsertVo vo) {
        List<ReqEventFlowLogInsertVo> evenIdList = commonService.findList(nameSpace + "selectEventIdByUserIdList", vo);
        List<ReqEventFlowLogInsertVo> eventList = new ArrayList<>();
        for (ReqEventFlowLogInsertVo event : evenIdList) {
            Integer count = commonService.getObject(nameSpaceFlow + "getCountLogAssignment", event);
            if (count < 0) {
                eventList.add(event);
            }
        }
        return eventList;
    }

    /*@ApiOperation(value = "事件删除", desc = "事件删除")
    public String updateEventDel(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("id不可为空！");
        }
        if (commonService.update(nameSpace + "updateEventDel", map) != NumberConstant.ONE_INT) {
            throw new CustomException("事件删除失败！");
        }
        map.put("event_id", map.get("id"));
        if (commonService.update(nameSpaceFlow + "updateEventFlowDel", map) < NumberConstant.ONE_INT) {
            throw new CustomException("日志删除失败！");
        }
        if (commonService.update(nameSpaceUser + "updateEventUserDel", map) < NumberConstant.ONE_INT) {
            throw new CustomException("当事人删除失败！");
        }
        return NotesConstant.SAVE_SUCCESS;
    }*/

    @ApiOperation(value = "修改受理状态", desc = "修改受理状态")
    public String updateEventAcceptance(ReqEventFlowLogInsertVo vo) {
        if (commonService.update(nameSpace + "updateEventAcceptance", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.EVENT_LOG_EXCEPTION);
        }
        ReqEventFlowLogInsertVo logMap = commonService.getObject(nameSpaceFlow + "selectEventFlowByEventId", vo);
        if (commonService.update(nameSpaceFlow + "updateEventFlowLogStatusByID", logMap) < NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.LOG_EXCEPTION);
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "网格员直接办结", desc = "网格员直接办结")
    public String insertEventEnd(@Valid ReqEventInsertVo vo) {
//        List<Map<String, Object>> userList = EventCheckUtils.eventCheck(map);
        if (StringUtils.isEmpty(vo.getId())) {
            vo.setId(IdUtil.randomUUID());
            vo.setEventCode(this.eventCode(vo));
        } else {
            vo.setEvent_tel(vo.getEventTel());
            vo.setEventSource("4");
            if (commonService.update(nameSpaceSafeSound + "updateSafeSoundEventByType", vo) != 1) {
                throw new CustomException(NotesConstant.INSERT_EXCEPTION);
            }
            vo.setEventCategoryId(commonService.getObject(nameSpaceSafeSound + "getValueNameDict", vo));
        }
        EventWarningSettingBo waitingMap = commonService.getObject(nameSpaceWaiting + "getWarnDealTime", vo);
        vo.setEarlyWarningTime(waitingMap.getEarlyWarningTime());
        vo.setAlarmTime(waitingMap.getAlarmTime());
        vo.setStatus(NumberConstant.ONE_STRING);
//        vo.setEventCode(this.eventCode(vo));
        vo.setReportingName(vo.get_user().getName());
        vo.setReportingUnit(vo.get_user().getCompany_name());
        vo.setReportingUnitCode(vo.get_user().getCompany_id());
        if (!NumberConstant.ONE_STRING.equals(vo.getIsResolve())) {
            throw new CustomException(NotesConstant.DEFUSE_EXCEPTION);
        }
        vo.setCompleteTime(vo.getResolveTime());
        //添加事件
        if (commonService.insert(nameSpace + "insertEventEnd", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.INSERT_EXCEPTION);
        }
        //添加图片
        // log.info("图片集合" + JSONUtil.toJsonStr(vo.getUrlList()));
        List<@Valid ReqEventAttachInsertVo> urlList = vo.getUrlList();
        if (!CollectionUtils.isEmpty(urlList)) {
            for (ReqEventAttachInsertVo sub : urlList) {
                // log.info("图片对象" + JSONUtil.toJsonStr(vo.getUrlList()));
                sub.setId(vo.getId());
//                EventAttachCheckUtils.attachCheck(sub);
                if (commonService.insert(nameSpaceAttach + "insertEventAttach", sub) != NumberConstant.ONE_INT) {
                    throw new CustomException(NotesConstant.INSERT_EXCEPTION);
                }
            }
        }
        List<ReqEventUserInsertVo> userList = vo.getUserList();
        try {
            for (ReqEventUserInsertVo user : userList) {
//                EventUserCheckUtils.eventUserCheck(user);
                if (user.getEventUserType().equals(NumberConstant.FOUR_STRING)) {
                    if (StringUtils.isNotEmpty(user.getEventCardno())) {
                        if (!IdcardUtil.isValidCard(user.getEventCardno())) {
                            throw new CustomException("证件号码错误！");
                        }
                    }
                }
                user.setEventId(vo.getId());
                user.set_user(vo.get_user());
                //添加当事人
                if (commonService.insert(nameSpaceUser + "insertEventUserKey", user) != NumberConstant.ONE_INT) {
                    throw new CustomException(user.getEventUserName() + NotesConstant.INSERT_EXCEPTION);
                }
            }
        } catch (DuplicateKeyException e) {
            throw new CustomException(NotesConstant.USER_CARD_EXCEPTION);
        }
        User user = vo.get_user();
        String jobDuty = commonService.getObject(nameSpaceSys + "getJobDuty", vo);
        if (NumberConstant.ONE_STRING.equals(jobDuty)) {//网格员
            vo.setHierarchy(NumberConstant.ONE_INT);
            vo.setGradeUserId(user.getId());
        } else {//非网格员
            vo.setHierarchy(HierarchyTypeEnums.hierarchyEnumGrad.getHierarchyGrade(user.getCompany_grade()));
        }
        vo.setEventFlowSettingType(NumberConstant.ONE_STRING);
        ReqEventInsertVo flowSettingMap = new ReqEventInsertVo();
        vo.setHierarchy(NumberConstant.ONE_INT);
        //查询网格员审批流程设置当前最新版本
        flowSettingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", vo);
        vo.setOfficeId(user.getCompany_id());
        vo.setFlowId(flowSettingMap.getId());
        vo.setFlowVersion(flowSettingMap.getVersion());
        vo.setStatus(NumberConstant.THREE_STRING);
        vo.setLogType(NumberConstant.TWO_STRING);
        vo.setEventId(vo.getId());
        // 添加网格员提报记录
        if (commonService.insert(nameSpaceFlow + "insertFirstEventFlowLogEnd", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_LOG_EXCEPTION);
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "网格员查询单条详情", desc = "网格员查询单条详情")
    public ReqEventFlowLogInsertVo getEventLogByCreateId(ReqEventFlowLogInsertVo vo) {
        ReqEventFlowLogInsertVo eventMap = commonService.getObject(nameSpace + "getEventLogByCreateId", vo);
        eventMap.setUserList(commonService.findList(nameSpaceUser + "selectUserByEventIdList", eventMap));
        return eventMap;
    }

    @ApiOperation(value = "事件查询单条详情", desc = "事件查询单条详情")
    public ReqEventFlowLogInsertVo getEventLogById(ReqEventFlowLogInsertVo vo) {
        ReqEventFlowLogInsertVo eventMap = commonService.getObject(nameSpace + "getEventLogById", vo);
        if (ObjectUtil.isNull(eventMap)) {
            throw new CustomException("未获取到矛盾信息");
        }
        if (StringUtils.isNotEmpty(eventMap.getRiskName())) {
            eventMap.setRiskNameList(Arrays.asList(eventMap.getRiskName().split(",")));
        }
        eventMap.setUserList(commonService.findList(nameSpaceUser + "selectUserByEventIdList", eventMap));
        return eventMap;
    }

    @ApiOperation(value = "查询本级下级数据", desc = "查询本级下级数据")
    public Page<ReqEventFlowLogInsertVo> findEventPageList(Page<ReqEventFlowLogInsertVo> page) throws ParseException {
        // 获取当前用户是否是横向部门
        Map<String, Object> params = page.getParams();
        Map<String, Object> user = (Map<String, Object>) params.get("_user");
        String fax = commonService.getObject(nameSpace + "getFax", user.get("company_id"));
        if (StringUtils.isNotEmpty(fax)) {// 横向部门
            page.getParams().put("fax", fax);
        }
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpace + "findEarlyWarningList", page);
        this.setTimeout(returnPage);
        return setEarlyWarning(returnPage);
    }

    @ApiOperation(value = "查询本级下级数据", desc = "查询本级下级数据")
    public Page<ReqEventFlowLogInsertVo> findEventAllList(Page<ReqEventFlowLogInsertVo> page) throws ParseException {
        // 获取当前用户是否是横向部门

        Map<String, Object> params = page.getParams();
        Map<String, Object> user = (Map<String, Object>) params.get("_user");
        String fax = commonService.getObject(nameSpace + "getFax", user.get("company_id"));
        if (StringUtils.isNotEmpty(fax)) {// 横向部门
            page.getParams().put("fax", fax);
        }
//        long aa = System.currentTimeMillis();
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpace + "findEventAllList", page);
//        long bb = System.currentTimeMillis();
        List<Map<String, Object>> warningConfigList = commonService.findList(nameSpace + "selectOverdueWarningConfigList",null);
//        System.out.printf("执行时长：%d 毫秒.", (bb - aa));
        Map<String, Object> subMap = new HashMap<>();
        subMap.put("_user",params.get("_user"));
        for (ReqEventFlowLogInsertVo vo : returnPage.getResults()){
            subMap.put("id",vo.getId());
            vo.setStatus(commonService.getObject(nameSpace + "getEventStatus",subMap));
            vo.setLogType(commonService.getObject(nameSpace + "getLogType",subMap));
            vo.setApproveDays(commonService.getObject(nameSpace + "getApproveDays",subMap));
            vo.setReturnVisit(commonService.getObject(nameSpace + "getReturnVisit",subMap));
            List<Map<String, Object>> subList = commonService.findList(nameSpace + "selectEventFlowLogCreateByList",subMap);
            if (StringUtils.toStr(user.get("id")).equals(subList.get(0).get("create_by")) && subList.size() > 1){
                vo.setDeleteType("1");
            } else {
                vo.setDeleteType("0");
            }
            for (Map<String, Object> warningConfig : warningConfigList){
                if (vo.getRiskLevel().equals(StringUtils.toStr(warningConfig.get("risk_type")))){
                    vo.setYellowWarnDays(StringUtils.toInteger(warningConfig.get("yellow_warn_days")));
                    vo.setRedWarnDays(StringUtils.toInteger(warningConfig.get("red_warn_days")));
                }
            }
        }
//        long cc = System.currentTimeMillis();
//        System.out.printf("执行时长：%d 毫秒.", (cc - bb));
        this.setTimeout(returnPage);
        return setEarlyWarning(returnPage);
    }

    @ApiOperation(value = "查询本级下级数据", desc = "查询本级下级数据", nologin = true)
    public ReqEventFlowLogInsertVo getEventAllAsc(ReqEventFlowLogInsertVo vo) {
        ReqEventFlowLogInsertVo eventMap = commonService.getObject(nameSpace + "getEventAllAsc", vo);
//        if (StringUtils.isNotEmpty(eventMap.getRiskName())) {
        if (!"".equals(eventMap.getRiskName())) {
            eventMap.setRiskNameList(Arrays.asList(eventMap.getRiskName().split(",")));
        }
        eventMap.setUserList(commonService.findList(nameSpaceUser + "selectUserByEventIdList", eventMap));
        return eventMap;
    }

    @ApiOperation(value = "查询日志流程", desc = "查询日志流程", nologin = true)
    public List<ReqEventFlowLogInsertVo> findFlowLogProcessList(ReqEventFlowLogInsertVo vo) {
        List<ReqEventFlowLogInsertVo> logList = commonService.findList(nameSpaceFlow + "findFlowLogProcessList", vo);
        List<ReqEventFlowLogInsertVo> mapList = new ArrayList<>();
        List<ReqEventFlowLogInsertVo> returnList = new ArrayList<>();
        List<ReqEventFlowLogInsertVo> processList = new ArrayList<>();
        ReqEventFlowLogInsertVo processMap = new ReqEventFlowLogInsertVo();
        for (ReqEventFlowLogInsertVo sub : logList) {
            //if (sub.getLogType().equals(NumberConstant.THREE_STRING) && StringUtils.isEmpty(sub.getAssignTime())) {
            /*if (sub.getIs_dispatch_office().equals("1")) {
                processList.add(sub); // 横向部门 list
                processMap.setProcessList(processList);
                ReqEventFlowLogInsertVo timeType = new ReqEventFlowLogInsertVo();
                timeType.setCreateTime(sub.getCreateTime());
                timeType.setCreateType(NumberConstant.ELEVEN_INT);
                mapList.add(timeType);
            } else {
                sub.setCreateType("");
                mapList.add(sub);
            }*/
            sub.setCreateType("");
            if (sub.getEventStatus().equals("1") && sub.getStatus().equals("1")) {// 针对已办结事项，但是log中存在待处理的数据，进行排除
                continue;
            }
            mapList.add(sub);
            /*// 如果已办结，显示回访记录按钮
            if (sub.getLogType().equals(NumberConstant.TWO_STRING) && sub.getStatus().equals(NumberConstant.THREE_STRING) && sub.getEventStatus().equals("1")
            && sub.getIs_dispatch_office().equals("0")
            ) {
                sub.setIs_show_hf_history("1");
            }*/
        }
        /*mapList = mapList.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(m -> m.getCreateTime()))), ArrayList::new));*/
        for (ReqEventFlowLogInsertVo sub : mapList) {
            if (StringUtils.isNotEmpty(sub.getCreateType())) {
                processMap.setCreateTime(sub.getCreateTime());
                returnList.add(processMap);
            } else {
                returnList.add(sub);
            }
        }
        returnList.sort(Comparator.comparing(o -> StringUtils.toStr(o.getCreateTime())));
        for (int i = 0; i < returnList.size(); i++) {
            ReqEventFlowLogInsertVo item = returnList.get(i);
            if (i == returnList.size() - 1 && item.getLogType().equals(NumberConstant.TWO_STRING) && item.getStatus().equals(NumberConstant.THREE_STRING) && item.getEventStatus().equals("1")
                    && item.getIs_dispatch_office().equals("0")) {
                item.setIs_show_hf_history("1");// 是否显示回访记录按钮标识
            }
        }
        return returnList;
    }

    @ApiOperation(value = "处置详情（进度详情）", desc = "处置详情（进度详情）")
    public ReqEventFlowLogInsertVo findFlowLogProcessInfo(ReqEventFlowLogInsertVo vo) {
        return commonService.getObject(nameSpaceFlow + "findFlowLogProcessInfo", vo);
    }

    @ApiOperation(value = "预警告警事件查询", desc = "事件查询")
    public Page<ReqEventFlowLogInsertVo> findEarlyWarningList(Page<ReqEventFlowLogInsertVo> page) throws ParseException {
        page.getParams().put("waring", "1");//超期标识
        Page<ReqEventFlowLogInsertVo> eventList = commonService.findPage(nameSpace + "findEarlyWarningList", page);
        setTimeout(eventList);
        return setEarlyWarning(eventList);
    }

    @ApiOperation(value = "预警告警事件", desc = "事件查询")
    public Page<ReqEventFlowLogInsertVo> findEarlyWarningStatusList(Page<ReqEventFlowLogInsertVo> page) throws ParseException {
        page.getParams().put("waring", "1");//超期标识
        Page<ReqEventFlowLogInsertVo> eventList = commonService.findPage(nameSpace + "findEarlyWarningStatusList", page);
        setTimeout(eventList);
        return setEarlyWarning(eventList);
    }

    //设置超期预警
    private Page<ReqEventFlowLogInsertVo> setEarlyWarning(Page<ReqEventFlowLogInsertVo> eventList) {
        //设置超时提醒
        for (ReqEventFlowLogInsertVo reqEarlyWarningVo : eventList.getResults()) {
            if ("1".equals(reqEarlyWarningVo.getEventStatus())) {
                //已办结绿色
                reqEarlyWarningVo.setIsEarlyWarning("1");
            } else {
                if (StringUtils.isEmpty(reqEarlyWarningVo.getApproveDays())){
                    reqEarlyWarningVo.setApproveDays(0);
                }
                if (StringUtils.isEmpty(reqEarlyWarningVo.getRedWarnDays())){
                    reqEarlyWarningVo.setRedWarnDays(0);
                }
                //红灯
                if (reqEarlyWarningVo.getDay() > (reqEarlyWarningVo.getApproveDays() + reqEarlyWarningVo.getRedWarnDays())) {
                    reqEarlyWarningVo.setIsEarlyWarning("4");
                } else if (reqEarlyWarningVo.getDay() > (reqEarlyWarningVo.getApproveDays() + reqEarlyWarningVo.getYellowWarnDays())) {
                    //黄灯
                    reqEarlyWarningVo.setIsEarlyWarning("3");
                } else {
                    //绿灯
                    reqEarlyWarningVo.setIsEarlyWarning("1");
                }
            }
        }
        return eventList;
    }


    @ApiOperation(value = "横传查询同级机构", desc = "横传查询同级机构")
    public List<ReqEventFlowLogInsertVo> selectOfficeFaxList(ReqEventFlowLogInsertVo vo) {
        ReqSysOfficeVo faxMap = commonService.getObject(nameSpaceSys + "getFaxById", vo);
        Integer fax = StringUtils.toInteger(faxMap.getNum());
        if (fax == NumberConstant.ONE_INT) {// 横向部门
            vo.setId(faxMap.getCreateBy());
            return commonService.findList(nameSpaceSys + "selectCreateByIdList", vo);
        }
        //return commonService.findList(nameSpaceSys + "selectParentByIdList", vo);
        return commonService.findList(nameSpaceSys + "selectParentByIdListNew", vo);
    }

    @ApiOperation(value = "添加超期预警处置", desc = "添加超期预警处置")
    public String insertEventOpinion(@Valid ReqEventOpinionInsertVo vo) {
        if (commonService.update(nameSpace + "updateSuperviseHandle", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SYS_EXCEPTION);
        }
        if (commonService.insert(nameSpaceOpinion + "insertEventOpinion", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.INSERT_EXCEPTION);
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "修改超期预警处置", desc = "修改超期预警处置")
    public String updateEventOpinion(@Valid ReqEventOpinionUpdateVo vo) {
        if (commonService.update(nameSpaceOpinion + "updateEventOpinion", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.UPDATE_EXCEPTION);
        }
        return NotesConstant.SAVE_SUCCESS;
    }

    @ApiOperation(value = "查询超期预警处置", desc = "查询超期预警处置")
    public List<ResEventOpinionVo> selectOpinionList(@Valid ReqEventOpinionFindVo vo) {
        List<ResEventOpinionVo> eventOpinion = commonService.findList(nameSpaceOpinion + "selectOpinionList", vo);
        return eventOpinion;
    }

    @ApiOperation(value = "风险预警 重点领域详情列表", desc = "风险预警 重点领域详情列表")
    public Page<ReqEventFlowLogInsertVo> findEventFocusAreasList(Page<ReqEventFlowLogInsertVo> page) {
        return commonService.findPage(nameSpace + "findEventFocusAreasList", page);
    }

    @ApiOperation(value = "查询本级下级矛盾超期数据", desc = "查询本级下级矛盾超期数据")
    public Page<ReqEventFlowLogInsertVo> findOverdueEventPageList(Page<ReqEventFlowLogInsertVo> page) {
        ReqEventFlowLogInsertVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), ReqEventFlowLogInsertVo.class);
        pageMap.setSysAreaId(commonService.getObject(nameSpaceSys + "getAreaById", pageMap));
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        page.setParams(pMap);
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpace + "findOverdueEventPageList", page);
        List<ReqEventFlowLogInsertVo> eventIdList = returnPage.getResults();
        this.setWarningLight(eventIdList);
        return returnPage;
    }


    @ApiOperation(value = "查询本级下级矛盾超期历史数据", desc = "查询本级下级矛盾超期历史数据")
    public Page<ReqEventFlowLogInsertVo> findOverdueEventHistoryPageList(Page<ReqEventFlowLogInsertVo> page) {
        ReqEventFlowLogInsertVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), ReqEventFlowLogInsertVo.class);
        pageMap.setSysAreaId(commonService.getObject(nameSpaceSys + "getAreaById", pageMap));
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        page.setParams(pMap);
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpace + "findOverdueEventHistoryPageList", page);
        List<ReqEventFlowLogInsertVo> eventIdList = returnPage.getResults();
        this.setWarningLight(eventIdList);
        return returnPage;
    }

    @ApiOperation(value = "查询涉众预警数据", desc = "查询涉众预警数据")
    public Page<ReqEventFlowLogInsertVo> findInvolveEveryonePageList(Page<ReqEventFlowLogInsertVo> page) {
        ReqEventFlowLogInsertVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), ReqEventFlowLogInsertVo.class);
        pageMap.setSysAreaId(commonService.getObject(nameSpaceSys + "getAreaById", pageMap));
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        page.setParams(pMap);
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpace + "findInvolveEveryonePageList", page);
        List<ReqEventFlowLogInsertVo> eventIdList = returnPage.getResults();
        this.setWarningLight(eventIdList);
        return returnPage;
    }

    @ApiOperation(value = "查询涉众预警数据历史", desc = "查询涉众预警数据历史")
    public Page<ReqEventFlowLogInsertVo> findInvolveEveryoneHistoryPageList(Page<ReqEventFlowLogInsertVo> page) {
        ReqEventFlowLogInsertVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), ReqEventFlowLogInsertVo.class);
        pageMap.setSysAreaId(commonService.getObject(nameSpaceSys + "getAreaById", pageMap));
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        page.setParams(pMap);
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpace + "findInvolveEveryoneHistoryPageList", page);
        List<ReqEventFlowLogInsertVo> eventIdList = returnPage.getResults();
        this.setWarningLight(eventIdList);
        return returnPage;
    }

    @ApiOperation(value = "查询风险因子预警列表数据", desc = "查询风险因子预警列表数据")
    public Page<ReqEventFlowLogInsertVo> findEventRiskFactorPageList(Page<ReqEventFlowLogInsertVo> page) {
        ReqEventFlowLogInsertVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), ReqEventFlowLogInsertVo.class);
        pageMap.setSysAreaId(commonService.getObject(nameSpaceSys + "getAreaById", pageMap));
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        page.setParams(pMap);
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpaceEventRiskFactor + "findEventRiskFactorPageList", page);
        List<ReqEventFlowLogInsertVo> eventIdList = returnPage.getResults();
        this.setWarningLight(eventIdList);
        return returnPage;
    }

    @ApiOperation(value = "查询风险因子预警列表数据历史", desc = "查询风险因子预警列表数据历史")
    public Page<ReqEventFlowLogInsertVo> findEventRiskFactorHistoryPageList(Page<ReqEventFlowLogInsertVo> page) {
        ReqEventFlowLogInsertVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), ReqEventFlowLogInsertVo.class);
        pageMap.setSysAreaId(commonService.getObject(nameSpaceSys + "getAreaById", pageMap));
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        page.setParams(pMap);
        Page<ReqEventFlowLogInsertVo> returnPage = commonService.findPage(nameSpaceEventRiskFactor + "findEventRiskFactorHistoryPageList", page);
        List<ReqEventFlowLogInsertVo> eventIdList = returnPage.getResults();
        this.setWarningLight(eventIdList);
        return returnPage;
    }

    private void setWarningLight(List<ReqEventFlowLogInsertVo> eventIdList) {
        for (ReqEventFlowLogInsertVo event : eventIdList) {
            if (StringUtils.isNotEmpty(event.getEventType()) && StringUtils.isNotEmpty(event.getRiskLevel()) && StringUtils.isNotEmpty(event.getStatus()) && StringUtils.isNotEmpty(event.getCompleteTime())) {
                String completeTime = event.getCompleteTime();
                FollowUpRecords followUpRecords = new FollowUpRecords();
                followUpRecords.setEventCode(event.getEventCode());
                List<FollowUpRecords> list = selectFollowUpRecordsList(followUpRecords);
                if (list.isEmpty()) {
                    event.setWarningLight(true);
                } else {
                    if (event.getRiskLevel().equals("一般矛盾纠纷")) {
                        for (FollowUpRecords upRecords : list) {
                            long daysBetweenLong = daysBetween(completeTime, upRecords.getCreateTime());
                            if (daysBetweenLong <= 7) {
                                break;
                            } else {
                                event.setWarningLight(true);
                            }
                        }
                    } else if (event.getRiskLevel().equals("复杂矛盾纠纷")) {
                        boolean flag = false;
                        boolean flag2 = false;
                        for (FollowUpRecords upRecords : list) {
                            long daysBetweenLong = daysBetween(completeTime, upRecords.getCreateTime());
                            if (daysBetweenLong <= 7) {
                                flag = true;
                            } else if (daysBetweenLong > 7 && daysBetweenLong <= 30) {
                                flag2 = true;
                            }
                        }
                        if (!flag2 || !flag) {
                            event.setWarningLight(true);
                        }
                    } else if (event.getRiskLevel().equals("重大矛盾纠纷")) {
                        boolean flag = false;
                        boolean flag2 = false;
                        boolean flag3 = false;
                        for (FollowUpRecords upRecords : list) {
                            long daysBetweenLong = daysBetween(completeTime, upRecords.getCreateTime());
                            if (daysBetweenLong <= 7) {
                                flag = true;
                            } else if (daysBetweenLong > 7 && daysBetweenLong <= 30) {
                                flag2 = true;
                            } else if (daysBetweenLong > 30 && daysBetweenLong <= 90) {
                                flag3 = true;
                            }
                        }
                        if (!flag2 || !flag || !flag3) {
                            event.setWarningLight(true);
                        }
                    }
                }
            }
            event.setUserList(commonService.findList(nameSpaceUser + "selectUserByEventIdList", event));
        }
    }

    /**
     * 生成事件编号
     *
     * @param vo
     * @return
     */
    private String eventCode(ReqEventInsertVo vo) {
//        String code = commonService.getObject(nameSpaceSys + "getAreaCode", map);
        String cityCode = vo.get_user().getCompany_sys_area();
//                MapUtil.getStr((Map<String, Object>) map.get("_user"), "company_sys_area");
        String type = "";
        switch (vo.getEventType()) {
            case NumberConstant.ONE_STRING: //上报
                type = "SJ";
                break;
            case NumberConstant.TWO_STRING: //矛盾
                type = "MD";
                break;
            case NumberConstant.THREE_STRING: //舆情
                type = "YQ";
                break;
            default:
                throw new CustomException(NotesConstant.LOG_EXCEPTION);
        }
        String today = DateUtil.today();
        today = today.replace("-", "");
//        Integer num = 1;
        Long incr = JedisUtils.incr("eventCode_" + type + today);
        JedisUtils.expired("eventCode_" + type + today, 60 * 60 * 24);//设置键过期/秒
        /*if (!JedisSentinelUtils.exists("eventCode_" + type + today)) {
            JedisSentinelUtils.set("eventCode_" + type + today, StringUtils.toStr(num), 60000000);
            return cityCode + type + today + String.format("%05d", num);
        } else {
            UnifyLogger.parent("rides取值为===========：" + JedisSentinelUtils.getObject("eventCode_" + type + today), UnifyLogger.Level.INFO);
            UnifyLogger.parent("主键为：eventCode_" + type + today + ",进入自增,key存活时间剩余:" + JedisSentinelUtils.ttl("eventCode_" + type + today), UnifyLogger.Level.INFO);
            UnifyLogger.parent(String.valueOf(JedisSentinelUtils.exists("eventCode_" + type + today)), UnifyLogger.Level.INFO);
            Integer jedis = StringUtils.toInteger(JedisSentinelUtils.get("eventCode_" + type + today)) + 1;
            JedisSentinelUtils.set("eventCode_" + type + today, StringUtils.toStr(jedis), 60000000);
            return cityCode + type + today + String.format("%05d", jedis);
        }*/
        return cityCode + type + today + String.format("%05d", incr);
    }

    /**
     * 自动获取是区街道社区编码
     *
     * @param map
     * @return
     */
    private Map<String, Object> getCityCodes(Map<String, Object> map) {
        Map<String, Object> cityMap = new HashMap<>();
        switch (MapUtil.getStr((Map<String, Object>) map.get("_user"), "company_grade")) {
            case NumberConstant.THREE_STRING: //市级编码
                cityMap.put("city_id", MapUtil.getStr((Map<String, Object>) map.get("_user"), "company_sys_area"));
                break;
            case NumberConstant.FOUR_STRING: //区级及以上编码
                cityMap = commonService.getObject(nameSpaceSys + "selectAreaCode", map);
                break;
            case NumberConstant.FIVE_STRING: //街道及以上编码
                cityMap = commonService.getObject(nameSpaceSys + "selectStreetCode", map);
            case NumberConstant.SIX_STRING: //社区及以上编码
                cityMap = commonService.getObject(nameSpaceSys + "selectCommunityCode", map);
                break;
            default:
                throw new CustomException(NotesConstant.CODE_EXCEPTION);
        }
        return cityMap;
    }

    /**
     * 上报 下派
     *
     * @param vo
     * @throws InterruptedException
     */
    private void insertLogTypeOne(ReqEventInsertVo vo) throws InterruptedException {
        ReqEventInsertVo flowSetting = new ReqEventInsertVo();
        flowSetting = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", vo);
        //查询网格员审批流程设置当前最新版本
//        flowSettingMap = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", vo);
        vo.setOfficeId(vo.get_user().getCompany_id());
        vo.setFlowId(flowSetting.getId());
        vo.setFlowVersion(flowSetting.getVersion());
        vo.setStatus(NumberConstant.THREE_STRING);
        vo.setEventId(vo.getId());
//        map.put("office_id", MapUtil.getStr((Map<String, Object>) map.get("_user"), "company_id"));
//        map.put("flow_id", flowSettingMap.get("id"));
//        map.put("flow_version", flowSettingMap.get("version"));
//        map.put("status", NumberConstant.THREE_STRING);
//        map.put("event_id", map.get("id"));
        if (vo.getGradeUserId().equals(NumberConstant.ONE_STRING)) {
//            vo.remove("grade_user_id");
            vo.setGradeUserId(null);
        }
        // 添加第一条提报记录
        if (commonService.insert(nameSpaceFlow + "insertFirstEventFlowLog", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_LOG_EXCEPTION);
        }
        //根据最新版本查询上级流程
        // fixme hierarchy =  7 ?  没有7啊，下面查询就回空指针。。。
        if (vo.getLogType().equals(NumberConstant.SIX_STRING)) {// 下派
            vo.setHierarchy(vo.getHierarchy() - NumberConstant.ONE_INT);
        } else {
            if (vo.getHierarchy() != 6) {
                vo.setHierarchy(vo.getHierarchy() + NumberConstant.ONE_INT);
            }
        }
        vo.setVersion(flowSetting.getVersion());
//        map.put("version", flowSettingMap.get("version"));
        flowSetting = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", vo);
        vo.setStatus(NumberConstant.ONE_STRING);
        vo.setFlowId(flowSetting.getId());
//        map.put("status", NumberConstant.ONE_STRING);
//        map.put("flow_id", flowSettingMap.get("id"));
        if (vo.getGradeD().equals(NumberConstant.ONE_STRING)) {// 非网格员
            if (vo.getEventFlowSettingType().equals(NumberConstant.ONE_STRING)) {
                //vo.setOfficeId(vo.get_user().getParent_id());

                // 判断上报用户是否是横向部门，如果是横向部门，则上报到同级别综治中心
                String fax = commonService.getObject(nameSpace + "getFax", vo.get_user().getCompany_id());
                if (StringUtils.isNotEmpty(fax)) {// 是横向部门
                    // 获取该横向部门所属的综治中心
                    String office_id = commonService.getObject(nameSpace + "getOfficeId", vo.get_user().getCompany_id());
                    vo.setOfficeId(office_id);
                    vo.setHierarchy(vo.getHierarchy() - 1);
                } else {
                    vo.setOfficeId(vo.get_user().getParent_id());
                }

//                map.put("office_id", MapUtil.getStr((Map<String, Object>) map.get("_user"), "parent_id"));
            } else {// 下派
                vo.setOfficeId(vo.getCrossOfficeId());
//                map.put("office_id", map.get("crossOfficeId"));
            }
        } else {
            vo.setOfficeId(vo.get_user().getCompany_id());
//            map.put("office_id", MapUtil.getStr((Map<String, Object>) map.get("_user"), "company_id"));
        }
        //延迟一秒执行 拉开创建时间
        TimeUnit.SECONDS.sleep(NumberConstant.ONE_INT);
        if (vo.getGradeD().equals(NumberConstant.ZERO_STRING)) {
            vo.setGradeUserId(null);
        }
        //添加社区待处理记录
        if (commonService.insert(nameSpaceFlow + "insertEventFlowLog", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_LOG_EXCEPTION);
        }
    }

    /**
     * 横穿
     *
     * @param vo
     * @throws InterruptedException
     */
    private void insertLogTypeCross(ReqEventInsertVo vo) throws InterruptedException {
        ReqEventInsertVo flowSetting = new ReqEventInsertVo();
        vo.setOfficeId(vo.get_user().getCompany_id());
        vo.setStatus(NumberConstant.THREE_STRING);
        vo.setEventId(vo.getId());
        // 添加第一条提报记录
        if (commonService.insert(nameSpaceFlow + "insertFirstEventFlowLog", vo) != NumberConstant.ONE_INT) {
            throw new CustomException(NotesConstant.SAVE_LOG_EXCEPTION);
        }

        //根据最新版本查询上级流程
        vo.setHierarchy(vo.getHierarchy());
        vo.setVersion(flowSetting.getVersion());
        flowSetting = commonService.getObject(nameSpaceFlow + "getEventFlowSetting", vo);
        vo.setStatus(NumberConstant.ONE_STRING);
        vo.setFlowId(flowSetting.getId());
        List<String> officeList = vo.getOfficeList();
        for (String office : officeList) {
            vo.setOfficeId(office);
            //延迟一秒执行 拉开创建时间
            TimeUnit.SECONDS.sleep(NumberConstant.ONE_INT);
            //添加社区待处理记录
            vo.setIs_dispatch_office("1");// 分派、横传的处置部门标识
            if (commonService.insert(nameSpaceFlow + "insertEventFlowLog", vo) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_LOG_EXCEPTION);
            }
        }
    }

    //    private EventCategoryAndEventTypeDto getEventCategoryAndEventType(){
//        List<HashMap<String,String>> list = commonService.findList(dictNameSpace + "getEventCategoryAndEventType", null);
//        HashMap<String, String> eventCategoryMap = new HashMap<>();
//        HashMap<String, String> eventTypeMap = new HashMap<>();
//        list.forEach(v->{
//            eventCategoryMap.put(v.get("eventCategoryId"),v.get("eventCategoryName"));
//            eventTypeMap.put(v.get("eventTypeId"),v.get("eventTypeName"));
//        });
//        EventCategoryAndEventTypeDto eventCategoryAndEventTypeDto = new EventCategoryAndEventTypeDto();
//        eventCategoryAndEventTypeDto.setEventCategoryMap(eventCategoryMap);
//        eventCategoryAndEventTypeDto.setEventTypeMap(eventTypeMap);
//        return eventCategoryAndEventTypeDto;
//    }
    @ApiOperation(value = "预警-重点领域", desc = "预警-重点领域", nologin = true)
    public Page<FousAreaVo> fousAreaWarringPageList(Page<FousAreaVo> page) {
////        log.info("当前的月份是----------------—————————————————————————————————————————————————》"+JSON.toJSONString(page.getParams()));
        FousAreaVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), FousAreaVo.class);
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotEmpty(pageMap.getOccurrenceEndDate())) {
            pMap.put("occurrenceEndDate", LocalDateTime.parse(pageMap.getOccurrenceEndDate() + " 23:59:59", dateTimeFormatter));
        }
        if (StringUtils.isNotEmpty(pageMap.getOccurrenceStartDate())) {
            pMap.put("occurrenceStartDate", LocalDateTime.parse(pageMap.getOccurrenceStartDate() + " 00:00:00", dateTimeFormatter));
        }

        page.setParams(pMap);

//        String month = String.valueOf(pMap.get("month"));
//        log.info("当前的月份是----------------——————————————————————————————————————————————————》"+month);
        Page<FousAreaVo> resultPage = commonService.findPage(nameSpace + "getAreaFousWarringList", page);
        if (resultPage.getResults() == null || resultPage.getResults().isEmpty()) {
            return new Page<FousAreaVo>();
        }
//        EventCategoryAndEventTypeDto eventCategoryAndEventType = getEventCategoryAndEventType();
//        HashMap<String, String> eventCategoryMap = eventCategoryAndEventType.getEventCategoryMap();
//        HashMap<String, String> eventTypeMap = eventCategoryAndEventType.getEventTypeMap();
        resultPage.getResults().forEach(v -> {
            if (StringUtil.isEmpty(v.getStatus())) {
                switch (String.valueOf(v.getStatus())) {
                    case "1":
                        v.setStatusName("已办结");
                        break;
                    case "2":
                        v.setStatusName("处理中");
                        break;
                    default:
                        v.setStatusName("");
                        break;
                }
            }
        });
        return resultPage;
    }

    @ApiOperation(value = "预警-重点领域历史", desc = "预警-重点领域历史", nologin = true)
    public Page<FousAreaVo> fousAreaWarringPageHistoryList(Page<FousAreaVo> page) {
////        log.info("当前的月份是----------------—————————————————————————————————————————————————》"+JSON.toJSONString(page.getParams()));
        FousAreaVo pageMap = JSON.parseObject(JSON.toJSONString(page.getParams()), FousAreaVo.class);
        Map<String, Object> pMap = JSON.parseObject(JSON.toJSONString(pageMap), Map.class);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotEmpty(pageMap.getOccurrenceEndDate())) {
            pMap.put("occurrenceEndDate", LocalDateTime.parse(pageMap.getOccurrenceEndDate() + " 23:59:59", dateTimeFormatter));
        }
        if (StringUtils.isNotEmpty(pageMap.getOccurrenceStartDate())) {
            pMap.put("occurrenceStartDate", LocalDateTime.parse(pageMap.getOccurrenceStartDate() + " 00:00:00", dateTimeFormatter));
        }

        page.setParams(pMap);

//        String month = String.valueOf(pMap.get("month"));
//        log.info("当前的月份是----------------——————————————————————————————————————————————————》"+month);
        Page<FousAreaVo> resultPage = commonService.findPage(nameSpace + "getAreaFousWarringListhistory", page);
        if (resultPage.getResults() == null || resultPage.getResults().isEmpty()) {
            return new Page<FousAreaVo>();
        }
//        EventCategoryAndEventTypeDto eventCategoryAndEventType = getEventCategoryAndEventType();
//        HashMap<String, String> eventCategoryMap = eventCategoryAndEventType.getEventCategoryMap();
//        HashMap<String, String> eventTypeMap = eventCategoryAndEventType.getEventTypeMap();
        resultPage.getResults().forEach(v -> {
            if (StringUtil.isEmpty(v.getStatus())) {
                switch (String.valueOf(v.getStatus())) {
                    case "1":
                        v.setStatusName("已办结");
                        break;
                    case "2":
                        v.setStatusName("处理中");
                        break;
                    default:
                        v.setStatusName("");
                        break;
                }
            }
        });
        return resultPage;
    }

    @ApiOperation(value = "获取当前登录用户是否是横向部门", desc = "获取当前登录用户是否是横向部门")
    public Boolean getIsHXOffice(Map<String, Object> map) {
        Map<String, Object> user = (Map<String, Object>) map.get("_user");
        String fax = commonService.getObject(nameSpace + "getFax", user.get("company_id"));
        if (StringUtils.isNotEmpty(fax)) {
            return true;
        } else {
            return false;
        }
    }

    @ApiOperation(value = "删除事件", desc = "删除事件")
    public String deleteEvent(Map<String, Object> map) {
        // 根据事件id查询事件
        ReqEventInsertVo event = commonService.getObject(nameSpace + "getEventById", map);
        Date currentOccurrenceDate = DateUtil.parse(event.getOccurrenceTime(), "yyyy-MM-dd");
        event.setOccurrenceTime(DateUtil.format(currentOccurrenceDate, "yyyy-MM-dd"));
        List<ReqEventInsertVo> list = commonService.findList("com.scpyun.platform.standard.jilinsscgsdp.event.find30DayEvent", event);
        // log.info("相同发生地 存在事件：{}", JSONUtil.toJsonStr(list));
        if (list != null && list.size() < 5) {
            // log.info("相同发生地 存在事件小于5次,解除 参数：{}", JSONUtil.toJsonStr(event));
            // 删除重点事 按照地区和类型
            /*if (commonService.update(nameSpace + "delEventTrigger", event) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.UPDATE_EXCEPTION);
            }*/
            commonService.update(nameSpace + "delEventTrigger", event);
        }

        //根据事件id删除
        commonService.delete(nameSpace + "deleteEventFLowLogCountContradiction", map);
        commonService.delete(nameSpace + "deleteTriggerEvent", map);
        commonService.delete(nameSpace + "deleteEventTrigger", map);
        commonService.delete(nameSpace + "deleteEventRiskFactor", map);
        commonService.delete(nameSpace + "deleteEvent", map);
        commonService.delete(nameSpace + "deleteEventFlowLog", map);
        commonService.delete(nameSpace + "deleteEventUser", map);
        commonService.delete(nameSpace + "deleteEventCountContradiction", map);
        commonService.delete(nameSpace + "deleteSupplementInfo", map);
        return NotesConstant.SAVE_SUCCESS;
    }


    @ApiOperation(value = "矛盾纠纷统计列表", desc = "矛盾纠纷统计列表")
    public Page<EventReportUnitStatisticVo> getReportUnitStatisticCountList(Page<EventReportUnitStatisticVo> page) {
        Object o = page.getParams().get("areaId");
        if (StringUtils.isEmpty(o)) {
            Map<String, Object> user = (Map<String, Object>) page.getParams().get("_user");
            page.getParams().put("areaId", user.get("company_id"));
        }
        Page<EventReportUnitStatisticVo> returnPage = commonService.findPage(nameSpace + "getReportUnitStatisticCountList", page);
        // log.info("查询结果={}", JSONUtil.toJsonStr(returnPage));
        boolean isFirst = true;
        for (EventReportUnitStatisticVo v : returnPage.getResults()) {
            v.setCreateStartTime((String) page.getParams().get("createStartTime"));
            v.setCreateEndTime((String) page.getParams().get("createEndTime"));
            if (isFirst && (Integer) page.getParams().get("pageNo") == 1) {
                // 查询 横向部门的数量
                v.setHxbmCount(commonService.getObject(nameSpace + "getHxbmReportCount", v));
                isFirst = false;
            } else {
                // 非本级处理
                // 查询 本级以下所有子孙的数量
                v.setZzzxCount(((Integer) commonService.getObject(nameSpace + "getZzzxChildReportCount", v)) + v.getZzzxCount());
                v.setHxbmCount((Integer) commonService.getObject(nameSpace + "getHxbmChildReportCount", v) + (Integer) commonService.getObject(nameSpace + "getHxbmReportCount", v));
            }
        }

        return returnPage;
    }


    @ApiOperation(value = "矛盾纠纷统计总数", desc = "矛盾纠纷统计总数")
    public Map<String, Object> getReportUnitStatisticTotalCount(EventReportUnitStatisticVo param) {
        if (StringUtils.isEmpty(param.getAreaId())) {
            param.setAreaId(param.get_user().getCompany_id());
        }
        List<EventReportUnitStatisticVo> list = commonService.findList(nameSpace + "getReportUnitStatisticTotalCountList", param);
        boolean isFirst = true;
        for (EventReportUnitStatisticVo v : list) {
            v.setCreateStartTime(param.getCreateStartTime());
            v.setCreateEndTime(param.getCreateEndTime());
            if (isFirst) {
                // 查询 横向部门的数量
                v.setHxbmCount(commonService.getObject(nameSpace + "getHxbmReportCount", v));
                isFirst = false;
            } else {
                // 非本级处理
                // 查询 本级以下所有子孙的数量
                v.setZzzxCount(((Integer) commonService.getObject(nameSpace + "getZzzxChildReportCount", v)) + v.getZzzxCount());
                v.setHxbmCount((Integer) commonService.getObject(nameSpace + "getHxbmChildReportCount", v) + (Integer) commonService.getObject(nameSpace + "getHxbmReportCount", v));
            }

        }
        int zzzxTotalCount = list.stream().mapToInt(EventReportUnitStatisticVo::getZzzxCount).sum();
        int hxTotalCount = list.stream().mapToInt(EventReportUnitStatisticVo::getHxbmCount).sum();

        return new HashMap<String, Object>() {{
            put("zzzxTotalCount", zzzxTotalCount);
            put("hxbmTotalCount", hxTotalCount);
        }};
    }

    @ApiOperation(value = "重复录入统计", desc = "重复录入统计", nologin = true)
    public Page getDisCountByIdCardPage(Page<Map> page) {
        String level = String.valueOf(page.getParams().get("level"));
        switch (level) {
            case "2":
                return commonService.findPage(nameSpaceUser + "getDisCountByIdCardPage", page);
            case "3":
                page.getParams().put("cityId", page.getParams().get("code"));
                return commonService.findPage(nameSpaceUser + "getDisCountByIdCardPage", page);
            case "4":
                page.getParams().put("areaId", page.getParams().get("code"));
                return commonService.findPage(nameSpaceUser + "getDisCountByIdCardPage", page);
            case "5":
                page.getParams().put("streetId", page.getParams().get("code"));
                return commonService.findPage(nameSpaceUser + "getDisCountByIdCardPage", page);
            case "6":
                page.getParams().put("communityId", page.getParams().get("code"));
                return commonService.findPage(nameSpaceUser + "getDisCountByIdCardPage", page);
            default:
                throw new IllegalArgumentException("参数异常" + level);

        }
    }

    @ApiOperation(value = "重复录入统计列表", desc = "重复录入统计列表", nologin = true)
    public List<HashMap<String, Object>> getDisCountByIdCardlist(HashMap<String, String> map) {
        String level = String.valueOf(map.get("level"));
        List<HashMap<String, Object>> result;
        switch (level) {
            case "2":
                result = commonService.findList(nameSpaceUser + "getDisCountByIdCardList", map);
                break;
            case "3":
                map.put("cityId", map.get("code"));
                result = commonService.findList(nameSpaceUser + "getDisCountByIdCardList", map);
                break;
            case "4":
                map.put("areaId", map.get("code"));
                result = commonService.findList(nameSpaceUser + "getDisCountByIdCardList", map);
                break;
            case "5":
                map.put("streetId", map.get("code"));
                result = commonService.findList(nameSpaceUser + "getDisCountByIdCardList", map);
                break;
            case "6":
                map.put("communityId", map.get("code"));
                result = commonService.findList(nameSpaceUser + "getDisCountByIdCardList", map);
                break;
            default:
                throw new IllegalArgumentException("参数异常" + level);
        }

        if (CollectionUtils.isNotEmpty(result)) {
            result.forEach(item -> {
                item.put("keyPersonHighlyConcernedRel", commonService.findList(murderManagementNameSpace + "findKeyPersonHighlyConcernedRelListByKeyPersonIdStr", item.get("id")));
            });
        }
        return result;

    }
}