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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.zehong.common.core.domain.model.LoginUser;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.system.domain.*;
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;
    /**
     * 查询探测器用户列表
     *
     * @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;
    }


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

        if (tDetectorUser.getVillageId() == null) {
            return  new ArrayList<>();
        }

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

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

        if (maps.size() > 0) {
            return maps;
        }

        return new ArrayList<>();
    }

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

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

        // 20240904 居民用户特殊处理，带有 村 和 安全装置的概念， 工商业用户 和 餐饮用户 带有 安全装置概念
        List<TDetectorUserVillageSafetyDeviceInfoVo> tDetectorUserVillageSafetyDeviceInfoVos = tDetectorUserMapper.queryDuserVilSafDevInfo(tDetectorUser);

        if (tDetectorUserVillageSafetyDeviceInfoVos.size() > 0) {

            // 居民用户集合
            List<TDetectorUserVillageSafetyDeviceInfoVo> residentsUsers = tDetectorUserVillageSafetyDeviceInfoVos.stream().filter(item -> "1".equals(item.getUserType())).collect(Collectors.toList());

            if (residentsUsers.size() > 0) {
                // 居民用户 处理方式封装
                List<Map<String,Object>> villageMapList = residentsUserInit(residentsUsers);
                if (villageMapList.size() > 0) {
                    collect.put("6",villageMapList);
                }
            }

            // 工商业用户 和 餐饮用户
            List<TDetectorUserVillageSafetyDeviceInfoVo> noResidentsUsers = tDetectorUserVillageSafetyDeviceInfoVos.stream().filter(item -> !"1".equals(item.getUserType())).collect(Collectors.toList());
            if (noResidentsUsers.size() > 0) {
                Map<String, List<Map<String, Object>>> stringListMap = noResidentsUserInit(noResidentsUsers);

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

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

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

        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> collect5 = value1.stream().filter(item -> item.getUserLatitude() != null && item.getUserLongitude() != null).collect(Collectors.toList());

                // 再过滤掉没有 天然气类型的
                List<TDetectorUserVillageSafetyDeviceInfoVo> collect6 = collect5.stream().filter(item -> item.getGasType() != null).collect(Collectors.toList());

                // 过滤掉 没有装置的
                List<TDetectorUserVillageSafetyDeviceInfoVo> collect2 = collect6.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 = collect6.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));

            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<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);
                                    }
                                }
                            }
                        }
                        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));

            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);
                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() {

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

        return tDetectorUserMapper.queryErrorDetectorUserList(deptId);
    }

    /**
     * 查询燃气用户列表-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);
    }

    /**
     * 新增燃气用户 和 安全装置
     * @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 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) {

        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();
                String gasType = gasUserExportVo.getGasType();
                String userType = gasUserExportVo.getUserType();
                String beyondEnterpriseName = gasUserExportVo.getBeyondEnterpriseName();
                String villageName = gasUserExportVo.getVillageName();

                if(!reImportOfIncorrectDataFlag) {

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

                if (StringUtils.isNotBlank(gasType)){
                    if (!"0".equals(gasType) && !"1".equals(gasType)) {
                        stringBuilder.append("燃气类型数据没按提示录入|");
                    }
                }

                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() {

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

        return tDetectorUserMapper.countByBeyondEnterpriseId(deptId);
    }

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

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