package com.zehong.system.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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);
    }

    /**
     * 查询探测器用户列表 地图使用 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");
                }
                list.add(userVO);
            }
            collect = list.stream().collect(Collectors.groupingBy(TDetectorUserVO::getIconType));
        } else {
            collect = new HashMap<>(0);
        }

        return collect;
    }

    /**
     * 查询探测器用户列表 地图使用 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);
    }
}
