package com.usky.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.Arith;
import com.usky.common.core.util.DateUtils;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.*;
import com.usky.fire.mapper.DemFireStatisticsMapper;
import com.usky.fire.service.DemFileLabelService;
import com.usky.fire.service.DemFireLabelAttributeService;
import com.usky.fire.service.DemFireStatisticsAttachService;
import com.usky.fire.service.DemFireStatisticsService;
import com.usky.fire.service.po.FireStatisticsPO;
import com.usky.fire.service.util.OnlineMethod;
import com.usky.fire.service.vo.*;
import io.lettuce.core.dynamic.support.ReflectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 火灾统计表 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-09-13
 */
@Service
public class DemFireStatisticsServiceImpl extends AbstractCrudService<DemFireStatisticsMapper, DemFireStatistics> implements DemFireStatisticsService {

    @Autowired
    private DemFireStatisticsAttachService demFireStatisticsAttachService;

    @Autowired
    private DemFileLabelService demFileLabelService;

    @Autowired
    private DemFireLabelAttributeService demFireLabelAttributeService;

    @Override
    public CommonPage<Object> fireAccidentStatistic(String fireNumber, Integer labelId, Integer classifyId, Integer id, Integer pageNum, Integer pageSize) {
        Integer type1 = 0;
        Integer type2 = 0;
        Integer type3 = 0;
        Integer type4 = 0;
        Integer type5 = 0;
        if (labelId != null && labelId != 0) {
            LambdaQueryWrapper<DemFireLabelAttribute> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.eq(DemFireLabelAttribute::getLabelId, labelId);
            List<DemFireLabelAttribute> list1 = demFireLabelAttributeService.list(queryWrapper1);
            if (list1.size() > 0) {
                switch (list1.get(0).getAttribute()) {
                    case "typeName1":
                        type1 = classifyId;
                        break;
                    case "typeName2":
                        type2 = classifyId;
                        break;
                    case "typeName3":
                        type3 = classifyId;
                        break;
                    case "typeName4":
                        type4 = classifyId;
                        break;
                    case "typeName5":
                        type5 = classifyId;
                        break;
                }
            }
        }
        IPage<DemFireStatistics> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(DemFireStatistics::getBurnedArea, DemFireStatistics::getDirectPropertyLoss, DemFireStatistics::getVictimNumber,
                DemFireStatistics::getInjuredNumber, DemFireStatistics::getDeathToll, DemFireStatistics::getFileCase, DemFireStatistics::getFireGrade,
                DemFireStatistics::getSubordinateDetachment, DemFireStatistics::getAdministrativeDivision, DemFireStatistics::getFireNumber,
                DemFireStatistics::getFireAddress, DemFireStatistics::getFireTime, DemFireStatistics::getId, DemFireStatistics::getTypeId1,
                DemFireStatistics::getTypeId2, DemFireStatistics::getTypeId3, DemFireStatistics::getTypeId4, DemFireStatistics::getTypeId5)
                .like(StringUtils.isNotBlank(fireNumber), DemFireStatistics::getFireNumber, fireNumber)
                .eq(type1 != null && type1 != 0, DemFireStatistics::getTypeId1, type1)
                .eq(type2 != null && type2 != 0, DemFireStatistics::getTypeId2, type2)
                .eq(type3 != null && type3 != 0, DemFireStatistics::getTypeId3, type3)
                .eq(type4 != null && type4 != 0, DemFireStatistics::getTypeId4, type4)
                .eq(type5 != null && type5 != 0, DemFireStatistics::getTypeId5, type5)
                .eq(id != null & id != 0, DemFireStatistics::getId, id)
                .orderByDesc(DemFireStatistics::getId);
        page = this.page(page, queryWrapper);
        List<Object> list = new ArrayList<>();
        if (page.getTotal() > 0) {
            List<String> fireNumberList = new ArrayList<>();
            List<Integer> labelIdList = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                fireNumberList.add(page.getRecords().get(i).getFireNumber());
            }
            List<DemFireStatisticsAttach> demFireStatisticsAttaches = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(fireNumberList)) {
                demFireStatisticsAttaches = demFireStatisticsAttachService.fireAccidentStatistic(fireNumberList);
            }

            List<DemFileLabel> demFileLabels = demFileLabelService.demFileLabelList(null, null, null);
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", page.getRecords().get(i).getId());
                map.put("burnedArea", page.getRecords().get(i).getBurnedArea());
                map.put("directPropertyLoss", page.getRecords().get(i).getDirectPropertyLoss());
                map.put("victimNumber", page.getRecords().get(i).getVictimNumber());
                map.put("injuredNumber", page.getRecords().get(i).getInjuredNumber());
                map.put("deathToll", page.getRecords().get(i).getDeathToll());
                map.put("fileCase", page.getRecords().get(i).getFileCase());
                map.put("fireGrade", page.getRecords().get(i).getFireGrade());
                map.put("subordinateDetachment", page.getRecords().get(i).getSubordinateDetachment());
                map.put("administrativeDivision", page.getRecords().get(i).getAdministrativeDivision());
                map.put("fireNumber", page.getRecords().get(i).getFireNumber());
                map.put("fireAddress", page.getRecords().get(i).getFireAddress());
                map.put("fireTime", page.getRecords().get(i).getFireTime());
                map.put("typeId1", page.getRecords().get(i).getTypeId1());
                map.put("typeId2", page.getRecords().get(i).getTypeId2());
                map.put("typeId3", page.getRecords().get(i).getTypeId3());
                map.put("typeId4", page.getRecords().get(i).getTypeId4());
                map.put("typeId5", page.getRecords().get(i).getTypeId5());
                map.put("typeName1", null);
                map.put("typeName2", null);
                map.put("typeName3", null);
                map.put("typeName4", null);
                map.put("typeName5", null);
                map.put("zid", null);
                map.put("fireCauseType1", null);
                map.put("fireSiteType1", null);
                map.put("labelName", null);
                for (int j = 0; j < demFireStatisticsAttaches.size(); j++) {
                    if (page.getRecords().get(i).getFireNumber().equals(demFireStatisticsAttaches.get(j).getFireNumber())) {
                        map.put("zid", demFireStatisticsAttaches.get(j).getId());
                        map.put("fireCauseType1", demFireStatisticsAttaches.get(j).getFireCauseType1());
                        map.put("fireSiteType1", demFireStatisticsAttaches.get(j).getFireSiteType1());
                    }
                }
                for (int j = 0; j < demFileLabels.size(); j++) {
                    if (page.getRecords().get(i).getTypeId1() != null && page.getRecords().get(i).getTypeId1() == demFileLabels.get(j).getId()) {
                        map.put("typeName1", demFileLabels.get(j).getLabelName());
                    }
                    if (page.getRecords().get(i).getTypeId2() != null && page.getRecords().get(i).getTypeId2() == demFileLabels.get(j).getId()) {
                        map.put("typeName2", demFileLabels.get(j).getLabelName());
                    }
                    if (page.getRecords().get(i).getTypeId3() != null && page.getRecords().get(i).getTypeId3() == demFileLabels.get(j).getId()) {
                        map.put("typeName3", demFileLabels.get(j).getLabelName());
                    }
                    if (page.getRecords().get(i).getTypeId4() != null && page.getRecords().get(i).getTypeId4() == demFileLabels.get(j).getId()) {
                        map.put("typeName4", demFileLabels.get(j).getLabelName());
                    }
                    if (page.getRecords().get(i).getTypeId5() != null && page.getRecords().get(i).getTypeId4() == demFileLabels.get(j).getId()) {
                        map.put("typeName5", demFileLabels.get(j).getLabelName());
                    }
                }
                list.add(map);
            }
        }
        return new CommonPage<>(list, page.getTotal(), pageSize, pageNum);
    }

    @Override
    public List<DemFireStatisticsExportVO> fireAccidentStatisticExport(String fireNumber, Integer labelId, Integer classifyId){
        List<DemFireStatisticsExportVO> list = new ArrayList<>();

        Integer type1 = 0;
        Integer type2 = 0;
        Integer type3 = 0;
        Integer type4 = 0;
        Integer type5 = 0;
        if (labelId != null && labelId != 0) {
            LambdaQueryWrapper<DemFireLabelAttribute> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.eq(DemFireLabelAttribute::getLabelId, labelId);
            List<DemFireLabelAttribute> list1 = demFireLabelAttributeService.list(queryWrapper1);
            if (list1.size() > 0) {
                switch (list1.get(0).getAttribute()) {
                    case "typeName1":
                        type1 = classifyId;
                        break;
                    case "typeName2":
                        type2 = classifyId;
                        break;
                    case "typeName3":
                        type3 = classifyId;
                        break;
                    case "typeName4":
                        type4 = classifyId;
                        break;
                    case "typeName5":
                        type5 = classifyId;
                        break;
                }
            }
        }
        LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(DemFireStatistics::getBurnedArea, DemFireStatistics::getDirectPropertyLoss, DemFireStatistics::getVictimNumber,
                DemFireStatistics::getInjuredNumber, DemFireStatistics::getDeathToll, DemFireStatistics::getFileCase, DemFireStatistics::getFireGrade,
                DemFireStatistics::getSubordinateDetachment, DemFireStatistics::getAdministrativeDivision, DemFireStatistics::getFireNumber,
                DemFireStatistics::getFireAddress, DemFireStatistics::getFireTime, DemFireStatistics::getId, DemFireStatistics::getTypeId1,
                DemFireStatistics::getTypeId2, DemFireStatistics::getTypeId3, DemFireStatistics::getTypeId4, DemFireStatistics::getTypeId5)
                .like(StringUtils.isNotBlank(fireNumber), DemFireStatistics::getFireNumber, fireNumber)
                .eq(type1 != null && type1 != 0, DemFireStatistics::getTypeId1, type1)
                .eq(type2 != null && type2 != 0, DemFireStatistics::getTypeId2, type2)
                .eq(type3 != null && type3 != 0, DemFireStatistics::getTypeId3, type3)
                .eq(type4 != null && type4 != 0, DemFireStatistics::getTypeId4, type4)
                .eq(type5 != null && type5 != 0, DemFireStatistics::getTypeId5, type5)
                .orderByDesc(DemFireStatistics::getId);
        List<DemFireStatistics> fireStatisticsList = this.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(fireStatisticsList)){
            List<String> fireNumberList = new ArrayList<>();
            for (int i = 0; i < fireStatisticsList.size(); i++) {
                fireNumberList.add(fireStatisticsList.get(i).getFireNumber());
            }
            List<DemFireStatisticsAttach> demFireStatisticsAttaches = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(fireNumberList)) {
                demFireStatisticsAttaches = demFireStatisticsAttachService.fireAccidentStatistic(fireNumberList);
            }

            List<DemFileLabel> demFileLabels = demFileLabelService.demFileLabelList(null, null, null);
            for (int i = 0; i < fireStatisticsList.size(); i++) {
                DemFireStatisticsExportVO demFireStatisticsExportVO = new DemFireStatisticsExportVO();
                demFireStatisticsExportVO.setFireNumber(fireStatisticsList.get(i).getFireNumber());
                demFireStatisticsExportVO.setFireAddress(fireStatisticsList.get(i).getFireAddress());
                demFireStatisticsExportVO.setFireTime((fireStatisticsList.get(i).getFireTime()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                demFireStatisticsExportVO.setFireCause(null);
                demFireStatisticsExportVO.setFireSite(null);
                for (int j = 0; j < demFireStatisticsAttaches.size(); j++) {
                    if (fireStatisticsList.get(i).getFireNumber().equals(demFireStatisticsAttaches.get(j).getFireNumber())) {
                        demFireStatisticsExportVO.setFireCause(demFireStatisticsAttaches.get(j).getFireCauseType1());
                        demFireStatisticsExportVO.setFireSite(demFireStatisticsAttaches.get(j).getFireSiteType1());
                    }
                }
                demFireStatisticsExportVO.setDirectPropertyLoss(fireStatisticsList.get(i).getDirectPropertyLoss());
                demFireStatisticsExportVO.setBurnedArea(fireStatisticsList.get(i).getBurnedArea());
                demFireStatisticsExportVO.setVictimNumber(fireStatisticsList.get(i).getVictimNumber());
                demFireStatisticsExportVO.setInjuredNumber(fireStatisticsList.get(i).getInjuredNumber());
                demFireStatisticsExportVO.setDeathToll(fireStatisticsList.get(i).getDeathToll());
                demFireStatisticsExportVO.setFileCase(fireStatisticsList.get(i).getFileCase());
                demFireStatisticsExportVO.setFireGrade(fireStatisticsList.get(i).getFireGrade());
                demFireStatisticsExportVO.setSubordinateDetachment(fireStatisticsList.get(i).getSubordinateDetachment());
                demFireStatisticsExportVO.setAdministrativeDivision(fireStatisticsList.get(i).getAdministrativeDivision());
                list.add(demFireStatisticsExportVO);
            }
        }

        return list;
    }

    @Transactional
    @Override
    public void addLabel(DemFileLabel demFileLabel) {
        if (demFileLabel.getId() == 0) {
            int count = demFileLabelService.demFileLabelCount(0, demFileLabel.getLabelName(), 0);
            if (count > 0) {
                throw new BusinessException("标签名不可重复");
            }
            LambdaQueryWrapper<DemFireLabelAttribute> queryWrapper = Wrappers.lambdaQuery();
            List<DemFireLabelAttribute> list = demFireLabelAttributeService.list(queryWrapper);
            String typeAttribute = "typeName1";
            if (list.size() > 1) {
                List<String> typeIdList1 = new ArrayList<>();
                typeIdList1.add("typeName1");
                typeIdList1.add("typeName2");
                typeIdList1.add("typeName3");
                typeIdList1.add("typeName4");
                typeIdList1.add("typeName5");
                List<String> typeIdList2 = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    typeIdList2.add(list.get(i).getAttribute());
                }
                List<String> typeIdList = OnlineMethod.subList2(typeIdList1, typeIdList2);
                typeAttribute = typeIdList.get(0);
            }
            demFileLabelService.addDemFileLabel(demFileLabel);
            DemFireLabelAttribute demFireLabelAttribute = new DemFireLabelAttribute();
            demFireLabelAttribute.setLabelId(demFileLabel.getId());
            demFireLabelAttribute.setAttribute(typeAttribute);
            demFireLabelAttributeService.save(demFireLabelAttribute);
        } else {
            int count = demFileLabelService.demFileLabelCount(0, demFileLabel.getLabelName(), demFileLabel.getId());
            if (count > 0) {
                throw new BusinessException("标签名不可重复");
            }
            demFileLabelService.updateDemFileLabel(demFileLabel);
        }
        int fid = demFileLabel.getId();
        List<DemFileLabel> demFileLabel1 = demFileLabel.getSubset();
        if (CollectionUtils.isNotEmpty(demFileLabel1)) {
            List<DemFileLabel> demFileLabel2 = new ArrayList<>();
            List<DemFileLabel> demFileLabel3 = new ArrayList<>();
            List<String> idList1 = new ArrayList<>();
            List<String> idList2 = new ArrayList<>();
            for (int i = 0; i < demFileLabel1.size(); i++) {
                if (demFileLabel1.get(i).getId() == 0) {
                    demFileLabel2.add(demFileLabel1.get(i));
                } else {
                    demFileLabel3.add(demFileLabel1.get(i));
                    idList1.add(demFileLabel1.get(i).getId() + "");
                }
            }
            List<DemFileLabel> demFileLabels = demFileLabelService.demFileLabelList(fid, null, null);
            if (CollectionUtils.isNotEmpty(demFileLabels)) {
                for (int i = 0; i < demFileLabels.size(); i++) {
                    idList2.add(demFileLabels.get(i).getId() + "");
                }
            }
            List<String> idlist = OnlineMethod.subList2(idList2, idList1);
            if (CollectionUtils.isNotEmpty(idlist)) {
                for (int i = 0; i < idlist.size(); i++) {
                    demFileLabelService.delDemFileLabel(Integer.parseInt(idlist.get(i)));
                }
            }

            if (CollectionUtils.isNotEmpty(demFileLabel3)) {
                for (int i = 0; i < demFileLabel3.size(); i++) {
                    int count = demFileLabelService.demFileLabelCount(fid, demFileLabel3.get(i).getLabelName(), demFileLabel3.get(i).getId());
                    if (count > 0) {
                        throw new BusinessException("分类名不可重复");
                    }
                    demFileLabelService.updateDemFileLabel(demFileLabel3.get(i));
                }
            }

            if (CollectionUtils.isNotEmpty(demFileLabel2)) {
                for (int i = 0; i < demFileLabel2.size(); i++) {
                    demFileLabel2.get(i).setFid(fid);
                    int count = demFileLabelService.demFileLabelCount(fid, demFileLabel2.get(i).getLabelName(), 0);
                    if (count > 0) {
                        throw new BusinessException("分类名不可重复");
                    }
                    demFileLabelService.addDemFileLabel(demFileLabel2.get(i));
                }
            }
        }
    }

    @Override
    public CommonPage<Object> fireStatisticList(String fireNumber, String fireCauseType1, Integer pageNum, Integer pageSize) {
        IPage<DemFireStatisticsAttach> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(DemFireStatisticsAttach::getFireCauseType1, DemFireStatisticsAttach::getFireNumber,
                DemFireStatisticsAttach::getId)
                .like(StringUtils.isNotBlank(fireNumber), DemFireStatisticsAttach::getFireNumber, fireNumber)
                .eq(StringUtils.isNotBlank(fireCauseType1), DemFireStatisticsAttach::getFireCauseType1, fireCauseType1)
                .orderByDesc(DemFireStatisticsAttach::getId);
        page = demFireStatisticsAttachService.page(page, queryWrapper);
        List<Object> list = new ArrayList<>();
        if (page.getTotal() > 0) {
            LambdaQueryWrapper<DemFireStatistics> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.select(DemFireStatistics::getFireGrade, DemFireStatistics::getAdministrativeDivision,
                    DemFireStatistics::getFireNumber, DemFireStatistics::getFireTime, DemFireStatistics::getId)
                    .like(StringUtils.isNotBlank(fireNumber), DemFireStatistics::getFireNumber, fireNumber)
                    .orderByDesc(DemFireStatistics::getId);
            List<DemFireStatistics> list1 = this.list(queryWrapper1);
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", null);
                map.put("administrativeDivision", null);
                map.put("fireGrade", null);
                map.put("fireTime", null);
                map.put("zid", page.getRecords().get(i).getId());
                map.put("fireCauseType1", page.getRecords().get(i).getFireCauseType1());
                map.put("fireNumber", page.getRecords().get(i).getFireNumber());
                for (int j = 0; j < list1.size(); j++) {
                    if (page.getRecords().get(i).getFireNumber().equals(list1.get(j).getFireNumber())) {
                        map.put("id", list1.get(j).getId());
                        map.put("fireGrade", list1.get(j).getFireGrade());
                        map.put("administrativeDivision", list1.get(j).getAdministrativeDivision());
                        map.put("fireTime", list1.get(j).getFireTime());
                    }
                }
                list.add(map);
            }
        }
        return new CommonPage<>(list, page.getTotal(), pageSize, pageNum);
    }

    @Transactional
    @Override
    public void bindingLabel(ParameterVo parameterVo) {
        LambdaQueryWrapper<DemFireLabelAttribute> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DemFireLabelAttribute::getLabelId, parameterVo.getLabelId());
        List<DemFireLabelAttribute> list = demFireLabelAttributeService.list(queryWrapper);
        for (int i = 0; i < parameterVo.getIdList().size(); i++) {
            DemFireStatistics demFireStatistics = new DemFireStatistics();
            demFireStatistics.setId(parameterVo.getIdList().get(i));
            switch (list.get(0).getAttribute()) {
                case "typeName1":
                    demFireStatistics.setTypeId1(parameterVo.getClassifyId());
                    break;
                case "typeName2":
                    demFireStatistics.setTypeId2(parameterVo.getClassifyId());
                    break;
                case "typeName3":
                    demFireStatistics.setTypeId3(parameterVo.getClassifyId());
                    break;
                case "typeName4":
                    demFireStatistics.setTypeId4(parameterVo.getClassifyId());
                    break;
                case "typeName5":
                    demFireStatistics.setTypeId5(parameterVo.getClassifyId());
                    break;
            }
            this.updateById(demFireStatistics);
        }
    }


    @Transactional
    @Override
    public void updateDemFireStatistics(DemFireStatisticsVo demFireStatisticsVo) {
        DemFireStatistics demFireStatistics = new DemFireStatistics();
        demFireStatistics.setId(demFireStatisticsVo.getId());
        demFireStatistics.setFireGrade(demFireStatisticsVo.getFireGrade());
        demFireStatistics.setFireAddress(demFireStatisticsVo.getFireAddress());
        demFireStatistics.setBurnedArea(demFireStatisticsVo.getBurnedArea());
        demFireStatistics.setAdministrativeDivision(demFireStatisticsVo.getAdministrativeDivision());
        demFireStatistics.setFillTime(demFireStatisticsVo.getFireTime());
        demFireStatistics.setDeathToll(demFireStatisticsVo.getDeathToll());
        demFireStatistics.setFileCase(demFireStatisticsVo.getFileCase());
        demFireStatistics.setDirectPropertyLoss(demFireStatisticsVo.getDirectPropertyLoss());
        demFireStatistics.setTypeId1(demFireStatisticsVo.getTypeId1());
        demFireStatistics.setTypeId2(demFireStatisticsVo.getTypeId2());
        demFireStatistics.setTypeId3(demFireStatisticsVo.getTypeId3());
        demFireStatistics.setTypeId4(demFireStatisticsVo.getTypeId4());
        demFireStatistics.setTypeId5(demFireStatisticsVo.getTypeId5());
        demFireStatistics.setInjuredNumber(demFireStatisticsVo.getInjuredNumber());
        demFireStatistics.setSubordinateDetachment(demFireStatisticsVo.getSubordinateDetachment());
        demFireStatistics.setVictimNumber(demFireStatisticsVo.getVictimNumber());
        demFireStatistics.setUpdateTime(LocalDateTime.now());
        demFireStatistics.setUpdatePerson(SecurityUtils.getUsername());
        this.updateById(demFireStatistics);
        DemFireStatisticsAttach demFireStatisticsAttach = new DemFireStatisticsAttach();
        demFireStatisticsAttach.setId(demFireStatisticsVo.getZid());
        demFireStatisticsAttach.setFireCauseType1(demFireStatisticsVo.getFireCauseType1());
        demFireStatisticsAttach.setFireSiteType1(demFireStatisticsVo.getFireSiteType1());
        demFireStatisticsAttach.setUpdateTime(LocalDateTime.now());
        demFireStatisticsAttach.setUpdatePerson(SecurityUtils.getUsername());
        demFireStatisticsAttachService.updateById(demFireStatisticsAttach);
    }

    @Transactional
    @Override
    public void delDemFireStatistics(Integer id, Integer zid) {
        this.removeById(id);
        demFireStatisticsAttachService.removeById(zid);
    }

    @Override
    public void abnormalData(DemFileLabel demFileLabel) {
        List<Integer> typeIdList = new ArrayList<>();
        if (demFileLabel.getId() != null && demFileLabel.getId() != 0) {
            LambdaQueryWrapper<DemFileLabel> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.eq(DemFileLabel::getFid, demFileLabel.getId());
            List<DemFileLabel> list1 = demFileLabelService.list(queryWrapper1);
            for (int i = 0; i < list1.size(); i++) {
                typeIdList.add(list1.get(i).getId());
            }
        } else {
            LambdaQueryWrapper<DemFileLabel> queryWrapper2 = Wrappers.lambdaQuery();
            queryWrapper2.eq(DemFileLabel::getLabelName, demFileLabel.getLabelName())
                    .eq(DemFileLabel::getFid, demFileLabel.getFid());
            List<DemFileLabel> list2 = demFileLabelService.list(queryWrapper2);
            for (int i = 0; i < list2.size(); i++) {
                typeIdList.add(list2.get(i).getId());
            }
        }
        if (CollectionUtils.isNotEmpty(typeIdList)) {
            LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.in(DemFireStatistics::getTypeId1, typeIdList)
                    .or()
                    .in(DemFireStatistics::getTypeId2, typeIdList)
                    .or()
                    .in(DemFireStatistics::getTypeId3, typeIdList)
                    .or()
                    .in(DemFireStatistics::getTypeId4, typeIdList)
                    .or()
                    .in(DemFireStatistics::getTypeId5, typeIdList);
            List<DemFireStatistics> list = this.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                throw new BusinessException("标签/分类绑定中，不可删除");
            }
        }
    }

    @Transactional
    @Override
    public void delDemFileLabel(Integer id) {
        DemFileLabel demFileLabel = new DemFileLabel();
        demFileLabel.setId(id);
        this.abnormalData(demFileLabel);
        demFileLabelService.removeById(id);
        List<DemFireLabelAttribute> list = demFireLabelAttributeService.freLabelAttributeList(id);
        if (CollectionUtils.isNotEmpty(list)) {
            demFireLabelAttributeService.delDemFireLabelAttribute(list.get(0).getId());
        }
    }

    @Override
    public CommonPage<Map<String, Object>> firePlaceList(String fireNumber, Integer id, Integer pageNum, Integer pageSize) {
        List<Map<String, Object>> list = new ArrayList<>();
        IPage<DemFireStatistics> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(DemFireStatistics::getId, DemFireStatistics::getFireNumber, DemFireStatistics::getBurnedArea,
                DemFireStatistics::getAffectedHouse, DemFireStatistics::getVictimNumber, DemFireStatistics::getDirectPropertyLoss,
                DemFireStatistics::getFireTime, DemFireStatistics::getFireGrade)
                .like(StringUtils.isNotBlank(fireNumber), DemFireStatistics::getFireNumber, fireNumber)
                .eq(id != null && id != 0, DemFireStatistics::getId, id)
                .orderByDesc(DemFireStatistics::getId);
        page = this.page(page, queryWrapper);
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<String> fireNumberList = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                fireNumberList.add(page.getRecords().get(i).getFireNumber());
            }
            LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.select(DemFireStatisticsAttach::getId, DemFireStatisticsAttach::getFireNumber, DemFireStatisticsAttach::getInitialFuelType1,
                    DemFireStatisticsAttach::getFireCauseType1, DemFireStatisticsAttach::getBuildName)
                    .in(CollectionUtils.isNotEmpty(fireNumberList), DemFireStatisticsAttach::getFireNumber, fireNumberList);
            List<DemFireStatisticsAttach> list1 = demFireStatisticsAttachService.list(queryWrapper1);
            for (int i = 0; i < page.getRecords().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", page.getRecords().get(i).getId());
                map.put("fireNumber", page.getRecords().get(i).getFireNumber());
                map.put("burnedArea", page.getRecords().get(i).getBurnedArea());
                map.put("affectedHouse", page.getRecords().get(i).getAffectedHouse());
                map.put("victimNumber", page.getRecords().get(i).getVictimNumber());
                map.put("directPropertyLoss", page.getRecords().get(i).getDirectPropertyLoss());
                map.put("fireTimeText", page.getRecords().get(i).getFireTime());
                map.put("fireGrade", page.getRecords().get(i).getFireGrade());
                map.put("id1", 0);
                map.put("initialFuelType1", null);
                map.put("fireCauseType1", null);
                map.put("buildName", null);
                for (int j = 0; j < list1.size(); j++) {
                    if (page.getRecords().get(i).getFireNumber().equals(list1.get(j).getFireNumber())) {
                        map.put("id1", list1.get(j).getId());
                        map.put("initialFuelType1", list1.get(j).getInitialFuelType1());
                        map.put("fireCauseType1", list1.get(j).getFireCauseType1());
                        map.put("buildName", list1.get(j).getBuildName());
                    }
                }
                list.add(map);
            }
        }
        return new CommonPage<>(list, page.getTotal(), pageSize, pageNum);
    }

    @Override
    public List<FirePlaceExportVO> firePlaceListExport(String fireNumber){
        List<FirePlaceExportVO> list = new ArrayList<>();
        LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(DemFireStatistics::getId, DemFireStatistics::getFireNumber, DemFireStatistics::getBurnedArea,
                DemFireStatistics::getAffectedHouse, DemFireStatistics::getVictimNumber, DemFireStatistics::getDirectPropertyLoss,
                DemFireStatistics::getFireTime, DemFireStatistics::getFireGrade)
                .like(StringUtils.isNotBlank(fireNumber), DemFireStatistics::getFireNumber, fireNumber)
                .orderByDesc(DemFireStatistics::getId);
        List<DemFireStatistics> list1= this.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list1)) {
            List<String> fireNumberList = new ArrayList<>();
            for (int i = 0; i < list1.size(); i++) {
                fireNumberList.add(list1.get(i).getFireNumber());
            }
            LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.select(DemFireStatisticsAttach::getId, DemFireStatisticsAttach::getFireNumber, DemFireStatisticsAttach::getInitialFuelType1,
                    DemFireStatisticsAttach::getFireCauseType1, DemFireStatisticsAttach::getBuildName)
                    .in(CollectionUtils.isNotEmpty(fireNumberList), DemFireStatisticsAttach::getFireNumber, fireNumberList);
            List<DemFireStatisticsAttach> list2 = demFireStatisticsAttachService.list(queryWrapper1);
            for (int i = 0; i < list1.size(); i++) {
                FirePlaceExportVO firePlaceExportVO = new FirePlaceExportVO();
                firePlaceExportVO.setFireNumber(list1.get(i).getFireNumber());
                firePlaceExportVO.setInitialFuelType1(null);
                firePlaceExportVO.setBurnedArea(list1.get(i).getBurnedArea());
                firePlaceExportVO.setAffectedHouse(list1.get(i).getAffectedHouse());
                firePlaceExportVO.setVictimNumber(list1.get(i).getVictimNumber());
                firePlaceExportVO.setFireCause(null);
                firePlaceExportVO.setDirectPropertyLoss(list1.get(i).getDirectPropertyLoss());
                firePlaceExportVO.setFireTime((list1.get(i).getFireTime()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                firePlaceExportVO.setFireGrade(list1.get(i).getFireGrade());
                firePlaceExportVO.setBuildName(null);
                for (int j = 0; j < list2.size(); j++) {
                    if (list1.get(i).getFireNumber().equals(list2.get(j).getFireNumber())) {
                        firePlaceExportVO.setInitialFuelType1(list2.get(j).getInitialFuelType1());
                        firePlaceExportVO.setFireCause(list2.get(j).getFireCauseType1());
                        firePlaceExportVO.setBuildName(list2.get(j).getBuildName());
                    }
                }
                list.add(firePlaceExportVO);
            }
        }

        return list;
    }

    @Transactional
    @Override
    public void updateFirePlace(DemFireStatistics demFireStatistics) {
        demFireStatistics.setUpdatePerson(SecurityUtils.getUsername());
        demFireStatistics.setUpdateTime(LocalDateTime.now());
        this.updateById(demFireStatistics);
        DemFireStatisticsAttach demFireStatisticsAttach = new DemFireStatisticsAttach();
        demFireStatisticsAttach.setId(demFireStatistics.getId1());
        demFireStatisticsAttach.setInitialFuelType1(demFireStatistics.getInitialFuelType1());
        demFireStatisticsAttach.setFireCauseType1(demFireStatistics.getFireCauseType1());
        demFireStatisticsAttach.setBuildName(demFireStatistics.getBuildName());
        demFireStatisticsAttach.setUpdatePerson(SecurityUtils.getUsername());
        demFireStatisticsAttach.setUpdateTime(LocalDateTime.now());
        demFireStatisticsAttachService.updateById(demFireStatisticsAttach);
    }

    @Override
    public List<Object> getFireCountByData(String startTime, String endTime, String address, String fireType) {
        Date startTime1 = null;
        Date endTime1 = null;
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime1 = OnlineMethod.transferString2Date(startTime);
            endTime1 = OnlineMethod.transferString2Date(endTime);
        }

        List<Object> list = new ArrayList<>();
        Date date = new Date();
        Date beginDayOfYear = DateUtils.getBeginDayOfYear(date);
        //获取传入时间的最大时间和最小时间
        int distanceOfTwoDate = Integer.parseInt(DateUtils.getYear(endTime1)) - Integer.parseInt(DateUtils.getYear(startTime1)) + 1;
        //获取数据库全部项目的最小时间和最大时间
        QueryWrapper<DemFireStatistics> query = Wrappers.query();
        query.select("max(fire_time) as fireTime");
        DemFireStatistics one = this.getOne(query);
        QueryWrapper<DemFireStatistics> query1 = Wrappers.query();
        query1.select("min(fire_time) as fireTime");
        DemFireStatistics one1 = this.getOne(query1);
        Date maxDate = null;
        Date minDate = null;
        if (one.getFireTime() != null) {
            maxDate = Date.from(one.getFireTime().atZone(ZoneId.systemDefault()).toInstant());
        }
        if (one1.getFireTime() != null) {
            minDate = Date.from(one1.getFireTime().atZone(ZoneId.systemDefault()).toInstant());
        }
        int distanceOfTwoDateYear = Integer.parseInt(DateUtils.getYear(maxDate)) - Integer.parseInt(DateUtils.getYear(minDate)) + 1;
        list.add(perfect(beginDayOfYear, date, address, fireType, 1));
        list.add(perfect(startTime1, endTime1, address, fireType, distanceOfTwoDate));
        list.add(perfect(null, null, address, fireType, distanceOfTwoDateYear));
        return list;
    }

    public List<Object> perfect(Date startTime, Date endTime, String address, String fireType, Integer subTime) {
        List<String> fireNumberList = new ArrayList<>();
        if (StringUtils.isNotBlank(fireType)) {
            LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.select(DemFireStatisticsAttach::getFireNumber)
                    .eq(DemFireStatisticsAttach::getFireCauseType1, fireType);
            List<DemFireStatisticsAttach> list1 = demFireStatisticsAttachService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(list1)) {
                for (int i = 0; i < list1.size(); i++) {
                    fireNumberList.add(list1.get(i).getFireNumber());
                }
            }
        }
        QueryWrapper<DemFireStatistics> query = Wrappers.query();
        query.select("MONTH (fire_time) monthTime", "COUNT(1) AS aCount")
                .like(StringUtils.isNotBlank(address), "fire_address", address)
                .in(CollectionUtils.isNotEmpty(fireNumberList), "fire_number", fireNumberList)
                .between(startTime != null && endTime != null, "fire_time", startTime, endTime)
                .groupBy("monthTime");
        List<Map<String, Object>> list = this.listMaps(query);
        List<Object> avgList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            int finalI = i;
            list.stream()
                    .filter(map -> Integer.parseInt(map.get("monthTime").toString()) == finalI)
                    .findFirst()
                    .map(map -> {
                        avgList.add(Arith.div(Double.parseDouble(map.get("aCount").toString()), subTime, 2));
                        return Optional.empty();
                    })
                    .orElseGet(() -> {
                        avgList.add(0.00);
                        return Optional.empty();
                    });
        }
        return avgList;
    }

    @Override
    public List<FireLevelRatioVO> getGroupByLevel(String startTime, String endTime, String address) {
        List<FireLevelRatioVO> list = new ArrayList<>();
        int fireCount = 0;
        List<String> fireCauses = demFireStatisticsAttachService.getFireType();
        for (String cause : fireCauses) {
            if (StringUtils.isBlank(cause)) {
                continue;
            }
            FireLevelRatioVO fireLevelRatioVo = new FireLevelRatioVO();
            fireLevelRatioVo.setFireType(cause);
            List<String> fireNumberList = new ArrayList<>();
            if (StringUtils.isNotBlank(cause)) {
                LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.select(DemFireStatisticsAttach::getFireNumber)
                        .eq(DemFireStatisticsAttach::getFireCauseType1, cause);
                List<DemFireStatisticsAttach> list1 = demFireStatisticsAttachService.list(queryWrapper);
                if (CollectionUtils.isNotEmpty(list1)) {
                    for (int i = 0; i < list1.size(); i++) {
                        fireNumberList.add(list1.get(i).getFireNumber());
                    }
                }
            }
            LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.like(StringUtils.isNotBlank(address), DemFireStatistics::getFireAddress, address)
                    .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), DemFireStatistics::getFireTime, startTime, endTime);
            Integer count = this.count(queryWrapper);
            fireLevelRatioVo.setRadio(count.doubleValue());
            list.add(fireLevelRatioVo);
            fireCount += count;
        }
        //排序
        List<FireLevelRatioVO> orderByList = list.stream().sorted(Comparator.comparing(FireLevelRatioVO::getRadio).reversed()).limit(10).collect(Collectors.toList());

        //差集求和
        double sum = list.stream().filter(item -> !orderByList.contains(item)).mapToDouble(FireLevelRatioVO::getRadio).sum();
        orderByList.stream().filter(item -> "其他".equals(item.getFireType())).findAny()
                .map(fireLevelRatio -> {
                            fireLevelRatio.setRadio(fireLevelRatio.getRadio() + sum);
                            return fireLevelRatio;
                        }
                ).orElseGet(() -> {
            FireLevelRatioVO fireLevelRatioVo = new FireLevelRatioVO();
            fireLevelRatioVo.setFireType("其他");
            fireLevelRatioVo.setRadio(sum);
            orderByList.add(fireLevelRatioVo);
            return fireLevelRatioVo;
        });
        int finalFireCount = fireCount;
        if (0 != finalFireCount) {
            orderByList.forEach(fireLevelRatio -> fireLevelRatio.setRadio(Arith.div(fireLevelRatio.getRadio(), finalFireCount)));
        }
        return orderByList;
    }

    @Override
    public CommonPage<FireStatisticsPO> page(Integer current, Integer size, String startTime, String endTime, String address) {
        Page<DemFireStatistics> page = new Page<>(current, size);
        LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), DemFireStatistics::getFireTime, startTime, endTime)
                .like(StringUtils.isNotBlank(address), DemFireStatistics::getFireAddress, address)
                .orderByDesc(DemFireStatistics::getDeathToll);
        page = this.page(page, queryWrapper);
        List<Map<String, String>> listmap = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            List<String> fireNumberList = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                fireNumberList.add(page.getRecords().get(i).getFireNumber());
            }
            LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.in(DemFireStatisticsAttach::getFireNumber, fireNumberList);
            List<DemFireStatisticsAttach> list = demFireStatisticsAttachService.list(queryWrapper1);
            AtomicReference<Map<String, String>> stringStringMap = new AtomicReference<>();
            listmap = page.getRecords().stream().map(m -> {
                list.stream().filter(m2 -> Objects.equals(m.getFireNumber(), m2.getFireNumber())).forEach(m2 -> {
                    stringStringMap.set(convertObjectToMap(m));
                    Map<String, String> stringStringMap1 = convertObjectToMap(m2);
                    stringStringMap.get().putAll(stringStringMap1);
                });
                return stringStringMap.get();
            }).collect(Collectors.toList());
        }

        List<FireStatisticsPO> list = listmap
                .stream()
                .map(this::enhanceFireStatisticsPo).collect(Collectors.toList());
        //筛选出精度和维度是空的数据
        List<FireStatisticsPO> isNullData = list.stream()
                .filter(fireStatisticsPo -> 0.00 == fireStatisticsPo.getLatitude())
                .filter(fireStatisticsPo -> StringUtils.isNotBlank(fireStatisticsPo.getAddress()))
                .collect(Collectors.toList());
        List<List<FireStatisticsPO>> subSets = Lists.partition(isNullData, 10);
        for (List<FireStatisticsPO> listLimit : subSets) {
            String addressList = listLimit.stream().map(FireStatisticsPO::getAddress).collect(Collectors.joining("|"));
            List<LocateInfo> lonLat = OnlineMethod.getLonLat(addressList);
            if (CollectionUtils.isNotEmpty(lonLat)) {
                for (FireStatisticsPO fireStatisticsPo : listLimit) {
                    fireStatisticsPo.setLatitude(lonLat.get(listLimit.indexOf(fireStatisticsPo)).getLatitude());
                    fireStatisticsPo.setLongitude(lonLat.get(listLimit.indexOf(fireStatisticsPo)).getLongitude());
                    fireStatisticsPo.setDistrict(lonLat.get(listLimit.indexOf(fireStatisticsPo)).getDistrict());
                    fireStatisticsPo.setStreet(lonLat.get(listLimit.indexOf(fireStatisticsPo)).getStreet());

                }
                baseMapper.updateList(listLimit);
            }
        }
        return new CommonPage<>(list, page.getTotal(), page.getSize(), page.getCurrent());
    }

    @Override
    public List<DemFireStatisticsScattorVO> fireStatisticScattor(String street, String lossType, String startTime, String endTime){
        List<DemFireStatisticsScattorVO> list = new ArrayList<>();
//        LambdaQueryWrapper<DemFireStatistics> queryWrapper = Wrappers.lambdaQuery();
//        List<DemFireStatistics> dataList = this.list(queryWrapper);
//        if(CollectionUtils.isNotEmpty(dataList)){
//            for (int i = 0; i < dataList.size(); i++) {
//                if(StringUtils.isBlank(dataList.get(i).getStreet()) || (dataList.get(i).getStreet()).length() == 0){
//                    List<LocateInfo> infoList = OnlineMethod.getLonLat(dataList.get(i).getFireAddress());
//                    if(infoList.size() > 0){
//                        dataList.get(i).setLatitude(infoList.get(0).getLatitude().toString());
//                        dataList.get(i).setLongitude(infoList.get(0).getLongitude().toString());
//                        dataList.get(i).setDistrict(infoList.get(0).getDistrict());
//                        this.updateById(dataList.get(i));
//                    }
//                }
//            }
//        }
//        LambdaQueryWrapper<DemFireStatistics> queryWrapper11 = Wrappers.lambdaQuery();
//        List<DemFireStatistics> dataList11 = this.list(queryWrapper11);
//        if(CollectionUtils.isNotEmpty(dataList11)){
//            for (int i = 0; i < dataList11.size(); i++) {
//                if(StringUtils.isBlank(dataList11.get(i).getStreet()) || (dataList11.get(i).getStreet()).length() == 0){
//                    String location = dataList11.get(i).getLongitude() + "," + dataList11.get(i).getLatitude();
//                    String streetTown = OnlineMethod.getStreetTown(location);
//                    System.out.println(streetTown);
//                    if (StringUtils.isNotBlank(streetTown)) {
//                        dataList11.get(i).setStreet(streetTown);
//                        this.updateById(dataList11.get(i));
//                    }
//                }
//            }
//        }

        LambdaQueryWrapper<DemFireStatistics> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(StringUtils.isNotBlank(street),DemFireStatistics::getStreet,street)
                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime),DemFireStatistics::getFireTime,startTime,endTime);
        if(StringUtils.isNotBlank(lossType)){
            if(lossType.equals("亡人火灾")){
                queryWrapper1.gt(DemFireStatistics::getDeathToll,0);
            }else if(lossType.equals("伤人火灾")){
                queryWrapper1.gt(DemFireStatistics::getInjuredNumber,0);
            }
        }
        List<DemFireStatistics> dataList1 = this.list(queryWrapper1);
        if(CollectionUtils.isNotEmpty(dataList1)){
            for (int i = 0; i < dataList1.size(); i++) {
                DemFireStatisticsScattorVO scattorVO = new DemFireStatisticsScattorVO();
                scattorVO.setFireNumber(dataList1.get(i).getFireNumber());
                scattorVO.setFireTime(dataList1.get(i).getFireTime());
                scattorVO.setFireAddress(dataList1.get(i).getFireAddress());
                scattorVO.setFireProcess(dataList1.get(i).getFireProcess());
                scattorVO.setDirectPropertyLoss(dataList1.get(i).getDirectPropertyLoss());
                scattorVO.setBurnedArea(dataList1.get(i).getBurnedArea());
                scattorVO.setAffectedHouse(dataList1.get(i).getAffectedHouse());
                scattorVO.setVictimNumber(dataList1.get(i).getVictimNumber());
                scattorVO.setDeathToll(dataList1.get(i).getDeathToll());
                scattorVO.setInjuredNumber(dataList1.get(i).getInjuredNumber());
                scattorVO.setLongitude(dataList1.get(i).getLongitude());
                scattorVO.setLatitude(dataList1.get(i).getLatitude());
                scattorVO.setDistrict(dataList1.get(i).getDistrict());
                scattorVO.setStreet(dataList1.get(i).getStreet());
                list.add(scattorVO);

            }
        }

        return list;
    }

    @Override
    public List<DemFireStatisticsCountScattorVO> fireStatisticCollect(String street, String startTime, String endTime){
        List<DemFireStatisticsCountScattorVO> list = new ArrayList<>();
        QueryWrapper<DemFireStatistics> queryWrapper = Wrappers.query();
        queryWrapper.select("ROUND(SUM(direct_property_loss)/10000,2) as directPropertyLossTotal","COUNT(*) as fireCount","ROUND(SUM(burned_area),2) as burnedAreaTotal","SUM(death_toll) as deathTollTotal","SUM(injured_number) as injuredNumberTotal")
                .eq(StringUtils.isNotBlank(street),"street",street)
                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime),"fire_time",startTime,endTime);
        List<Map<String,Object>> maps = this.listMaps(queryWrapper);
        if(maps.size() > 0 && Integer.parseInt(maps.get(0).get("fireCount").toString()) > 0){
            DemFireStatisticsCountScattorVO scattorVO = new DemFireStatisticsCountScattorVO();
            scattorVO.setDirectPropertyLossTotal(Double.parseDouble(maps.get(0).get("directPropertyLossTotal").toString()));
            scattorVO.setFireCount(Integer.parseInt(maps.get(0).get("fireCount").toString()));
            scattorVO.setBurnedAreaTotal(Double.parseDouble(maps.get(0).get("burnedAreaTotal").toString()));
            scattorVO.setDeathTollTotal((int)Math.round(Double.parseDouble(maps.get(0).get("deathTollTotal").toString())));
            scattorVO.setInjuredNumberTotal((int)Math.round(Double.parseDouble(maps.get(0).get("injuredNumberTotal").toString())));
            list.add(scattorVO);
        }

        return list;
    }

    @Override
    public List<FireBubbleVO> getAvgAndSum(String startTime, String endTime, String fireType, String unitId) {
        List<FireBubbleVO> fireBubbleVOS = new ArrayList<>();
        List<String> fireNumberList = new ArrayList<>();
        if (StringUtils.isNotBlank(fireType)) {
            LambdaQueryWrapper<DemFireStatisticsAttach> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.select(DemFireStatisticsAttach::getFireNumber)
                    .eq(DemFireStatisticsAttach::getFireCauseType1, fireType);
            List<DemFireStatisticsAttach> list = demFireStatisticsAttachService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    fireNumberList.add(list.get(i).getFireNumber());
                }
            }
        }
        QueryWrapper<DemFireStatistics> query = Wrappers.query();
        query.select("administrative_division as region", "IFNULL(sum(death_toll),0) as deathPerson", "IFNULL(avg(burned_area),0.00) as fireArea", "count(1) as fireCount")
                .eq(StringUtils.isNotBlank(unitId), "company_code", unitId)
                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), "fire_time", startTime, endTime)
                .in(CollectionUtils.isNotEmpty(fireNumberList), "fire_number", fireNumberList)
                .groupBy("administrative_division");
        List<Map<String, Object>> list = this.listMaps(query);
//        list = list.stream().filter(s -> s.get("region").toString().contains("派出所")).collect(Collectors.toList());
        list.forEach(s -> {
            FireBubbleVO fireBubbleVo = new FireBubbleVO();
            if (s.get("region").toString().contains("派出所")){
                fireBubbleVo.setRegion(s.get("region").toString().replace("派出所",""));
            }else {
                fireBubbleVo.setRegion(s.get("region").toString());
            }

            fireBubbleVo.setFireCount(Integer.valueOf(s.get("fireCount").toString()));
            fireBubbleVo.setDeathToll(Double.valueOf(s.get("deathPerson").toString()));
            fireBubbleVo.setFireArea(Double.valueOf(s.get("fireArea").toString()));
            fireBubbleVOS.add(fireBubbleVo);
        });
        return fireBubbleVOS;
    }


    public FireStatisticsPO enhanceFireStatisticsPo(Map<String, String> map) {
        FireStatisticsPO fireStatisticsPo = new FireStatisticsPO();
        fireStatisticsPo.setId(Optional.ofNullable(map.get("fireNumber")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setAddress(Optional.ofNullable(map.get("fireAddress")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setBurnedArea(Optional.ofNullable(map.get("burnedArea")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setPropertyLoss(Optional.ofNullable(map.get("directPropertyLoss")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setDeathToll(Optional.ofNullable(map.get("deathToll")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setNonFatal(Optional.ofNullable(map.get("victimNumber")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setDisasterHome(Optional.ofNullable(map.get("affectedHouse")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setFireCause(Optional.ofNullable(map.get("fireCauseType1")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setFireLevel(Optional.ofNullable(map.get("fireGrade")).filter(s -> !"null".equals(s)).orElse(""));
        fireStatisticsPo.setLongitude(Double.valueOf(Optional.ofNullable(map.get("longitude")).filter(StringUtils::isNotBlank).orElse("0.00")));
        fireStatisticsPo.setLatitude(Double.valueOf(Optional.ofNullable(map.get("latitude")).filter(StringUtils::isNotBlank).orElse("0.00")));
        fireStatisticsPo.setDistrict(map.get("district"));
        fireStatisticsPo.setStreet(map.get("street"));
        fireStatisticsPo.setPlaceOne(map.get("initialFuelType1"));
        fireStatisticsPo.setPlaceTwo(map.get("initialFuelType2"));
        fireStatisticsPo.setFireGoodsOne(map.get("fireSiteType1"));
        fireStatisticsPo.setFireGoodsTwo(map.get("fireSiteType2"));
        fireStatisticsPo.setNature(map.get("useCharacterName"));
        return fireStatisticsPo;
    }


    private static Map<String, String> convertObjectToMap(Object obj) {
        return Arrays.stream(BeanUtils.getPropertyDescriptors(obj.getClass()))
                .filter(pd -> !"class".equals(pd.getName()))
                .collect(HashMap::new,
                        (map, pd) -> {
                            if (ReflectionUtils.invokeMethod(pd.getReadMethod(), obj) != null) {
                                map.put(pd.getName(), String.valueOf(ReflectionUtils.invokeMethod(pd.getReadMethod(), obj)));
                            }
                        },
                        HashMap::putAll);
    }
}
