package com.zehong.system.service.impl;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.zehong.common.core.domain.model.LoginUser;
import com.zehong.common.core.page.PageDomain;
import com.zehong.common.core.page.TableDataInfo;
import com.zehong.common.core.page.TableSupport;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.system.domain.*;
import com.zehong.system.domain.dto.UserLinkGasBottleIdDTO;
import com.zehong.system.domain.dto.UserLinkGasBottleTitleDTO;
import com.zehong.system.domain.vo.*;
import com.zehong.system.mapper.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.zehong.system.service.ITDetectorUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * 燃气用户Service业务层处理
 *
 * @author zehong
 * @date 2022-02-07
 */
@Service
public class TDetectorUserServiceImpl implements ITDetectorUserService {
    @Resource
    private TDetectorUserMapper tDetectorUserMapper;
    @Resource
    private TDeviceInfoMapper tDeviceInfoMapper;
    @Resource
    private TSiteStationInfoMapper tSiteStationInfoMapper;
    @Resource
    private TGasuserSafetyDeviceInfoMapper gasuserSafetyDeviceInfoMapper;
    @Resource
    private TEnterpriseInfoMapper tEnterpriseInfoMapper;

    @Resource
    private TUserManageVillageMapper villageMapper;

    @Resource
    private TDetectorUserErrorMapper tDetectorUserErrorMapper;

    @Resource
    private DataSource dataSource;

    /**
     * 气瓶档案
     */
    @Resource
    private TLpgGasBottleFilesMapper lpgGasBottleFilesMapper;

    /**
     * 重装记录
     */
    @Resource
    private TLpgAirChargeFilesMapper lpgAirChargeFilesMapper;

    /**
     * 配送记录
     */
    @Resource
    private TLpgDeliveryRecordMapper tLpgDeliveryRecordMapper;

    /**
     * 查询探测器用户列表
     *
     * @return 探测器用户
     */
    @Override
    public List<TDetectorUserVO> detectorUserList(TDetectorUser tDetectorUser) {
        long startTime = System.currentTimeMillis();
        List<TDetectorUserVO> list = new ArrayList<>();
        List<TDetectorUserVO> tDetectorUserList = tDetectorUserMapper.countTDetectorUser(tDetectorUser);

        Map<Long, List<TDetectorUserVO>> collect = tDetectorUserList.stream().collect(Collectors.groupingBy(TDetectorUserVO::getUserId));

        for (Map.Entry<Long, List<TDetectorUserVO>> longListEntry : collect.entrySet()) {
            List<Object> initList = new ArrayList<>();
            List<TDetectorUserVO> value = longListEntry.getValue();
            if (value.size() > 0) {
                TDetectorUserVO userVO = new TDetectorUserVO();
                BeanUtils.copyProperties(value.get(0), userVO);
                for (TDetectorUserVO tDetectorUserVO : value) {
                    // 如果设备数量为0 则不显示
                    if (tDetectorUserVO.getDetectorCount() == 0) {
                        continue;
                    }
                    initList.add(tDetectorUserVO);
                }
                userVO.setDetectorCountList(initList);
                list.add(userVO);
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("detectorUserList = " + (end - startTime));
        return list;
    }


    /**
     * 查询探测器用户列表 地图使用 LabelMarker 标注的方式
     *
     * @param tDetectorUser tDetectorUser
     * @return r
     */
    @Override
    public List<TDetectorUserVO> massMarksDetectorUserList(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.countTDetectorUserForMassMarks(tDetectorUser);
    }

    /**
     * po 转 map
     *
     * @param obj o
     * @return r
     */
    public static Map<String, Object> toMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    /**
     * 查询探测器用户列表 地图使用 labelsLayerMarks 标注的方式
     *
     * @param tDetectorUser tDetectorUser
     * @return r
     */
    @Override
    public Map<String, List<TDetectorUserVO>> labelsLayerMarksDetectorUserList(TDetectorUser tDetectorUser) {

        Map<String, List<TDetectorUserVO>> collect;
        List<TDetectorUserVO> list = new ArrayList<>();
        List<TDetectorUserVO> tDetectorUserList = tDetectorUserMapper.countTDetectorUser(tDetectorUser);

        if (tDetectorUserList.size() > 0) {
            for (TDetectorUserVO user : tDetectorUserList) {
                TDetectorUserVO userVO = new TDetectorUserVO();
                BeanUtils.copyProperties(user, userVO);

                List<Object> newList = new ArrayList<>();
                newList.add(user);
                userVO.setDetectorCountList(newList);

                if ("1".equals(userVO.getUserType())) {
                    userVO.setIconType("6");
                } else if ("2".equals(userVO.getUserType())) {
                    userVO.setIconType("61");
                } else if ("3".equals(userVO.getUserType())) {
                    userVO.setIconType("62");
                } else if ("4".equals(userVO.getUserType())) {
                    userVO.setIconType("18");
                }
                list.add(userVO);
            }
            collect = list.stream().collect(Collectors.groupingBy(TDetectorUserVO::getIconType));
        } else {
            collect = new HashMap<>(0);
        }

        return collect;
    }

    /**
     * 根据气瓶条码查询 气瓶详情和 气瓶追溯
     *
     * @param code r
     * @return r
     */
    @Override
    public LpgGasBottleFilesBackToVo getLpgGasBottleFilesBackToByCode(String code) {

        LpgGasBottleFilesBackToVo lpgGasBottleFilesBackToVo = new LpgGasBottleFilesBackToVo();
        List<String> strings = Collections.singletonList(code);
        List<TLpgGasBottleFiles> lpgGasBottleFiles = lpgGasBottleFilesMapper.queryAllByFQRcodeList(strings);
        if (lpgGasBottleFiles != null && lpgGasBottleFiles.size() > 0) {
            TLpgGasBottleFiles tLpgGasBottleFiles = lpgGasBottleFiles.get(0);
            BeanUtils.copyProperties(tLpgGasBottleFiles, lpgGasBottleFilesBackToVo);
        }

        //最后两次的充装记录
        List<TLpgAirChargeFiles> lpgAirChargeFiles = lpgAirChargeFilesMapper.queryAllByBarCodeLimit2(code);

        //最后两次的配送记录
        List<TLpgDeliveryRecord> lpgDeliveryRecords = tLpgDeliveryRecordMapper.queryAllByBottleCodeLimit2(code);

        List<Map<String, Object>> backToMessage = new ArrayList<>();


        StringBuilder sb = new StringBuilder();
        Map<String, Object> map = new HashMap<>();
        if (lpgAirChargeFiles.size() > 0) {
            TLpgAirChargeFiles tLpgAirChargeFiles = lpgAirChargeFiles.get(0);
            map.put("time", tLpgAirChargeFiles.getFillEndTime());
            map.put("title", "充装记录");
            sb.append("由充装单位为【").append(tLpgAirChargeFiles.getStationName()).append("】完成充装");
            map.put("message", sb.toString());
            backToMessage.add(map);

            if (lpgAirChargeFiles.size() > 1) {
                TLpgAirChargeFiles tLpgAirChargeFiles1 = lpgAirChargeFiles.get(1);
                map = new HashMap<>();
                sb = new StringBuilder();
                map.put("time", tLpgAirChargeFiles1.getFillEndTime());
                map.put("title", "充装记录");
                sb.append("由充装单位为【").append(tLpgAirChargeFiles1.getStationName()).append("】完成充装");
                map.put("message", sb.toString());
                backToMessage.add(map);
            }
        }

        if (lpgDeliveryRecords.size() > 0) {

            map = new HashMap<>();
            sb = new StringBuilder();

            TLpgDeliveryRecord lpgDeliveryRecord = lpgDeliveryRecords.get(0);
            map.put("time", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, lpgDeliveryRecord.getDeliveryDate()));
            map.put("title", "配送记录");
            sb.append("由配送人员【").append(lpgDeliveryRecord.getDeliveryPerson()).append("】完成配送");
            map.put("message", sb.toString());
            backToMessage.add(map);

            if (lpgDeliveryRecords.size() > 1) {

                map = new HashMap<>();
                sb = new StringBuilder();

                TLpgDeliveryRecord lpgDeliveryRecord1 = lpgDeliveryRecords.get(1);
                map.put("time", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, lpgDeliveryRecord1.getDeliveryDate()));
                map.put("title", "配送记录");
                sb.append("由配送人员【").append(lpgDeliveryRecord1.getDeliveryPerson()).append("】完成配送");
                map.put("message", sb.toString());
                backToMessage.add(map);
            }

        }

//        backToMessage.sort(Comparator.comparing((Map<String, Object> mapitem) -> (Date) mapitem.get("time")).reversed());
        backToMessage.sort((a, b) -> DateUtil.parse(a.get("time").toString()).getTime() - DateUtil.parse(b.get("time").toString()).getTime() >= 0 ? -1 : 1);

        lpgGasBottleFilesBackToVo.setBackToMessage(backToMessage);
        return lpgGasBottleFilesBackToVo;
    }

    /**
     * 获取探测器用户列表 大屏地图 labelsLayer 标注的方式 分页查询 居民用户
     *
     * @param tDetectorUser t
     * @return r
     */
    @Override
    public TableDataInfo pageQueryLabelsLayerMarksDUser(TDetectorUser tDetectorUser) {

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();

        TableDataInfo tableDataInfo = new TableDataInfo();

        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");

        if (tDetectorUser.getVillageId() == null) {
            return tableDataInfo;
        }

        List<TDetectorUserVillageSafetyDeviceInfoVo> tDetectorUserVillageSafetyDeviceInfoVos = tDetectorUserMapper.queryDuserVilSafDevInfoOnlyResidentsInit(tDetectorUser);

        // 数据封装
        List<Map<String, Object>> maps = residentsUserInitForPage(tDetectorUserVillageSafetyDeviceInfoVos);

        if (maps.size() > 0) {

            List<Map<String, Object>> newList = new ArrayList<>();

            int total = maps.size();
            tableDataInfo.setTotal(total);

            // 开始索引  手动分页
            int fromIndex = (pageNum - 1) * pageSize;
            // 结束索引
            int toIndex = fromIndex + pageSize;
            // 如果结束索引大于集合的最大索引，那么规定结束索引=集合大小
            toIndex = Math.min(toIndex, total);

            newList = fromIndex > total ? newList : maps.subList(fromIndex, toIndex);

            tableDataInfo.setRows(newList);
            return tableDataInfo;
        }

        return tableDataInfo;
    }

    /**
     * 查询探测器用户列表 地图使用 labelsLayerMarks 标注的方式
     *
     * @param tDetectorUser tDetectorUser
     * @return r
     */
    @Override
    public Map<Object, List<Map<String, Object>>> labelsLayerMarksDUserVillageSafDevInfoMap(TDetectorUser tDetectorUser) {

        long start = System.currentTimeMillis();

        Map<Object, List<Map<String, Object>>> collect = new HashMap<>();

        // 20240904 居民用户特殊处理，带有 村 和 安全装置的概念

        //居民用户处理
        List<Map<String, Object>> list = tDetectorUserMapper.queryDuserVilSafDevInfoOnlyResidents(tDetectorUser);

        List<Map<String, Object>> userMapList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            map.put("userMapList",userMapList);
        }
        if (list.size() > 0) {
            collect.put("6", list);
        } else {
            collect.put("6", new ArrayList<>());
        }

        // ， 工商业用户 和 餐饮用户 带有 安全装置概念
        List<TDetectorUserVillageSafetyDeviceInfoVo> tDetectorUserVillageSafetyDeviceInfoVos = tDetectorUserMapper.queryDuserVilSafDevInfo(tDetectorUser);

        if (tDetectorUserVillageSafetyDeviceInfoVos.size() > 0) {

            // 工商业用户 和 餐饮用户
            Map<String, List<Map<String, Object>>> stringListMap = noResidentsUserInit(tDetectorUserVillageSafetyDeviceInfoVos);

            if (stringListMap.size() > 0) {
                // 工商业用户
                List<Map<String, Object>> maps = stringListMap.get("2");

                if (maps != null && maps.size() > 0) {
                    collect.put("61", maps);
                } else {
                    collect.put("61", new ArrayList<>());
                }

                // 餐饮用户
                List<Map<String, Object>> maps1 = stringListMap.get("4");
                if (maps1 != null && maps1.size() > 0) {
                    collect.put("18", maps1);
                } else {
                    collect.put("18", new ArrayList<>());
                }
            }
        } else {
            collect = new HashMap<>(0);
        }
        long end = System.currentTimeMillis();

        long jiange = end - start;

        System.out.println("jiange ===" + jiange);

        return collect;
    }

    /**
     * 居民用户 处理方式封装
     *
     * @param noResidentsUsers no
     * @return m
     */
    private Map<String, List<Map<String, Object>>> noResidentsUserInit(List<TDetectorUserVillageSafetyDeviceInfoVo> noResidentsUsers) {
        Map<String, List<Map<String, Object>>> collect = new HashMap<>();

        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 按照用户类型分组
        Map<String, List<TDetectorUserVillageSafetyDeviceInfoVo>> collectByType = noResidentsUsers.stream()
                .collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getUserType));


        for (Map.Entry<String, List<TDetectorUserVillageSafetyDeviceInfoVo>> stringListEntry : collectByType.entrySet()) {
            String key = stringListEntry.getKey();
            List<Map<String, Object>> userList = new ArrayList<>();

            collect.put(key, userList);
            List<TDetectorUserVillageSafetyDeviceInfoVo> value = stringListEntry.getValue();

            // 按照 userId 分组
            Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect1 = value.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getUserId));

            for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> longListEntry : collect1.entrySet()) {

                List<TDetectorUserVillageSafetyDeviceInfoVo> value1 = longListEntry.getValue();

                // 过滤掉 没有装置的
                List<TDetectorUserVillageSafetyDeviceInfoVo> collect2 = value1.stream().filter(item -> item.getGasUserSafetyDeviceId() == null).collect(Collectors.toList());

                // 没有装置的 直接 封装用户数据
                if (collect2.size() > 0) {
                    for (TDetectorUserVillageSafetyDeviceInfoVo tDetectorUserVillageSafetyDeviceInfoVo : collect2) {
                        List<Map<String, Object>> safetyDeviceMapList = new ArrayList<>();
                        Map<String, Object> userListItem = new HashMap<>();
                        userListItem.put("userId", tDetectorUserVillageSafetyDeviceInfoVo.getUserId());
                        userListItem.put("nickName", tDetectorUserVillageSafetyDeviceInfoVo.getNickName());
                        userListItem.put("phone", tDetectorUserVillageSafetyDeviceInfoVo.getPhone());
                        userListItem.put("address", tDetectorUserVillageSafetyDeviceInfoVo.getAddress());
                        userListItem.put("longitude", tDetectorUserVillageSafetyDeviceInfoVo.getUserLongitude());
                        userListItem.put("gasType", tDetectorUserVillageSafetyDeviceInfoVo.getGasType());
                        userListItem.put("latitude", tDetectorUserVillageSafetyDeviceInfoVo.getUserLatitude());
                        if ("2".equals(tDetectorUserVillageSafetyDeviceInfoVo.getUserType())) {
                            userListItem.put("iconType", "61");
                        } else if ("4".equals(tDetectorUserVillageSafetyDeviceInfoVo.getUserType())) {
                            userListItem.put("iconType", "18");
                        }
                        userListItem.put("safetyDeviceList", safetyDeviceMapList);
                        userList.add(userListItem);
                    }
                }

                // 过滤掉 有装置的
                List<TDetectorUserVillageSafetyDeviceInfoVo> collect3 = value1.stream().filter(item -> item.getGasUserSafetyDeviceId() != null).collect(Collectors.toList());

                if (collect3.size() > 0) {

                    Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect4 = collect3.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getGasUserSafetyDeviceId));
                    for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> listEntry : collect4.entrySet()) {

                        List<TDetectorUserVillageSafetyDeviceInfoVo> value2 = listEntry.getValue();

                        List<Map<String, Object>> safetyDeviceMapList = new ArrayList<>();
                        Map<String, Object> userListItem = new HashMap<>();
                        userListItem.put("userId", value2.get(0).getUserId());
                        userListItem.put("nickName", value2.get(0).getNickName() == null ? "" : value2.get(0).getNickName());
                        userListItem.put("phone", value2.get(0).getPhone() == null ? "" : value2.get(0).getPhone());
                        userListItem.put("address", value2.get(0).getAddress() == null ? "" : value2.get(0).getAddress());
                        userListItem.put("longitude", value2.get(0).getUserLongitude() == null ? "" : value2.get(0).getUserLongitude());
                        userListItem.put("latitude", value2.get(0).getUserLatitude() == null ? "" : value2.get(0).getUserLatitude());
                        userListItem.put("gasType", value2.get(0).getGasType() == null ? "" : value2.get(0).getGasType());
                        if (value2.get(0).getUserType() != null && "2".equals(value2.get(0).getUserType())) {
                            userListItem.put("iconType", "61");
                        } else if (value2.get(0).getUserType() != null && "4".equals(value2.get(0).getUserType())) {
                            userListItem.put("iconType", "18");
                        }
                        userListItem.put("safetyDeviceList", safetyDeviceMapList);
                        userList.add(userListItem);

                        for (TDetectorUserVillageSafetyDeviceInfoVo tDetectorUserVillageSafetyDeviceInfoVo : value2) {
                            //封装 设备信息
                            Map<String, Object> safetyDeviceMapItem = new HashMap<>();
                            safetyDeviceMapItem.put("gasUserSafetyDeviceId", tDetectorUserVillageSafetyDeviceInfoVo.getGasUserSafetyDeviceId());
                            safetyDeviceMapItem.put("iotNo", tDetectorUserVillageSafetyDeviceInfoVo.getIotNo());
                            safetyDeviceMapItem.put("deviceName", tDetectorUserVillageSafetyDeviceInfoVo.getDeviceName());
                            safetyDeviceMapItem.put("detctionMedium", tDetectorUserVillageSafetyDeviceInfoVo.getDetctionMedium());
                            safetyDeviceMapItem.put("deviceInstallTime", tDetectorUserVillageSafetyDeviceInfoVo.getDeviceInstallTime());
                            if (tDetectorUserVillageSafetyDeviceInfoVo.getDeviceInstallTime() != null) {
                                String format = targetFormat.format(tDetectorUserVillageSafetyDeviceInfoVo.getDeviceInstallTime());
                                safetyDeviceMapItem.put("deviceInstallTime", format);
                            } else {
                                safetyDeviceMapItem.put("deviceInstallTime", "");
                            }
                            safetyDeviceMapList.add(safetyDeviceMapItem);
                        }
                    }
                }
            }
        }
        return collect;
    }

    /**
     * 居民用户 处理方式封装 提供分压查询功能了。
     *
     * @param residentsUsers r
     * @return m
     */
    private List<Map<String, Object>> residentsUserInitForPage(List<TDetectorUserVillageSafetyDeviceInfoVo> residentsUsers) {

        //返回 userlist
        List<Map<String, Object>> userMapList = new ArrayList<>();

        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (residentsUsers.size() > 0) {

            // 如果没关联村的就不展示了
            List<TDetectorUserVillageSafetyDeviceInfoVo> collect = residentsUsers.stream().filter(item -> item.getVillageId() != null).collect(Collectors.toList());

            //按照 村id 分组
            Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect1 = collect.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getVillageId));

            // 查询气瓶信息
            List<Long> collect5 = collect.stream().map(TDetectorUserVillageSafetyDeviceInfoVo::getVillageId).collect(Collectors.toList());
            List<UserLinkGasBottleTitleDTO> userLinkGasBottleTitleDTOS = tDetectorUserMapper.queryUserIdLinkGasBottleTitleByVillageIds(collect5);
            Map<Long, List<UserLinkGasBottleTitleDTO>> collect6 = userLinkGasBottleTitleDTOS.stream().collect(Collectors.groupingBy(UserLinkGasBottleTitleDTO::getUserId));

            for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> longListEntry : collect1.entrySet()) {
                List<TDetectorUserVillageSafetyDeviceInfoVo> villageList = longListEntry.getValue();

                int userNum = 0;
                int deviceNum = 0;
                // 按照 用户 分组
                Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect2 = villageList.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getUserId));

                if (collect2.size() > 0) {
                    // 拿到用户数，并组装用户数据
                    userNum = collect2.size();

                    for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> listEntry : collect2.entrySet()) {

                        List<Map<String, Object>> safetyDeviceMapList = new ArrayList<>();
                        List<String> gasBottleTitleList = new ArrayList<>();

                        List<TDetectorUserVillageSafetyDeviceInfoVo> userList = listEntry.getValue();
                        Long key = listEntry.getKey();

                        // 封装用户数
                        Map<String, Object> userMapListItme = new HashMap<>();
                        userMapListItme.put("userId", key);
                        userMapListItme.put("nickName", userList.get(0).getNickName() == null ? "" : userList.get(0).getNickName());
                        userMapListItme.put("phone", userList.get(0).getPhone() == null ? "" : userList.get(0).getPhone());
                        userMapListItme.put("address", userList.get(0).getAddress() == null ? "" : userList.get(0).getAddress());
                        userMapListItme.put("safetyDeviceList", safetyDeviceMapList);

                        // 过滤掉 没有 安全装置的
                        List<TDetectorUserVillageSafetyDeviceInfoVo> collect4 = userList.stream().filter(item -> item.getGasUserSafetyDeviceId() != null).collect(Collectors.toList());

                        // 按照 安全装置 分组
                        Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect3 = collect4.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getGasUserSafetyDeviceId));

                        if (collect3.size() > 0) {
                            // 拿到每个 用户下 安全装置 数 相加。
                            deviceNum += collect3.size();

                            for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> entry : collect3.entrySet()) {

                                List<TDetectorUserVillageSafetyDeviceInfoVo> safetyDeviceInfoList = entry.getValue();

                                if (safetyDeviceInfoList.size() > 0) {
                                    for (TDetectorUserVillageSafetyDeviceInfoVo tDetectorUserVillageSafetyDeviceInfoVo : safetyDeviceInfoList) {
                                        //封装 设备信息
                                        Map<String, Object> safetyDeviceMapItem = new HashMap<>();
                                        safetyDeviceMapItem.put("gasUserSafetyDeviceId", tDetectorUserVillageSafetyDeviceInfoVo.getGasUserSafetyDeviceId());
                                        safetyDeviceMapItem.put("iotNo", tDetectorUserVillageSafetyDeviceInfoVo.getIotNo());
                                        safetyDeviceMapItem.put("deviceName", tDetectorUserVillageSafetyDeviceInfoVo.getDeviceName());
                                        safetyDeviceMapItem.put("detctionMedium", tDetectorUserVillageSafetyDeviceInfoVo.getDetctionMedium());
                                        if (tDetectorUserVillageSafetyDeviceInfoVo.getDeviceInstallTime() != null) {
                                            String format = targetFormat.format(tDetectorUserVillageSafetyDeviceInfoVo.getDeviceInstallTime());
                                            safetyDeviceMapItem.put("deviceInstallTime", format);
                                        } else {
                                            safetyDeviceMapItem.put("deviceInstallTime", "");
                                        }
                                        safetyDeviceMapList.add(safetyDeviceMapItem);
                                    }
                                }
                            }
                        }

                        // 封装 气瓶条码，只是气瓶条码，然后点击条码再查询详细数据
                        userMapListItme.put("gasBottleTitleList", gasBottleTitleList);
                        List<UserLinkGasBottleTitleDTO> userLinkGasBottleTitleDTOS1 = collect6.get(key);
                        if (userLinkGasBottleTitleDTOS1 != null && userLinkGasBottleTitleDTOS1.size() > 0) {
                            List<String> collect7 = userLinkGasBottleTitleDTOS1.stream().map(UserLinkGasBottleTitleDTO::getrCode).collect(Collectors.toList());
                            List<Map<String, Object>> gasBottleTitleMapList = new ArrayList<>();
                            if (collect7.size() > 0) {
                                for (String s : collect7) {
                                    Map<String, Object> map = new HashMap<>();
                                    if (StringUtils.isNotBlank(s)) {
                                        map.put("code", s);
                                        gasBottleTitleMapList.add(map);
                                    }
                                }
                            }
                            userMapListItme.put("gasBottleTitleList", gasBottleTitleMapList);
                        }
                        userMapList.add(userMapListItme);
                    }
                }
            }
        }
        return userMapList;
    }

    /**
     * 居民用户 处理方式封装
     *
     * @param residentsUsers r
     * @return m
     */
    private List<Map<String, Object>> residentsUserInit(List<TDetectorUserVillageSafetyDeviceInfoVo> residentsUsers) {

        //遍历 村 集合
        List<Map<String, Object>> villageMapList = new ArrayList<>();
        if (residentsUsers.size() > 0) {

            // 如果没关联村的就不展示了
            List<TDetectorUserVillageSafetyDeviceInfoVo> collect = residentsUsers.stream().filter(item -> item.getVillageId() != null).collect(Collectors.toList());

            // 村没有经纬度的就不展示了
            List<TDetectorUserVillageSafetyDeviceInfoVo> collect5 = collect.stream().filter(item -> item.getLatitude() != null && item.getLongitude() != null).collect(Collectors.toList());

            //按照 村id 分组
            Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect1 = collect5.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getVillageId));

            // 统计气瓶数量
            List<Long> collect6 = collect5.stream().map(TDetectorUserVillageSafetyDeviceInfoVo::getVillageId).collect(Collectors.toList());
            List<UserLinkGasBottleIdDTO> userLinkGasBottleIdDTOS = tDetectorUserMapper.queryUserIdLinkGasBottleIdByVillageIds(collect6);
            Map<Long, List<UserLinkGasBottleIdDTO>> collect7 = userLinkGasBottleIdDTOS.stream().collect(Collectors.groupingBy(UserLinkGasBottleIdDTO::getVillageId));

            for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> longListEntry : collect1.entrySet()) {
                List<TDetectorUserVillageSafetyDeviceInfoVo> villageList = longListEntry.getValue();
                Long key1 = longListEntry.getKey();
                // 封装 村数据
                Map<String, Object> villageMapListItem = new HashMap<>();
                villageMapListItem.put("villageId", key1);
                villageMapListItem.put("villageName", villageList.get(0).getVillageName());
                villageMapListItem.put("address", villageList.get(0).getRegionName());
                villageMapListItem.put("longitude", villageList.get(0).getLongitude());
                villageMapListItem.put("latitude", villageList.get(0).getLatitude());
                villageMapListItem.put("iconType", "6");

                int userNum = 0;
                int deviceNum = 0;
                // 按照 用户 分组
                Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect2 = villageList.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getUserId));

                List<Map<String, Object>> userMapList = new ArrayList<>();
                if (collect2.size() > 0) {
                    // 拿到用户数，并组装用户数据
                    userNum = collect2.size();

                    for (Map.Entry<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> listEntry : collect2.entrySet()) {
                        List<TDetectorUserVillageSafetyDeviceInfoVo> userList = listEntry.getValue();

                        // 过滤掉 没有 安全装置的
                        List<TDetectorUserVillageSafetyDeviceInfoVo> collect4 = userList.stream().filter(item -> item.getGasUserSafetyDeviceId() != null).collect(Collectors.toList());

                        // 按照 安全装置 分组
                        Map<Long, List<TDetectorUserVillageSafetyDeviceInfoVo>> collect3 = collect4.stream().collect(Collectors.groupingBy(TDetectorUserVillageSafetyDeviceInfoVo::getGasUserSafetyDeviceId));

                        if (collect3.size() > 0) {
                            // 拿到每个 用户下 安全装置 数 相加。
                            deviceNum += collect3.size();
                        }
                    }
                }

                villageMapListItem.put("userNum", userNum);
                villageMapListItem.put("deviceNum", deviceNum);
                villageMapListItem.put("userMapList", userMapList);
                List<UserLinkGasBottleIdDTO> userLinkGasBottleIdDTOS1 = collect7.get(key1);
                if (userLinkGasBottleIdDTOS1 != null && userLinkGasBottleIdDTOS1.size() > 0) {
                    villageMapListItem.put("gasBottle", userLinkGasBottleIdDTOS1.size());
                } else {
                    villageMapListItem.put("gasBottle", 0);
                }
                villageMapList.add(villageMapListItem);
            }
        }

        return villageMapList;
    }

    /**
     * 查询探测器用户列表 地图使用 massMarks 标注的方式
     * @param tDetectorUser tDetectorUser
     * @return r
     */
/*
    @Override
    public Map<String, List<TMassMarksDetectorUserVO>> massMarksDetectorUserList(TDetectorUser tDetectorUser) {
        List<TDetectorUserVO> tDetectorUserList = tDetectorUserMapper.countTDetectorUserForMassMarks(tDetectorUser);
        Map<String, List<TMassMarksDetectorUserVO>> collect ;
        if (tDetectorUserList.size() > 0) {

            List<TMassMarksDetectorUserVO> massMarksDetectorUsers = new ArrayList<>();

            TMassMarksDetectorUserVO massMarksDetectorUser;
            for(TDetectorUserVO user : tDetectorUserList){

                BigDecimal longitude = user.getLongitude();
                BigDecimal latitude = user.getLatitude();

                BigDecimal[] lnglat = new BigDecimal[2];
                lnglat[1] = latitude;
                lnglat[0] = longitude;
                massMarksDetectorUser = new TMassMarksDetectorUserVO();
                lnglat[1] = latitude;
                lnglat[0] = longitude;
                massMarksDetectorUser.setLnglat(lnglat);
                if ("1".equals(user.getUserType())) {
                    massMarksDetectorUser.setIconType("6");
                } else if ("2".equals(user.getUserType())) {
                    massMarksDetectorUser.setIconType("61");
                }
                massMarksDetectorUser.setStyle(2);
                massMarksDetectorUsers.add(massMarksDetectorUser);
            }
            collect = massMarksDetectorUsers.stream().collect(Collectors.groupingBy(TMassMarksDetectorUserVO::getIconType));
        } else {
            collect = new HashMap<>();
        }
        return collect;
    }
*/


    /**
     * 查询探测器报警用户（前台调用）
     *
     * @return 探测器用户
     */
    @Override
    public List<Map> getDetectorUserAlarmList() {
        List<Map> list = new ArrayList<>();

        // 查询报警用户
        List<Map> userList = tDetectorUserMapper.getDetectorUserAlarmList();
        for (Map map : userList) {
            map.put("iconType", "6");
            list.add(map);
        }
        // 查询报警设备
        List<Map> infoList = tDeviceInfoMapper.getDeviceInfoAlarmList();
        for (Map map : infoList) {
            // deviceType：1阀门井 2调压箱
            if (map.get("deviceType").equals("1")) {
                map.put("iconType", "3");
            } else if (map.get("deviceType").equals("2")) {
                map.put("iconType", "2");
            }
            list.add(map);
        }
        // 查询报警场站
        List<Map> stationList = tSiteStationInfoMapper.getSiteStationAlarmList();
        for (Map map : stationList) {
            map.put("iconType", "4");
            list.add(map);
        }

        return list;
    }

    /**
     * 查询探测器报警用户（后台推送）
     *
     * @param tDetectorUser 探测器用户
     * @return 探测器用户
     */
    @Override
    public List<TDetectorUserVO> detectorUserAlarmList(TDetectorUser tDetectorUser) {
        List<TDetectorUserVO> list = new ArrayList<>();
        List<TDetectorUserVO> tDetectorUserList = tDetectorUserMapper.countTDetectorUser(tDetectorUser);

        List<Object> initList = new ArrayList<>();
        for (TDetectorUserVO user : tDetectorUserList) {
            TDetectorUserVO userVO = new TDetectorUserVO();
            BeanUtils.copyProperties(user, userVO);
            initList.add(userVO);
            userVO.setDetectorCountList(initList);

            list.add(user);
        }

        return list;
    }

    /**
     * 泽宏云推送查询燃气用户
     *
     * @param tDetectorUser 燃气用户
     * @return 燃气用户
     */
    @Override
    public List<TDetectorUser> selectTDetectorUser(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.selectTDetectorUser(tDetectorUser);
    }

    /**
     * 查询燃气用户
     *
     * @param userId 燃气用户ID
     * @return 燃气用户
     */
    @Override
    public TDetectorUser selectTDetectorUserById(Long userId) {
        return tDetectorUserMapper.selectTDetectorUserById(userId);
    }

    /**
     * 查询燃气用户列表
     *
     * @param tDetectorUser 燃气用户
     * @return 燃气用户
     */
    @Override
    public List<TDetectorUser> selectTDetectorUserList(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.selectTDetectorUserList(tDetectorUser);
    }

    /**
     * 查询导入的错误数据
     *
     * @return r
     */
    @Override
    public List<TDetectorUser> queryErrorDetectorUserList(String gasType) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String deptId = loginUser.getUser().getDeptId();

        return tDetectorUserMapper.queryErrorDetectorUserList(deptId, gasType);
    }

    @Override
    public List<TDetectorUser> queryByUserOwnIdAndEnterpriseIdForThirdParty(List<String> userOwnIds, String enterpriseId) {
        return tDetectorUserMapper.queryByUserOwnIdAndEnterpriseIdForThirdParty(userOwnIds, enterpriseId);
    }

    /**
     * 根据userOwnIds 和  enterpriseId 查询数据
     *
     * @param userOwnIds   u
     * @param enterpriseId e
     * @return r
     */
    @Override
    public List<TDetectorUser> queryByUserOwnIdsAndEnterpriseId(List<String> userOwnIds, String enterpriseId) {
        return tDetectorUserMapper.queryByUserOwnIdsAndEnterpriseId(userOwnIds, enterpriseId);
    }

    /**
     * 查询燃气用户列表-new
     *
     * @param tDetectorUser 燃气用户
     * @return 燃气用户
     */
    @Override
    public List<TDetectorUser> newSelectTDetectorUserList(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.newSelectTDetectorUserList(tDetectorUser);
    }

    /**
     * 查询燃气用户列表 - 导出使用
     *
     * @param tDetectorUser t
     * @return r
     */
    @Override
    public List<TDetectorUser> selectForExportTDetectorUserList(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.selectForExportTDetectorUserList(tDetectorUser);
    }

    @Override
    public List<TDetectorUser> selectTDetectorListstatus(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.selectTDetectorListstatus(tDetectorUser);
    }

    /**
     * 新增燃气用户
     *
     * @param tDetectorUser 燃气用户
     * @return 结果
     */
    @Override
    public int insertTDetectorUser(TDetectorUser tDetectorUser) {
        return tDetectorUserMapper.insertTDetectorUser(tDetectorUser);
    }

    @Override
    public int insertBatchSafetyDevice(List<TGasuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList) {
        return gasuserSafetyDeviceInfoMapper.insertBatch(gasuserSafetyDeviceInfoList);
    }

    /**
     * 批量插入 第三方传输来的数据
     *
     * @param tYehuaqiUsers r
     * @return r
     */
    @Override
    public int insertBatchForThirdParty(List<TDetectorUser> tYehuaqiUsers) {
        return tDetectorUserMapper.insertBatchForThirdParty(tYehuaqiUsers);
    }

    /**
     * 新增燃气用户 和 安全装置
     *
     * @param gasUserAndSafetyDeviceVo gas
     * @return r
     */
    @Override
    public int addUserAndSafetyDevice(GasUserAndSafetyDeviceVo gasUserAndSafetyDeviceVo) {

        TDetectorUser detectorUser = gasUserAndSafetyDeviceVo.getDetectorUser();
        tDetectorUserMapper.insertTDetectorUser(detectorUser);
        List<TGasuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList = gasUserAndSafetyDeviceVo.getGasuserSafetyDeviceInfoList();
        if (gasuserSafetyDeviceInfoList != null && gasuserSafetyDeviceInfoList.size() > 0) {
            for (TGasuserSafetyDeviceInfo tGasuserSafetyDeviceInfo : gasuserSafetyDeviceInfoList) {
                tGasuserSafetyDeviceInfo.setRelationGasuserId(detectorUser.getUserId());
            }
            gasuserSafetyDeviceInfoMapper.insertBatch(gasuserSafetyDeviceInfoList);
        }
        return 1;
    }

    /**
     * 修改燃气用户 和 安全装置
     *
     * @param gasUserAndSafetyDeviceVo gas
     * @return r
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserAndSafetyDevice(GasUserAndSafetyDeviceVo gasUserAndSafetyDeviceVo) {

        TDetectorUser detectorUser = gasUserAndSafetyDeviceVo.getDetectorUser();
        tDetectorUserMapper.updateTDetectorUser(detectorUser);
        List<TGasuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList = gasUserAndSafetyDeviceVo.getGasuserSafetyDeviceInfoList();
        if (gasuserSafetyDeviceInfoList != null && gasuserSafetyDeviceInfoList.size() > 0) {
            for (TGasuserSafetyDeviceInfo tGasuserSafetyDeviceInfo : gasuserSafetyDeviceInfoList) {
                tGasuserSafetyDeviceInfo.setRelationGasuserId(detectorUser.getUserId());
            }
        }

        gasuserSafetyDeviceInfoMapper.deleteTGasuserSafetyDeviceInfoByUserId(detectorUser.getUserId());
        if (gasuserSafetyDeviceInfoList != null && gasuserSafetyDeviceInfoList.size() > 0) {
            gasuserSafetyDeviceInfoMapper.insertBatch(gasuserSafetyDeviceInfoList);
        }
        return 1;
    }

    /**
     * 批量修改
     *
     * @param list l
     * @return r
     */
    @Override
    public int updateBatch(List<TDetectorUser> list) {
        return tDetectorUserMapper.updateBatch(list);
    }

    /**
     * 根据用户id 集合删除 安全装置
     *
     * @param userIds u
     * @return
     */
    @Override
    public int deleteBatchSafetyDeviceByUserIds(List<Long> userIds) {
        return gasuserSafetyDeviceInfoMapper.deleteBatchSafetyDeviceByUserIds(userIds);
    }

    /**
     * 修改燃气用户
     *
     * @param tDetectorUser 燃气用户
     * @return 结果
     */
    @Override
    public int updateTDetectorUser(TDetectorUser tDetectorUser) {
        tDetectorUser.setUpdateTime(DateUtils.getNowDate());
        return tDetectorUserMapper.updateTDetectorUser(tDetectorUser);
    }

    /**
     * 批量删除燃气用户
     *
     * @param userIds 需要删除的燃气用户ID
     * @return 结果
     */
    @Override
    public int deleteTDetectorUserByIds(Long[] userIds) {
        return tDetectorUserMapper.deleteTDetectorUserByIds(userIds);
    }

    /**
     * 删除燃气用户信息
     *
     * @param userId 燃气用户ID
     * @return 结果
     */
    @Override
    public int deleteTDetectorUserById(Long userId) {
        return tDetectorUserMapper.deleteTDetectorUserById(userId);
    }

    /**
     * 用户数量
     *
     * @return
     */
    public Map<String, Object> selectUserNum() {
        return tDetectorUserMapper.selectUserNum();
    }

    /**
     * 查询用户统计信息
     *
     * @return
     */
    @Override
    public TDetectorUserCount userStatistics(String id) {
        return tDetectorUserMapper.userStatistics(id);
    }

    /**
     * 获取用户安检信息
     *
     * @param inspectVo
     * @return
     */
    @Override
    public List<TDetectorUserInspectVo> getDetectorUserInspectInfo(TDetectorUserInspectVo inspectVo) {
        return tDetectorUserMapper.getDetectorUserInspectInfo(inspectVo);
    }

    /**
     * 燃气用户导入
     *
     * @param XmbhList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @param response
     * @return
     */
    @Override
    public String importEmployedPeopleInfo(List<UserManageGasUserExportVo> XmbhList, Boolean isUpdateSupport, String operName, HttpServletResponse response) {
        if (XmbhList.size() > 0) {
            for (UserManageGasUserExportVo userManageGasUserExportVo : XmbhList) {
                System.out.println(userManageGasUserExportVo.getLinkman());
            }
        }

        return null;
    }

    /**
     * 处理解析好的 自定义模版的导入的数据
     *
     * @param dataInfos d
     */
    @Override
    public void handleCustomImportData(List<UserManageGasUserExportVo> dataInfos, boolean updateSupport) {

    }


    /**
     * 处理解析好的 自定义模版的导入的数据 多sheet
     *
     * @param gasUserExportVos            d 燃气用户数据
     * @param safetyDeviceExportVos       s 安全装置信息
     * @param reImportOfIncorrectDataFlag r 错误数据重新导入标志  true 表示错误数据重新导入
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleCustomMoreSheetImportData(List<UserManageGasUserExportVo> gasUserExportVos,
                                                List<UserManageSafetyDeviceExportVo> safetyDeviceExportVos,
                                                boolean updateSupport, boolean reImportOfIncorrectDataFlag, String gasType) {

        List<TDetectorUser> successDataList = new ArrayList<>();

        List<TDetectorUser> errorDataList = new ArrayList<>();

        // 安全装置 按照 用户自由id 分组
        Map<String, List<UserManageSafetyDeviceExportVo>> safetyDeviceList = null;

        if (gasUserExportVos.size() > 0) {
            if (safetyDeviceExportVos != null && safetyDeviceExportVos.size() > 0) {
                safetyDeviceList = safetyDeviceExportVos.stream().collect(Collectors.groupingBy(UserManageSafetyDeviceExportVo::getUserOwnId));
            }

            TDetectorUser tDetectorUserError;
            StringBuilder stringBuilder = new StringBuilder();
            for (UserManageGasUserExportVo gasUserExportVo : gasUserExportVos) {
                String userOwnId = gasUserExportVo.getUserOwnId();
                // 2024-10-26 基本信息的天然气用户 和 液化气监管的 液化气用户 用一张表
                gasUserExportVo.setGasType(gasType);
                String userType = gasUserExportVo.getUserType();
                String beyondEnterpriseName = gasUserExportVo.getBeyondEnterpriseName();
                String villageName = gasUserExportVo.getVillageName();

                if (!reImportOfIncorrectDataFlag) {

                    if (StringUtils.isBlank(userOwnId)) {
                        stringBuilder.append("用户自由id为空|");
                    }
                }

                if ((StringUtils.isNotBlank(userType))) {
                    if (!"1".equals(userType) && !"2".equals(userType) && !"3".equals(userType) && !"4".equals(userType)) {
                        stringBuilder.append("用户类型数据没按提示录入|");
                    }
                }

                if (StringUtils.isBlank(beyondEnterpriseName)) {
                    stringBuilder.append("所属企业为空|");
                } else {
                    List<TEnterpriseInfo> tEnterpriseInfos = tEnterpriseInfoMapper.selectTEnterpriseInfoByName(beyondEnterpriseName);
                    if (tEnterpriseInfos != null && tEnterpriseInfos.size() > 0) {
                        gasUserExportVo.setBeyondEnterpriseId(tEnterpriseInfos.get(0).getEnterpriseId());
                    } else {
                        stringBuilder.append("所属企业不存在|");
                    }
                }

                if (StringUtils.isBlank(villageName)) {
                    stringBuilder.append("居住区(村、庄)为空|");
                } else {
                    TUserManageVillage tUserManageVillage = new TUserManageVillage();
                    tUserManageVillage.setfVillageName(villageName);
                    List<TUserManageVillage> tUserManageVillages = villageMapper.selectTUserManageVillageList(tUserManageVillage);
                    if (tUserManageVillages == null || tUserManageVillages.size() == 0) {
                        stringBuilder.append("居住区(村、庄)不存在|");
                    } else {
                        Long aLong = tUserManageVillages.get(0).getfVillageId();
                        gasUserExportVo.setVillageId(aLong);
                    }
                }

                //说明有错误数据
                if (StringUtils.isNotBlank(stringBuilder.toString())) {
                    tDetectorUserError = new TDetectorUser();

                    BeanUtils.copyProperties(gasUserExportVo, tDetectorUserError);

                    tDetectorUserError.setErrorMsg(stringBuilder.toString());
                    stringBuilder = new StringBuilder();
                    errorDataList.add(tDetectorUserError);
                    //正确数据
                } else {
                    TDetectorUser detectorUser = new TDetectorUser();
                    BeanUtils.copyProperties(gasUserExportVo, detectorUser);
                    successDataList.add(detectorUser);
                }
            }
        }

        //错误数据批量插入错误表
        if (errorDataList.size() > 0) {
            tDetectorUserMapper.insertBatch(errorDataList);
        }

        //正确数据插入后 生成id,再关联 安全装置
        if (successDataList.size() > 0) {

            //成功的数据里面如果有 userId，那说明是要修改的 要做区分
            List<TDetectorUser> addCollect = successDataList.stream().filter(item -> item.getUserId() == null).collect(Collectors.toList());
            if (addCollect.size() > 0) {
                tDetectorUserMapper.insertBatch(addCollect);
                if (safetyDeviceList != null && safetyDeviceList.size() > 0) {
                    List<TGasuserSafetyDeviceInfo> gasuserSafetyDeviceInfoList = new ArrayList<>();

                    //正确的 和 错误的 都是先出入 后 再统一处理 安全装置。
                    if (errorDataList.size() > 0) {
                        addCollect.addAll(errorDataList);
                    }
                    for (TDetectorUser detectorUser : addCollect) {
                        String userOwnId = detectorUser.getUserOwnId();
                        List<UserManageSafetyDeviceExportVo> userManageSafetyDeviceExportVos = safetyDeviceList.get(userOwnId);
                        if (userManageSafetyDeviceExportVos != null && userManageSafetyDeviceExportVos.size() > 0) {
                            TGasuserSafetyDeviceInfo gasuserSafetyDeviceInfo;
                            for (UserManageSafetyDeviceExportVo userManageSafetyDeviceExportVo : userManageSafetyDeviceExportVos) {
                                gasuserSafetyDeviceInfo = new TGasuserSafetyDeviceInfo();
                                BeanUtils.copyProperties(userManageSafetyDeviceExportVo, gasuserSafetyDeviceInfo);
                                gasuserSafetyDeviceInfo.setRelationGasuserId(detectorUser.getUserId());
                                gasuserSafetyDeviceInfoList.add(gasuserSafetyDeviceInfo);
                            }
                        }
                    }

                    if (gasuserSafetyDeviceInfoList.size() > 0) {
                        gasuserSafetyDeviceInfoMapper.insertBatch(gasuserSafetyDeviceInfoList);
                    }
                }
            }
            //是要修改的
            List<TDetectorUser> updateCollect = successDataList.stream().filter(item -> item.getUserId() != null).collect(Collectors.toList());
            if (updateCollect.size() > 0 && reImportOfIncorrectDataFlag) {
                String sql = "UPDATE t_detector_user \n" +
                        "SET nick_name = ?,\n" +
                        "user_type = ?,\n" +
                        "gas_type = ?,\n" +
                        "f_village_id = ?,\n" +
                        "beyond_enterprise_id = ?,\n" +
                        "address = ?,\n" +
                        "linkman = ?,\n" +
                        "phone = ?,\n" +
                        "remarks = ?,\n" +
                        "error_msg = ? \n" +
                        "WHERE\n" +
                        "\tuser_id = ?";
                try (Connection conn = dataSource.getConnection()) {
                    PreparedStatement pstmt = conn.prepareStatement(sql);
                    for (TDetectorUser detectorUser : updateCollect) {
                        pstmt.setString(1, detectorUser.getNickName());
                        pstmt.setString(2, detectorUser.getUserType());
                        pstmt.setString(3, detectorUser.getGasType());
                        pstmt.setLong(4, detectorUser.getVillageId());
                        pstmt.setString(5, detectorUser.getBeyondEnterpriseId());
                        pstmt.setString(6, detectorUser.getAddress());
                        pstmt.setString(7, detectorUser.getLinkman());
                        pstmt.setString(8, detectorUser.getPhone());
                        pstmt.setString(9, detectorUser.getRemarks());
                        pstmt.setString(10, null);
                        pstmt.setLong(11, detectorUser.getUserId());
                        pstmt.addBatch();
                    }
                    pstmt.executeBatch();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据企业id统计错误数据
     *
     * @return r
     */
    @Override
    public int countByBeyondEnterpriseId(String gasType) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String deptId = loginUser.getUser().getDeptId();

        return tDetectorUserMapper.countByBeyondEnterpriseId(deptId, gasType);
    }

    /**
     * 根据企业id 清除数据
     *
     * @return r
     */
    @Override
    public int clearImportErrorByEnterpriseId(String gasType) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String deptId = loginUser.getUser().getDeptId();
        return tDetectorUserMapper.clearByBeyondEnterpriseId(deptId, gasType);
    }

    /**
     * 统计用户
     * @return
     */
    @Override
    public Map<String, Object> summaryUser() {
        return tDetectorUserMapper.summaryUser();
    }
}
