package com.sckw.slope.detection.service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.model.enums.*;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.RegularUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.HttpResult;
import com.sckw.slope.detection.dao.mysql.*;
import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
import com.sckw.slope.detection.model.dos.mysql.*;
import com.sckw.slope.detection.model.dos.tdengine.Devices;
import com.sckw.slope.detection.model.dto.*;
import com.sckw.slope.detection.model.param.ProjectAndDeviceParam;
import com.sckw.slope.detection.model.param.ProjectThresholdSettingParam;
import com.sckw.slope.detection.model.param.ThresholdDetailQuery;
import com.sckw.slope.detection.model.param.ThresholdQuery;
import com.sckw.slope.detection.model.vo.ProjectAndDeviceVo;
import com.sckw.slope.detection.model.vo.ProjectThresholdSettingVO;
import com.sckw.slope.detection.model.vo.ThresholdDetailVO;
import com.sckw.slope.detection.service.repository.KwsThresholdRepository;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description 阈值service
 * @date 2023-11-01 16:11:03
 */
@Slf4j
@Service
public class ThresholdService {

    @Autowired
    CommonService commonService;

    @Autowired
    KwsDeviceModelPartMapper deviceModelPartMapper;

    @Autowired
    KwsDeviceMapper deviceMapper;

    @Autowired
    KwsProjectMapper projectMapper;

    @Autowired
    DevicesMapper devicesMapper;

    @Autowired
    KwsProjectDeviceMapper projectDeviceMapper;

    @Autowired
    KwsDeviceIntegrationMapper deviceIntegrationMapper;

    @Autowired
    KwsThresholdMapper thresholdMapper;

    @Autowired
    KwsThresholdRepository thresholdRepository;

    @Autowired
    KwsDeviceReferenceMapper deviceReferenceMapper;

    public PageRes newSelect(ThresholdQuery thresholdQuery, HttpServletRequest request) {
        PageHelper.startPage(thresholdQuery.getPage(), thresholdQuery.getPageSize());
        HeaderData headerData = commonService.getHeaderData(request);
        List<Integer> status = new ArrayList<>();
        status.add(DeviceEnum.ALREADY_REFERRED_TO.getCode());
        List<KwsThreshold> list = thresholdMapper.selectListAll(thresholdQuery, headerData, status);
        List<ThresholdSelectDTO> dtoList = deviceMapper.selectDeviceAllByProjectAndMountainId(thresholdQuery.getProjectId(), headerData.getMountainId(), status);
        PageInfo<ThresholdSelectDTO> info = new PageInfo<>(dtoList);
        if (CollectionUtils.isEmpty(dtoList)) {
            return PageRes.build(info, dtoList);
        }
        for (ThresholdSelectDTO dto : dtoList) {
            Long deviceId = dto.getDeviceId();
            //基本要素
            List<DeviceElementDTO> basiclElementList = deviceModelPartMapper.selectElementList(thresholdQuery.getProjectId(),
                    headerData.getMountainId(), status, deviceId);
            List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                    .eq(KwsThreshold::getDeviceId, deviceId)
                    .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                    .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
                    .orderByDesc(KwsThreshold::getCreateTime)
            );
            String setting = ThresholdEnum.IS_NOT_SET.getStatus();
            String statusName = ThresholdEnum.IS_NOT_SET.getDestination();
            if (!CollectionUtils.isEmpty(kwsThresholds)) {
                setting = kwsThresholds.get(0).getSetting();
                if (ThresholdEnum.PARTIAL_SETTING.getStatus().equals(setting)) {
                    statusName = ThresholdEnum.PARTIAL_SETTING.getDestination();
                } else {
                    setting = ThresholdEnum.HAVE_SET.getStatus();
                    statusName = ThresholdEnum.HAVE_SET.getDestination();
                }
            }
            dto.setId(thresholdQuery.getProjectId());
            StringBuilder phones = new StringBuilder();
            if (!CollectionUtils.isEmpty(kwsThresholds)) {
                for (int i = 0; i < kwsThresholds.size(); i++) {
                    if (i != (kwsThresholds.size() - 1)) {
                        phones.append(kwsThresholds.get(i).getPhones()).append(",");
                    } else {
                        phones.append(kwsThresholds.get(i).getPhones());
                    }
                }
            }
            List<String> itemNameList = new ArrayList<>();
            //翻译
            List<String> collect = basiclElementList.stream().map(DeviceElementDTO::getElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                for (String dict : collect) {
                    //不查询数据库【kws_device_model_part】 查字典
                    Map<String, SystemDict> dictList = commonService.getDictList(null,
                            new HashMap<>() {
                                {
                                    put("code", DictEnum.MODEL_PART.getCodeType());
                                    put("type", "1");
                                }
                            }
                    );
                    itemNameList.add(dictList == null ? dict : (dictList.get(dict) == null ? dict : dictList.get(dict).getLabel()));
                }
            }
            //集成要素
            List<DeviceElementDTO> integratedElementList = deviceIntegrationMapper.selectIntegratedElement(thresholdQuery.getProjectId(),
                    headerData.getMountainId(), status, deviceId);
            List<String> collect1 = integratedElementList.stream().map(DeviceElementDTO::getIntegrationElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect1)) {
                itemNameList.addAll(collect1);
            }
            dto.setItemName(JSONObject.toJSONString(itemNameList));
            //获取总数和设置阈值数
            int deviceTotal = getThresholdNumber(thresholdQuery.getProjectId(), headerData, deviceId);
            dto.setDeviceTotal(String.valueOf(deviceTotal));
            int deviceSetTotal = 0;
            if (!CollectionUtils.isEmpty(kwsThresholds)) {
                deviceSetTotal = kwsThresholds.stream().map(KwsThreshold::getItemName).distinct().collect(Collectors.toList()).size();
            }
            dto.setDeviceSetTotal(deviceSetTotal);
            dto.setDeviceName(dto.getDeviceName());
            dto.setStatus(setting);
            dto.setStatusName(statusName);
            dto.setPhones(phones.toString());
            dto.setUpdateByName(CollectionUtils.isEmpty(kwsThresholds) ? null : kwsThresholds.get(0).getCreateBy().toString());
            dto.setUpdateTime(CollectionUtils.isEmpty(kwsThresholds) ? null : kwsThresholds.get(0).getCreateTime());
        }
        return PageRes.build(info, dtoList);
    }

    public PageRes select(ThresholdQuery thresholdQuery, HttpServletRequest request) {
        PageHelper.startPage(thresholdQuery.getPage(), thresholdQuery.getPageSize());
        HeaderData headerData = commonService.getHeaderData(request);
        List<Integer> status = new ArrayList<>();
        status.add(DeviceEnum.ALREADY_REFERRED_TO.getCode());
        List<ThresholdSelectDTO> dtoList = deviceMapper.selectDeviceAllByProjectAndMountainId(thresholdQuery.getProjectId(), headerData.getMountainId(), status);
        PageInfo<ThresholdSelectDTO> info = new PageInfo<>(dtoList);
        if (CollectionUtils.isEmpty(dtoList)) {
            return PageRes.build(info, dtoList);
        }
        for (ThresholdSelectDTO dto : dtoList) {
            Long deviceId = dto.getDeviceId();
            //基本要素
            List<DeviceElementDTO> basiclElementList = deviceModelPartMapper.selectElementList(thresholdQuery.getProjectId(),
                    headerData.getMountainId(), status, deviceId);
            List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                    .eq(KwsThreshold::getDeviceId, deviceId)
                    .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                    .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
                    .orderByDesc(KwsThreshold::getCreateTime)
            );
            String setting = ThresholdEnum.IS_NOT_SET.getStatus();
            String statusName = ThresholdEnum.IS_NOT_SET.getDestination();
            if (!CollectionUtils.isEmpty(kwsThresholds)) {
                setting = kwsThresholds.get(0).getSetting();
                if (ThresholdEnum.PARTIAL_SETTING.getStatus().equals(setting)) {
                    statusName = ThresholdEnum.PARTIAL_SETTING.getDestination();
                } else {
                    setting = ThresholdEnum.HAVE_SET.getStatus();
                    statusName = ThresholdEnum.HAVE_SET.getDestination();
                }
            }
            dto.setId(thresholdQuery.getProjectId());
            StringBuilder phones = new StringBuilder();
            if (!CollectionUtils.isEmpty(kwsThresholds)) {
                for (int i = 0; i < kwsThresholds.size(); i++) {
                    if (i != (kwsThresholds.size() - 1)) {
                        phones.append(kwsThresholds.get(i).getPhones()).append(",");
                    } else {
                        phones.append(kwsThresholds.get(i).getPhones());
                    }
                }
            }
            List<String> itemNameList = new ArrayList<>();
            //翻译
            List<String> collect = basiclElementList.stream().map(DeviceElementDTO::getElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                Map<String, SystemDict> dictList = commonService.getDictByDictCode(DictEnum.MODEL_PART);
                for (String dict : collect) {
                    //不查询数据库【kws_device_model_part】 查字典
                    itemNameList.add(dictList == null ? dict : (dictList.get(dict) == null ? dict : dictList.get(dict).getLabel()));
                }
            }
            //集成要素
            List<DeviceElementDTO> integratedElementList = deviceIntegrationMapper.selectIntegratedElement(thresholdQuery.getProjectId(),
                    headerData.getMountainId(), status, deviceId);
            List<String> collect1 = integratedElementList.stream().map(DeviceElementDTO::getIntegrationElement).filter(s -> s != null).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect1) && collect1.size() > 0) {
                itemNameList.addAll(collect1);
            }
            dto.setItemNameCount(itemNameList.size());
            dto.setItemName(JSONObject.toJSONString(itemNameList.stream().distinct().collect(Collectors.toList())));
            //获取总数和设置阈值数
            int deviceTotal = getThresholdNumber(thresholdQuery.getProjectId(), headerData, deviceId);
            dto.setDeviceTotal(String.valueOf(deviceTotal));
            int deviceSetTotal = 0;
            if (!CollectionUtils.isEmpty(kwsThresholds) && kwsThresholds.size() > 0) {
                deviceSetTotal = kwsThresholds.stream().map(KwsThreshold::getItemName).distinct().collect(Collectors.toList()).size();
            }
            dto.setDeviceSetTotal(deviceSetTotal);
            dto.setDeviceName(dto.getDeviceName());
            dto.setStatus(setting);
            dto.setStatusName(statusName);
            dto.setPhones(phones.toString());
            dto.setCreateByName(CollectionUtils.isEmpty(kwsThresholds) ? null : (kwsThresholds.get(0).getCreateBy() == null ? null : kwsThresholds.get(0).getCreateBy().toString()));
            dto.setUpdateByName(CollectionUtils.isEmpty(kwsThresholds) ? null : (kwsThresholds.get(0).getUpdateBy() == null ? null : kwsThresholds.get(0).getUpdateBy().toString()));
            dto.setUpdateTime(CollectionUtils.isEmpty(kwsThresholds) ? null : kwsThresholds.get(0).getCreateTime());
        }
        return PageRes.build(info, dtoList);
    }

    private int getThresholdNumber(String projectId, HeaderData headerData, Long deviceId) {
        List<Integer> status = new ArrayList<>();
        status.add(DeviceEnum.ALREADY_REFERRED_TO.getCode());
        //基本要素
        List<DeviceElementDTO> basiclElementList = deviceModelPartMapper.selectElementList(projectId,
                headerData.getMountainId(), status, deviceId);
        //集成要素
        List<DeviceElementDTO> integratedElementList = deviceIntegrationMapper.selectIntegratedElement(projectId,
                headerData.getMountainId(), status, deviceId);
        int count = 0;
        if (!CollectionUtils.isEmpty(basiclElementList)) {
            List<String> collect = basiclElementList.stream().map(DeviceElementDTO::getElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                for (String s : collect) {
                    List<String> stringList = StringUtils.splitStrToList(s, String.class);
                    count = count + stringList.size();
                }
            }

        }
        if (!CollectionUtils.isEmpty(integratedElementList)) {
            List<String> collect = integratedElementList.stream().map(DeviceElementDTO::getIntegrationElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                count = count + collect.size();
//                for (String s : collect) {
//                    List<String> stringList = StringUtils.splitStrToList(s, String.class);
//                    count = count + stringList.size();
//                }
            }
        }
        return count;
    }

    public HttpResult detail(ThresholdDetailQuery thresholdQuery, HttpServletRequest request) {
        String deviceId = thresholdQuery.getDeviceId();
        String itemName = thresholdQuery.getItemName();
        HeaderData headerData = commonService.getHeaderData(request);
        String mountainId = headerData.getMountainId();
        List<KwsThreshold> kwsThreshold = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                .eq(KwsThreshold::getDeviceId, Long.parseLong(deviceId))
                .eq(KwsThreshold::getItemName, itemName)
                .eq(KwsThreshold::getMountainId, mountainId)
                .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
        );
        KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                .eq(KwsDeviceReference::getMountainId, mountainId)
                .eq(KwsDeviceReference::getDeviceId, deviceId)
                .eq(KwsDeviceReference::getType, 1)
                .eq(KwsDeviceReference::getItem, itemName)
                .eq(KwsDeviceReference::getDelFlag, 0)
        );
        ThresholdDetailVO vo = new ThresholdDetailVO();
        if (!CollectionUtils.isEmpty(kwsThreshold)) {
            vo.setPhones(kwsThreshold.get(0).getPhones());
            vo.setItemName(itemName);
            vo.setDeviceId(deviceId);
            vo.setItemValue(deviceReference == null ? null : deviceReference.getCurrentValue());
            //查询td获取数据
//            vo.setVariation();
            List<ThresholdBean> beanList = new ArrayList<>();
            for (KwsThreshold threshold : kwsThreshold) {
                ThresholdBean bean = new ThresholdBean();
                bean.setLevel(threshold.getLevel());
                bean.setMax(threshold.getMax());
                bean.setMin(threshold.getMin());
                beanList.add(bean);
            }
            vo.setThreshold(beanList);
        }
        return HttpResult.ok(vo);
    }

    @Transactional
    public HttpResult configuration(ThresholdConfigurationDTO configurationDTO, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        String projectId = configurationDTO.getProjectId();
        List<ThresholdBean> threshold = configurationDTO.getThreshold();
        String itemName = configurationDTO.getItemName();
        String phones = configurationDTO.getPhones();
        String deviceId = configurationDTO.getDeviceId();
        if (CollectionUtils.isEmpty(threshold)) {
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "设置阈值不能全部为空");
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(phones)) {
            List<String> phonesStr = StringUtils.splitStrToList(phones, String.class);
            for (String phone : phonesStr) {
                if (!RegularUtils.matchs(RegularUtils.PHONE_REG, phone)) {
                    return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "联系电话格式不正确,请检查并重新输入！");
                }
            }
        }
        //页面阈值等级校验
        //当前使用阈值123级硬编码校验
        //checkThresholdLevel(configurationDTO, headerData);
        //后期阈值等级扩容可调用此方法
        //checkLevelMax(threshold, configurationDTO, headerData);
        for (ThresholdBean thresholdBean : threshold) {
            //验证数据库层面阈值数据存储值
            int level = thresholdBean.getLevel();
//            checkDatabaseThresholdLevel(level, thresholdBean, headerData, deviceId, itemName);
            KwsThreshold selected = thresholdMapper.selectOne(new LambdaQueryWrapper<KwsThreshold>()
                    .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                    .eq(KwsThreshold::getDeviceId, deviceId)
                    .eq(KwsThreshold::getItemName, itemName)
                    .eq(KwsThreshold::getLevel, level)
                    .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
            );
            if (selected == null) {
                KwsThreshold kwsThreshold = new KwsThreshold();
                kwsThreshold.setId(new IdWorker(NumberConstant.ONE).nextId());
                kwsThreshold.setDeviceId(Long.parseLong(deviceId));
                kwsThreshold.setItemName(itemName);
                kwsThreshold.setMountainId(headerData.getMountainId());
                //计算设置状态  便于select
//                String setting = checkAndSettings(configurationDTO, headerData);
//                kwsThreshold.setSetting(setting);
                kwsThreshold.setLevel(Integer.valueOf(thresholdBean.getLevel()));
                kwsThreshold.setMax(String.valueOf(thresholdBean.getMax()));
                kwsThreshold.setMin(String.valueOf(thresholdBean.getMin()));
                kwsThreshold.setPhones(phones);
                kwsThreshold.setStatus(0);
                kwsThreshold.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
                kwsThreshold.setCreateName(headerData.getCreateName());
                LocalDateTime now = LocalDateTime.now();
                kwsThreshold.setCreateTime(now);
                kwsThreshold.setUpdateTime(now);
                kwsThreshold.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
                kwsThreshold.setUpdateName(headerData.getUpdateName());
                thresholdMapper.insert(kwsThreshold);
            } else {
                selected.setLevel(Integer.valueOf(thresholdBean.getLevel()));
                //计算设置状态  便于select
//                String setting = checkAndSettings(configurationDTO, headerData);
//                selected.setSetting(setting);
                selected.setMax(String.valueOf(thresholdBean.getMax()));
                selected.setMin(String.valueOf(thresholdBean.getMin()));
                selected.setPhones(phones);
                selected.setStatus(0);
                selected.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
                selected.setUpdateName(headerData.getUpdateName());
                selected.setUpdateTime(LocalDateTime.now());
                thresholdRepository.saveOrUpdate(selected);
            }
        }
        //计算设置状态  便于select
        String setting = checkAndSettings(configurationDTO, headerData);
        thresholdMapper.update(null,
                new LambdaUpdateWrapper<KwsThreshold>()
                .eq(KwsThreshold::getDeviceId,configurationDTO.getDeviceId())
                        .set(KwsThreshold::getSetting,setting));
        Map<String, SystemDict> dict = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getId, Long.parseLong(projectId)));
        KwsDevice kwsDevice = deviceMapper.selectOne(new LambdaQueryWrapper<KwsDevice>().eq(KwsDevice::getId, Long.parseLong(deviceId)));
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("element", dict == null ? itemName : (dict.get(itemName) == null ? itemName : dict.get(itemName).getLabel()));
        logMap.put("deviceName", kwsDevice == null ? null : kwsDevice.getName());
        commonService.insertLog(MessageLogEnum.SETTINGS_DEVICE_THRESHOLD, headerData, logMap, headerData.getUpdateBy() == null ?
                null : Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    /**
     * 比较数据库中存在的阈值与页面填写的阈值范围
     *
     * @param level         阈值等级
     * @param thresholdBean 页面填写数据
     * @param headerData    请求头信息
     * @param deviceId      设备id
     * @param itemName      要素项
     */
    private void checkDatabaseThresholdLevel(int level, ThresholdBean thresholdBean, HeaderData headerData, String deviceId, String itemName) {
        if (1 == level) {
            KwsThreshold twoKwsThreshold = thresholdSelect(2, headerData, deviceId, itemName);
            KwsThreshold threeKwsThreshold = thresholdSelect(3, headerData, deviceId, itemName);
            if (twoKwsThreshold != null) {
                String min = twoKwsThreshold.getMin();
                if (min.contains("-")) {
//                    min = StringUtils.deleteCharString(min, "-");
                    if (Double.parseDouble(min) < Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("一级最小值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(min) > Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("一级最小值阈值设置数据填写错误");
                    }
                }
                String max = twoKwsThreshold.getMax();
                if (max.contains("-")) {
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("一级最大值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("一级最大值阈值设置数据填写错误");
                    }
                }
            }
            if (threeKwsThreshold != null) {
                String min = threeKwsThreshold.getMin();
                if (min.contains("-")) {
                    if (Double.parseDouble(min) < Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("一级最小值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(min) < Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("一级最小值阈值设置数据填写错误");
                    }
                }
                String max = threeKwsThreshold.getMax();
                if (max.contains("-")) {
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("一级最大值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("一级最大值阈值设置数据填写错误");
                    }
                }
            }
        } else if (2 == level) {
            KwsThreshold oneKwsThreshold = thresholdSelect(1, headerData, deviceId, itemName);
            KwsThreshold threeKwsThreshold = thresholdSelect(3, headerData, deviceId, itemName);
            if (oneKwsThreshold != null) {
                String min = oneKwsThreshold.getMin();
                if (min.contains("-")) {
//                    min = StringUtils.deleteCharString(min, "-");
                    if (Double.parseDouble(min) > Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("二级最小值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(min) > Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("阈值设置数据填写错误");
                    }
                }
                String max = oneKwsThreshold.getMax();
                if (max.contains("-")) {
//                    min = StringUtils.deleteCharString(min, "-");
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(max) < Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("阈值设置数据填写错误");
                    }
                }
            }
            if (threeKwsThreshold != null) {
                String min = threeKwsThreshold.getMin();
                if (min.contains("-")) {
                    if (Double.parseDouble(min) < Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("二级最小级阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(min) < Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("二级最小级阈值设置数据填写错误");
                    }
                }
                String max = threeKwsThreshold.getMax();
                if (max.contains("-")) {
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("二级最大值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(max) > Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在三级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("二级最大值阈值设置数据填写错误");
                    }
                }
            }
        } else if (3 == level) {
            KwsThreshold oneKwsThreshold = thresholdSelect(1, headerData, deviceId, itemName);
            KwsThreshold twoKwsThreshold = thresholdSelect(2, headerData, deviceId, itemName);
            if (oneKwsThreshold != null) {
                String min = oneKwsThreshold.getMin();
                if (min.contains("-")) {
                    if (Double.parseDouble(min) > Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("三级最小值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(min) < Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("三级最小值阈值设置数据填写错误");
                    }
                }
                String max = oneKwsThreshold.getMax();
                if (max.contains("-")) {
                    if (Double.parseDouble(max) < Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("三级最大值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(max) < Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在一级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("三级最大值阈值设置数据填写错误");
                    }
                }
            }
            if (twoKwsThreshold != null) {
                String min = twoKwsThreshold.getMin();
                if (min.contains("-")) {
                    if (Double.parseDouble(min) > Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("三级最小值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(min) > Double.parseDouble(thresholdBean.getMin())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMin(), min);
                        throw new BusinessException("三级最小值阈值设置数据填写错误");
                    }
                }
                String max = twoKwsThreshold.getMax();
                if (max.contains("-")) {
                    if (Double.parseDouble(thresholdBean.getMax()) > Double.parseDouble(max)) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("三级最大值阈值设置数据填写错误");
                    }
                } else {
                    if (Double.parseDouble(max) < Double.parseDouble(thresholdBean.getMax())) {
                        log.error("当前等级:{}，当前设置阈值：{},存在二级阈值:{}", level, thresholdBean.getMax(), max);
                        throw new BusinessException("三级最大值阈值设置数据填写错误");
                    }
                }
            }
        }
    }

    private KwsThreshold thresholdSelect(int level, HeaderData headerData, String deviceId, String itemName) {
        KwsThreshold threshold = thresholdMapper.selectOne(new LambdaQueryWrapper<KwsThreshold>()
                .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                .eq(KwsThreshold::getDeviceId, deviceId)
                .eq(KwsThreshold::getItemName, itemName)
                .eq(KwsThreshold::getLevel, level)
                .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
        );
        return threshold;
    }

    private void checkThresholdLevel(ThresholdConfigurationDTO configurationDTO, HeaderData headerData) {
        List<ThresholdBean> threshold = configurationDTO.getThreshold();
        Map<Integer, ThresholdBean> maps = threshold.stream().collect(Collectors.toMap(ThresholdBean::getLevel, Function.identity(), (key1, key2) -> key2));
        ThresholdBean thresholdBeanOne = maps.get(1);
        ThresholdBean thresholdBeanTwo = maps.get(2);
        ThresholdBean thresholdBeanThree = maps.get(3);
        if (thresholdBeanTwo != null) {
            String min = String.valueOf(thresholdBeanTwo.getMin());//10
            String max = String.valueOf(thresholdBeanTwo.getMax());//90
            if (thresholdBeanThree != null) {
                double minThree = Double.parseDouble(thresholdBeanThree.getMin());//8
//                if (minThree.contains("-")) {
//                    minThree = com.sckw.core.utils.StringUtils.deleteCharString(minThree, "-");//-8
//                }
                double maxThree = Double.parseDouble(thresholdBeanThree.getMax());//80
                if (max.compareTo(String.valueOf(maxThree)) < 0) {
                    throw new BusinessException("阈值填写错误");
                }
                if (min.contains("-")) {
//                min = com.sckw.core.utils.StringUtils.deleteCharString(min, "-");//-10
                    if (min.compareTo(String.valueOf(maxThree)) > 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                } else {
                    if (min.compareTo(String.valueOf(maxThree)) > 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                }

            }
            if (thresholdBeanOne != null) {
                String minOne = String.valueOf(thresholdBeanOne.getMin()); //15
                String maxThree = String.valueOf(thresholdBeanOne.getMax());//100
                if (max.compareTo(maxThree) > 0) {
                    throw new BusinessException("阈值填写错误");
                }
                if (minOne.contains("-")) {
//                    minOne = com.sckw.core.utils.StringUtils.deleteCharString(minOne, "-");//-15
                    if (min.compareTo(minOne) < 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                } else {
                    if (min.compareTo(minOne) < 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                }
            }
        }
        if (thresholdBeanThree != null) {
            String minThree = String.valueOf(thresholdBeanThree.getMin());//8
            String maxThree = String.valueOf(thresholdBeanThree.getMax());//80
            if (thresholdBeanTwo != null) {
                double twoMax = Double.parseDouble(thresholdBeanTwo.getMax());//90
                double twoMin = Double.parseDouble(thresholdBeanTwo.getMin());//-10
                if (String.valueOf(twoMax).compareTo(maxThree) < 0) {
                    throw new BusinessException("阈值填写错误");
                }
                if (minThree.contains("-")) {
//                    minThree = com.sckw.core.utils.StringUtils.deleteCharString(minThree, "-");//-8
                    if (String.valueOf(twoMin).compareTo(minThree) > 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                } else {
                    if (String.valueOf(twoMin).compareTo(minThree) > 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                }
//                if (twoMin.contains("-")) {
//                    twoMin = com.sckw.core.utils.StringUtils.deleteCharString(twoMin, "-");//-8
//                }

            }
            if (thresholdBeanOne != null) {
                String oneMax = String.valueOf(thresholdBeanOne.getMax());//100
                String oneMin = String.valueOf(thresholdBeanOne.getMin());//-15
                if (oneMax.compareTo(maxThree) < 0) {
                    throw new BusinessException("阈值填写错误");
                }
                if (oneMin.contains("-")) {
//                    oneMin = com.sckw.core.utils.StringUtils.deleteCharString(oneMin, "-");//-8
                    if (oneMax.compareTo(maxThree) > 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                } else {
                    if (oneMin.compareTo(minThree) > 0) {
                        throw new BusinessException("阈值填写错误");
                    }
                }
            }
        }
    }

    private void checkLevelMax(List<ThresholdBean> threshold, ThresholdConfigurationDTO configurationDTO, HeaderData headerData) {
        Integer maxLevel = threshold.stream().map(ThresholdBean::getLevel).max((x, y) -> x - y).get();
        if (threshold.size() > 1) {
            Map<Integer, ThresholdBean> maps = threshold.stream().collect(Collectors.toMap(ThresholdBean::getLevel, Function.identity(), (key1, key2) -> key2));
            int count = 0;
            for (int i = maxLevel; i > 0; i--) {
                ThresholdBean thresholdBean = maps.get(maxLevel);
                if (thresholdBean != null) {
                    String thresholdBeanMin = String.valueOf(thresholdBean.getMin());
                    if (thresholdBeanMin.contains("-")) {
                        thresholdBeanMin = com.sckw.core.utils.StringUtils.deleteCharString(thresholdBeanMin, "-");
                    }
                    ThresholdBean thresholdBean1 = maps.get(i);
                    if (thresholdBean1 != null) {
                        String max = String.valueOf(thresholdBean1.getMax());
                        String min = String.valueOf(thresholdBean1.getMin());
                        if (min.contains("-")) {
                            min = com.sckw.core.utils.StringUtils.deleteCharString(min, "-");
                        }
                        if (BigDecimal.valueOf(Long.parseLong(max)).compareTo(BigDecimal.valueOf(Double.parseDouble(thresholdBean.getMax()))) > 0) {
                            throw new BusinessException("阈值填写错误");
                        }
                        if (BigDecimal.valueOf(Long.parseLong(min)).compareTo(BigDecimal.valueOf(Long.parseLong(thresholdBeanMin))) < 0) {
                            throw new BusinessException("阈值填写错误");
                        }
                    }
                }
            }
            for (ThresholdBean value : maps.values()) {
                int level = value.getLevel();
                if (level == count) {
                    int levelMax = level + 1;
                    int levelMin = level - 1;
                    if (maps.get(levelMax) != null) {
                        double min = Double.parseDouble(value.getMin());
                        double max = Double.parseDouble(value.getMax());
                    }
                    if (maps.get(levelMin) != null) {

                    }
                }
            }
            ThresholdBean thresholdBean2 = maps.get(2);
            ThresholdBean thresholdBean1 = maps.get(1);
            ThresholdBean thresholdBean3 = maps.get(3);
        }
        if (1 != maxLevel) {
            //上限界定
            KwsThreshold maxThreshold = thresholdMapper.selectOne(new LambdaQueryWrapper<KwsThreshold>()
                    .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                    .eq(KwsThreshold::getDeviceId, Long.parseLong(configurationDTO.getDeviceId()))
                    .eq(KwsThreshold::getItemName, configurationDTO.getItemName())
                    .eq(KwsThreshold::getLevel, (maxLevel + 1))
                    .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
            );
            if (maxThreshold != null) {
                String max = maxThreshold.getMax();
                String min = maxThreshold.getMin();
            }
            //下限界定
        }
    }

    private String checkAndSettings(ThresholdConfigurationDTO configurationDTO, HeaderData headerData) {
        String deviceId = configurationDTO.getDeviceId();
        List<Integer> status = new ArrayList<>();
        status.add(DeviceEnum.ALREADY_REFERRED_TO.getCode());
        //基本要素
        List<DeviceElementDTO> basiclElementList = deviceModelPartMapper.selectElementList(configurationDTO.getProjectId(),
                headerData.getMountainId(), status, Long.parseLong(deviceId));
        //集成要素
        List<DeviceElementDTO> integratedElementList = deviceIntegrationMapper.selectIntegratedElement(configurationDTO.getProjectId(),
                headerData.getMountainId(), status, Long.parseLong(deviceId));
        int count = 0;
        if (!CollectionUtils.isEmpty(basiclElementList)) {
            List<String> collect = basiclElementList.stream().map(DeviceElementDTO::getElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                for (String s : collect) {
                    List<String> stringList = StringUtils.splitStrToList(s, String.class);
                    count = count + stringList.size();
                }
            }

        }
        if (!CollectionUtils.isEmpty(integratedElementList)) {
            List<String> collect = integratedElementList.stream().map(DeviceElementDTO::getIntegrationElement).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                count = count + collect.size();
//                for (String s : collect) {
//                    List<String> stringList = StringUtils.splitStrToList(s, String.class);
//                    count = count + stringList.size();
//                }
            }
        }
        List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                .eq(KwsThreshold::getDeviceId, configurationDTO.getDeviceId())
                .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
        );
        int number = 0;
        if (!CollectionUtils.isEmpty(kwsThresholds)) {
            List<String> collect = kwsThresholds.stream().map(KwsThreshold::getItemName).distinct().collect(Collectors.toList());
            number = collect.size();
        }
        // 0未设置 1 部分设置 2 已设置
        String setting = "0";
        if (number != 0) {
            if (count == number) {
                setting = "2";
            } else if (count > number) {
                setting = "1";
            }
        }
        return setting;
    }

    @Transactional
    public HttpResult dels(DeleteThresholdDTO deleteThreshold, HttpServletRequest request) {
        String itemName = deleteThreshold.getItemName();
        String projectId = deleteThreshold.getProjectId();
        String deviceId = deleteThreshold.getDeviceId();
        HeaderData headerData = commonService.getHeaderData(request);
//        List<DeviceElementDTO> list = deviceModelPartMapper.selectElementList(projectId, headerData.getMountainId(), null, Long.parseLong(deviceId));
        List<KwsThreshold> list = thresholdRepository.list(new LambdaQueryWrapper<KwsThreshold>()
                .eq(KwsThreshold::getDeviceId, Long.parseLong(deviceId))
                .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                .eq(KwsThreshold::getItemName, itemName)
                .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
        );
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(threshold -> {
                threshold.setStatus(NumberConstant.ONE);
                threshold.setDelFlag(NumberConstant.ONE);
                threshold.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
                threshold.setUpdateName(headerData.getUpdateName());
                threshold.setUpdateTime(LocalDateTime.now());
                thresholdRepository.updateById(threshold);
            });
        }
        List<String> stringList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            stringList = list.stream().map(KwsThreshold::getItemName).distinct().collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(stringList) && stringList.size() > 0) {
            Map<String, SystemDict> dict = commonService.getDictByDictCode(DictEnum.MODEL_PART);
            KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                    .eq(KwsProject::getId, Long.parseLong(projectId)));
            StringBuilder itemNameList = new StringBuilder();
            for (int i = 0; i < stringList.size(); i++) {
                if (i != stringList.size() - 1) {
                    itemNameList.append(dict == null ? itemName : dict.get(itemName).getLabel()).append(",");
                } else {
                    itemNameList.append(dict == null ? itemName : dict.get(itemName).getLabel());
                }
            }
            KwsDevice kwsDevice = deviceMapper.selectOne(new LambdaQueryWrapper<KwsDevice>().eq(KwsDevice::getId, Long.parseLong(deviceId)));
            Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
            logMap.put("projectName", project.getName());
            logMap.put("element", itemNameList);
            logMap.put("deviceName", kwsDevice == null ? null : kwsDevice.getName());
            commonService.insertLog(MessageLogEnum.DELETE_DEVICE_THRESHOLD, headerData, logMap, headerData.getUpdateBy() == null ?
                    null : Long.parseLong(headerData.getUpdateBy()));
        }
        return HttpResult.ok("删除成功");
    }

    @Autowired
    KwsProjectAreaMapper projectAreaMapper;

    public HttpResult getDevice(ProjectAndDeviceParam param) {
        String deviceId = param.getDeviceId();
        String projectId = param.getProjectId();
        KwsProject project = projectMapper.selectById(Long.parseLong(projectId));
        KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>()
                .eq(KwsProjectArea::getProjectId, Long.parseLong(projectId))
                .eq(KwsProjectArea::getDelFlag, 0));
        ProjectAndDeviceVo vo = new ProjectAndDeviceVo();
        vo.setFence(area == null ? null : area.getFence());
        KwsDevice kwsDevice = deviceMapper.selectById(Long.parseLong(deviceId));
        if (kwsDevice != null) {
            vo.setLogicLng(kwsDevice.getLogicLng());
            vo.setLogicLat(kwsDevice.getLogicLat());
            vo.setLogicAlt(kwsDevice.getLogicAlt());
        }
        vo.setDeviceId(deviceId);
        vo.setDeviceName(kwsDevice == null ? null : kwsDevice.getName());
        vo.setProjectId(projectId);
        vo.setProjectName(project == null ? null : project.getName());
        Devices devices = null;
        String itemName = param.getItemName();
        List<String> list = new ArrayList<>();
        list.add(DictItemEnum.LONGITUDE_X.getValue());
        list.add(DictItemEnum.LATITUDE_Y.getValue());
        list.add(DictItemEnum.ALTITUDE_Z.getValue());
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        if (Objects.nonNull(itemName)) {
            if (list.contains(itemName)) {
                try {
                    devices = devicesMapper.selectLastDataByCodeAndItemName(kwsDevice.getSnCode(), itemName);
                } catch (Exception e) {
                    log.error("设备查询td异常：{}", e.getMessage(), e);
                }
                BigDecimal offset = null;
                KwsDeviceReference deviceRelation = null;
                if (Objects.nonNull(itemName)) {
                    if (devices != null) {
                        deviceRelation = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                                .eq(KwsDeviceReference::getDeviceId, deviceId)
                                .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                                .eq(KwsDeviceReference::getType, "1")
                                .eq(KwsDeviceReference::getItem, itemName)
                        );
                        offset = commonService.computeOffset(devices.getVal(), itemName, deviceRelation);
                        vo.setCurrentValue(devices.getVal());
                    }
                }
                vo.setOffset(offset == null ? null : offset.toString());
            } else if (dictByDictCode != null && (dictByDictCode.get(itemName) != null)) {
                try {
                    devices = devicesMapper.selectLastDataByCodeAndItemName(kwsDevice.getSnCode(), itemName);
                } catch (Exception e) {
                    log.error("设备查询td异常：{}", e.getMessage(), e);
                }
                vo.setCurrentValue(devices == null ? null : devices.getVal());
            }
        }
        return HttpResult.ok(vo);
    }

    public HttpResult selectSetting(ProjectThresholdSettingParam param, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        String projectId = param.getProjectId();
        //100 全部  0未设置 1 部分设置 2 已设置
        String type = param.getType();
        if ("100".equals(type)) {
            return getDeviceAll(projectId, headerData, param);
        } else {
            List<ProjectThresholdSettingVO> returnList = new ArrayList<>();
            List<KwsProjectDevice> selectList = projectDeviceMapper.selectList(new LambdaQueryWrapper<KwsProjectDevice>()
                    .eq(KwsProjectDevice::getDelFlag, 0)
                    .eq(KwsProjectDevice::getProjectId, Long.parseLong(projectId))
            );
            if (CollectionUtils.isEmpty(selectList)) {
                return HttpResult.ok();
            }
            List<Long> deviceIds = selectList.stream().map(KwsProjectDevice::getDeviceId).distinct().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(deviceIds)) {
                return HttpResult.ok();
            }
            List<String> typeSetting = new ArrayList<>();
            typeSetting.add("0");
            typeSetting.add("1");
            typeSetting.add("2");
            LambdaQueryWrapper<KwsThreshold> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
                    .eq(KwsThreshold::getStatus, NumberConstant.ZERO)
                    .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                    .in(KwsThreshold::getDeviceId, deviceIds)
            ;
            KwsProject project = projectMapper.selectById(Long.parseLong(projectId));
            if (typeSetting.contains(type)) {
                wrapper.eq(KwsThreshold::getSetting, type);
                List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(wrapper);
                if (CollectionUtils.isEmpty(kwsThresholds)) {
                    return HttpResult.ok();
                }
                deviceIds = kwsThresholds.stream().map(KwsThreshold::getDeviceId).distinct().collect(Collectors.toList());
                for (Long deviceId : deviceIds) {
                    ProjectThresholdSettingVO vo = new ProjectThresholdSettingVO();
                    vo.setProjectId(projectId);
                    vo.setProjectName(project == null ? null : project.getName());
                    vo.setDeviceId(deviceId.toString());
                    KwsDevice kwsDevice = deviceMapper.selectById(deviceId);
                    vo.setDeviceName(kwsDevice == null ? null : kwsDevice.getName());
                    List<Integer> status = new ArrayList<>();
                    status.add(DeviceEnum.ALREADY_REFERRED_TO.getCode());
                    //基本要素
                    List<DeviceElementDTO> basiclElementList = deviceModelPartMapper.selectElementList(projectId,
                            headerData.getMountainId(), status, deviceId);
                    Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
                    StringBuilder itemNames = new StringBuilder();
                    List<String> itemNameList = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(basiclElementList)) {
                        for (DeviceElementDTO deviceElementDTO : basiclElementList) {
                            String itemNameLabel = deviceElementDTO.getElement() == null ? null : (
                                    dictByDictCode == null ? deviceElementDTO.getElement() : (dictByDictCode.get(deviceElementDTO.getElement()) == null ? deviceElementDTO.getElement() :
                                            (dictByDictCode.get(deviceElementDTO.getElement()).getLabel())
                                    )
                            );
                            if (Objects.nonNull(itemNameLabel)) {
                                itemNameList.add(itemNameLabel);
                            }
                        }
                    }
                    //集成要素
                    List<DeviceElementDTO> integratedElementList = deviceIntegrationMapper.selectIntegratedElement(projectId,
                            headerData.getMountainId(), status, deviceId);
                    if (!CollectionUtils.isEmpty(integratedElementList)) {
                        List<String> integratedItemName = integratedElementList.stream().map(DeviceElementDTO::getIntegrationElement).distinct().collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(integratedItemName)) {
                            itemNameList.addAll(integratedItemName);
                        }
                    }
                    if (!CollectionUtils.isEmpty(itemNameList)) {
                        for (int i = 0; i < itemNameList.size(); i++) {
                            if (i != (itemNameList.size() - 1)) {
                                itemNames.append(itemNameList.get(i)).append(",");
                            } else {
                                itemNames.append(itemNameList.get(i));
                            }
                        }
                    }

                    vo.setItemNames(itemNames == null ? null : itemNames.toString());
                    //阈值联系人
                    List<KwsThreshold> thresholdList = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                            .eq(KwsThreshold::getStatus, NumberConstant.ZERO)
                            .eq(KwsThreshold::getDelFlag, 0)
                            .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                            .orderByDesc(KwsThreshold::getCreateTime)
                    );
                    StringBuilder phoneList = new StringBuilder();
                    if (!CollectionUtils.isEmpty(thresholdList)) {
                        List<String> phones = thresholdList.stream().map(KwsThreshold::getPhones).distinct().collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(phones)) {
                            for (int i = 0; i < phones.size(); i++) {
                                if (i != (phones.size() - 1)) {
                                    phoneList.append(phones.get(i)).append(",");
                                } else {
                                    phoneList.append(phones.get(i));
                                }
                            }
                        }
                        vo.setPhones(phoneList == null ? null : phoneList.toString());
                        vo.setUpdateTime(thresholdList.get(0).getCreateTime());
                    }
                    returnList.add(vo);
                }
            }
            if (!CollectionUtils.isEmpty(returnList)) {
                returnList = returnList.stream().skip((param.getPage() - 1) * param.getPageSize()).limit(param.getPageSize()).collect(Collectors.toList());
            }
            return HttpResult.ok(returnList);
        }
    }

    private HttpResult getDeviceAll(String projectId, HeaderData headerData, ProjectThresholdSettingParam param) {
        List<ProjectThresholdSettingVO> returnList = new ArrayList<>();
        List<KwsProjectDevice> selectList = projectDeviceMapper.selectList(new LambdaQueryWrapper<KwsProjectDevice>()
                .eq(KwsProjectDevice::getDelFlag, 0)
                .eq(KwsProjectDevice::getProjectId, Long.parseLong(projectId))
        );
        if (CollectionUtils.isEmpty(selectList)) {
            return HttpResult.ok();
        }
        List<Long> deviceIds = selectList.stream().map(KwsProjectDevice::getDeviceId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(deviceIds)) {
            return HttpResult.ok();
        }
        ProjectThresholdSettingVO returnData = new ProjectThresholdSettingVO();
        KwsProject project = projectMapper.selectById(Long.parseLong(projectId));
        for (Long deviceId : deviceIds) {
            returnData.setProjectId(projectId);
            returnData.setProjectName(project == null ? null : project.getName());
            returnData.setDeviceId(deviceId.toString());
            KwsDevice kwsDevice = deviceMapper.selectById(deviceId);
            returnData.setDeviceName(kwsDevice == null ? null : kwsDevice.getName());
            List<Integer> status = new ArrayList<>();
            status.add(DeviceEnum.ALREADY_REFERRED_TO.getCode());
            //基本要素
            List<DeviceElementDTO> basiclElementList = deviceModelPartMapper.selectElementList(projectId,
                    headerData.getMountainId(), status, deviceId);
            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
            StringBuilder itemNames = new StringBuilder();
            List<String> itemNameList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(basiclElementList)) {
                for (DeviceElementDTO deviceElementDTO : basiclElementList) {
                    String itemNameLabel = deviceElementDTO.getElement() == null ? null : (
                            dictByDictCode == null ? deviceElementDTO.getElement() : (dictByDictCode.get(deviceElementDTO.getElement()) == null ? deviceElementDTO.getElement() :
                                    (dictByDictCode.get(deviceElementDTO.getElement()).getLabel())
                            )
                    );
                    if (Objects.nonNull(itemNameLabel)) {
                        itemNameList.add(itemNameLabel);
                    }
                }
            }
            //集成要素
            List<DeviceElementDTO> integratedElementList = deviceIntegrationMapper.selectIntegratedElement(projectId,
                    headerData.getMountainId(), status, deviceId);
            if (!CollectionUtils.isEmpty(integratedElementList)) {
                List<String> integratedItemName = integratedElementList.stream().map(DeviceElementDTO::getIntegrationElement).distinct().collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(integratedItemName)) {
                    itemNameList.addAll(integratedItemName);
                }
            }
            if (!CollectionUtils.isEmpty(itemNameList)) {
                for (int i = 0; i < itemNameList.size(); i++) {
                    if (i != (itemNameList.size() - 1)) {
                        itemNames.append(itemNameList.get(i)).append(",");
                    } else {
                        itemNames.append(itemNameList.get(i));
                    }
                }
            }
            returnData.setItemNames(itemNames == null ? null : itemNames.toString());
            //阈值联系人
            List<KwsThreshold> thresholdList = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                    .eq(KwsThreshold::getStatus, NumberConstant.ZERO)
                    .eq(KwsThreshold::getDelFlag, 0)
                    .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                    .orderByDesc(KwsThreshold::getCreateTime)
            );
            StringBuilder phoneList = new StringBuilder();
            if (!CollectionUtils.isEmpty(thresholdList)) {
                List<String> phones = thresholdList.stream().map(KwsThreshold::getPhones).distinct().collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(phones)) {
                    for (int i = 0; i < phones.size(); i++) {
                        if (i != (phones.size() - 1)) {
                            phoneList.append(phones.get(i)).append(",");
                        } else {
                            phoneList.append(phones.get(i));
                        }
                    }
                }
                returnData.setUpdateTime(thresholdList.get(0).getCreateTime());
            }
            returnData.setPhones(phoneList == null ? null : phoneList.toString());
            returnList.add(returnData);
        }
        if (!CollectionUtils.isEmpty(returnList)) {
            returnList = returnList.stream().skip((param.getPage() - 1) * param.getPageSize()).limit(param.getPageSize()).collect(Collectors.toList());
        }
        return HttpResult.ok(returnList);
    }
}
