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.DeviceEnum;
import com.sckw.core.model.enums.DictEnum;
import com.sckw.core.model.enums.DictItemEnum;
import com.sckw.core.model.enums.MessageLogEnum;
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.excel.utils.DateUtil;
import com.sckw.slope.detection.dao.mysql.*;
import com.sckw.slope.detection.dao.tdengine.InsTablesMapper;
import com.sckw.slope.detection.dao.tdengine.SlopeDataMapper;
import com.sckw.slope.detection.model.dos.mysql.*;
import com.sckw.slope.detection.model.dos.tdengine.InsTables;
import com.sckw.slope.detection.model.dos.tdengine.SlopeData;
import com.sckw.slope.detection.model.dto.*;
import com.sckw.slope.detection.model.param.DeviceQuery;
import com.sckw.slope.detection.model.param.ProjectChartLogParam;
import com.sckw.slope.detection.model.param.ProjectQuery;
import com.sckw.slope.detection.model.vo.*;
import com.sckw.slope.detection.service.repository.KwsDeviceRelationRepository;
import com.sckw.slope.detection.service.repository.KwsProjectDeviceRepository;
import com.sckw.slope.detection.service.repository.KwsProjectRepository;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description 项目service
 * @date 2023-10-30 13:10:50
 */
@Slf4j
@Service
public class ProjectService {

    private static final Long equatorial_circumference = 40075020000L;
    private static final Long LATITUDE_REFERENCE = 111000000L;

    @Autowired
    CommonService commonService;

    @Autowired
    KwsProjectMapper projectMapper;

    @Autowired
    KwsProjectRepository projectRepository;

    @Autowired
    KwsProjectAreaMapper projectAreaMapper;

    @Autowired
    KwsDeviceIntegrationMapper deviceIntegrationMapper;

    @Autowired
    KwsIntegrationMapper integrationMapper;

    @Autowired
    KwsDeviceMapper deviceMapper;

    @Autowired
    SlopeDataMapper slopeDataMapper;

    @Autowired
    InsTablesMapper insTablesMapper;

    @Autowired
    KwsProjectDeviceMapper projectDeviceMapper;

    @Autowired
    KwsDeviceReferenceMapper deviceReferenceMapper;

    @Autowired
    KwsThresholdMapper thresholdMapper;

    @Autowired
    KwsMountainCompanyMapper mountainCompanyMapper;

    @Autowired
    KwsDeviceRelationMapper deviceRelationMapper;

    @Autowired
    KwsDeviceRelationRepository deviceRelationRepository;

    @Autowired
    KwsProjectDeviceRepository projectDeviceRepository;

    /**
     * 新增项目
     *
     * @param projectAddDto 请求参数
     * @param request       http流
     * @return 返回值
     */
    @Transactional
    public HttpResult add(ProjectAddDTO projectAddDto, HttpServletRequest request) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectAddDto.getBuildPhone())) {
            if (!RegularUtils.matchs(RegularUtils.PHONE_REG, projectAddDto.getBuildPhone())) {
                return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "施工单位联系电话格式不正确,请检查并重新输入！");
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectAddDto.getDesignPhone())) {
            if (!RegularUtils.matchs(RegularUtils.PHONE_REG, projectAddDto.getDesignPhone())) {
                return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "设计单位联系电话格式不正确,请检查并重新输入！");
            }
        }
        HeaderData headerData = commonService.getHeaderData(request);
        KwsProject project = new KwsProject();
        BeanUtils.copyProperties(projectAddDto, project);
        long id = new IdWorker(NumberConstant.ONE).nextId();
        project.setId(id);
        project.setStatus(NumberConstant.ZERO);
        project.setCreateBy(Long.parseLong(headerData.getCreateBy()));
        LocalDateTime now = LocalDateTime.now();
        project.setCreateTime(now);
        project.setUpdateBy(Long.parseLong(headerData.getUpdateBy()));
        project.setUpdateTime(now);
        project.setCompanyId(headerData.getCompanyId());
        project.setProjectType(projectAddDto.getProjectType());
        project.setMountainId(headerData.getMountainId());
        project.setMountainNewId(projectAddDto.getMountainId());
        List<KwsProject> projectList = projectMapper.selectListByType(projectAddDto.getProjectType());
        if (projectList.size() > 99) {
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "当前类型项目已经增加上限!");
        }
        String projectNo = "1";
        if (Objects.isNull(projectList)) {
            projectNo = StringUtils.addZeroForNum(projectNo, 2);
        } else {
            projectNo = StringUtils.addZeroForNum(String.valueOf(projectList.size() + 1), 2);
        }
        project.setProjectNo(projectAddDto.getProjectType() + projectNo);
        projectMapper.insert(project);
        KwsProjectArea area = new KwsProjectArea();
        area.setId(new IdWorker(NumberConstant.ONE).nextId());
        area.setProjectId(id);
        area.setArea(projectAddDto.getArea());
//        area.setCompanyId(headerData.getCompanyId());
        area.setFence(projectAddDto.getFence());
        area.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        area.setCreateTime(now);
        area.setUpdateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        area.setUpdateTime(now);
        projectAreaMapper.insert(area);
        KwsMountainCompany company = new KwsMountainCompany();
        company.setId(new IdWorker(NumberConstant.ONE).nextId());
        company.setMountainId(headerData.getMountainId());
        company.setCompanyId(headerData.getCompanyId());
        mountainCompanyMapper.insert(company);
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", projectAddDto.getName());
        logMap.put("mountainName", projectAddDto.getMountainName());
        commonService.insertLog(MessageLogEnum.ADD_PROJECT, headerData, logMap, headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        return HttpResult.ok();
    }

    /**
     * 项目管理分页查询
     *
     * @param projectQueryDto 请求分页
     * @param response        http流
     * @return 返回值
     */
    public PageRes select(ProjectQuery projectQueryDto, HttpServletRequest response) {
        PageHelper.startPage(projectQueryDto.getPage(), projectQueryDto.getPageSize());
        List<ProjectVo> list = projectMapper.selectByProjectParam(projectQueryDto, commonService.getHeaderData(response).getCompanyId());
        PageInfo<ProjectVo> pageInfo = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(pageInfo, list);
        }
        Map<String, SystemDict> projectType = commonService.getDictByDictCode(DictEnum.PROJECT_TYPE);
        for (ProjectVo vo : list) {
            vo.setProjectTypeLabel(vo.getProjectType() == null ? null :
                    (projectType.get(vo.getProjectType()) == null ? vo.getProjectType() :
                            projectType.get(vo.getProjectType()).getLabel()));
            vo.setDeviceTotal(projectDeviceMapper.selectCount(new LambdaQueryWrapper<KwsProjectDevice>().eq(KwsProjectDevice::getProjectId, vo.getId())).intValue());
            KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>().eq(KwsProjectArea::getProjectId, vo.getId()));
            vo.setFence(area == null ? null : area.getFence());
            vo.setArea(area == null ? null : area.getArea());
        }
        return PageRes.build(pageInfo, list);
    }

    public HttpResult detail(String id, HttpServletRequest response) {
        Map<String, SystemDict> projectType = commonService.getDictByDictCode(DictEnum.PROJECT_TYPE);
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                        .eq(KwsProject::getId, id)
                /**.eq(KwsProject::getCompanyId, commonService.getHeaderData(response).getCompanyId())*/);
        ProjectVo vo = new ProjectVo();
        BeanUtils.copyProperties(project, vo);
        KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>().eq(KwsProjectArea::getProjectId, vo.getId()));
        vo.setFence(area == null ? null : area.getFence());
        vo.setArea(area == null ? null : area.getArea());
        vo.setProjectTypeLabel(vo.getProjectType() == null ? null :
                (projectType.get(vo.getProjectType()) == null ? vo.getProjectType() :
                        projectType.get(vo.getProjectType()).getLabel()));
        return HttpResult.ok(vo);
    }

    @Transactional
    public HttpResult update(ProjectUpdateDTO projectAddDto, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        KwsProject project = new KwsProject();
        BeanUtils.copyProperties(projectAddDto, project);
        project.setMountainNewId(projectAddDto.getMountainId());
        project.setMountainId(headerData.getMountainId());
        project.setId(Long.parseLong(projectAddDto.getId()));
        project.setStatus(NumberConstant.ZERO);
        LocalDateTime now = LocalDateTime.now();
        project.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
        project.setUpdateTime(now);
        project.setRemark(org.apache.commons.lang3.StringUtils.isBlank(projectAddDto.getRemark()) ? null : projectAddDto.getRemark());
        projectRepository.updateById(project);
        String fence = projectAddDto.getFence();
        projectAreaMapper.update(null, new LambdaUpdateWrapper<KwsProjectArea>()
                .eq(KwsProjectArea::getProjectId, projectAddDto.getId())
                .set(KwsProjectArea::getFence, fence)
                .set(KwsProjectArea::getArea, projectAddDto.getArea())
        );
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", projectAddDto.getName());
        logMap.put("mountainName", projectAddDto.getMountainName());
        commonService.insertLog(MessageLogEnum.UPDATE_PROJECT, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
        return HttpResult.ok();
    }

    @Transactional
    public HttpResult dels(String ids, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        List<Long> list = StringUtils.splitStrToList(ids, Long.class);
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getId, list.get(0)));
        if (project == null) {
            throw new BusinessException("要删除的项目不存在");
        }
        Long count = projectDeviceMapper.selectCount(new LambdaQueryWrapper<KwsProjectDevice>()
                .eq(KwsProjectDevice::getProjectId, list.get(0))
                .eq(KwsProjectDevice::getDelFlag, 0)
        );
        if (count > 0) {
            throw new BusinessException("项目存在关联设备，不允许删除!");
        }
        int update = projectMapper.update(null, new LambdaUpdateWrapper<KwsProject>().in(KwsProject::getId, list).set(KwsProject::getDelFlag, "1"));
        projectAreaMapper.update(null, new LambdaUpdateWrapper<KwsProjectArea>().in(KwsProjectArea::getProjectId, list).set(KwsProjectArea::getDelFlag, 1));
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("mountainName", project.getMountainName());
        commonService.insertLog(MessageLogEnum.DELETE_PROJECT, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
        if (update < 1) {
            throw new BusinessException("删除失败");
        }
        return HttpResult.ok();
    }

    public HttpResult monitorItem(String id, HttpServletRequest request) {
        String companyId = commonService.getHeaderData(request).getCompanyId();
        Map<String, SystemDict> modelTypeDict = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        //查询基本要素
        List<BaseItemDTO> baseItem = projectDeviceMapper.selectDataByProjectId(Long.parseLong(id));
        List<IntegrationItemVO> integrationItem = projectDeviceMapper.selectIntegrationItemByProjectId(Long.parseLong(id));
        JSONObject jsonObject = new JSONObject();
        if (!CollectionUtils.isEmpty(baseItem)) {
            for (BaseItemDTO baseItemDTO : baseItem) {
                baseItemDTO.setPartName(baseItemDTO.getPartName() == null ? null :
                        (modelTypeDict == null ? baseItemDTO.getPartName() :
                                (modelTypeDict.get(baseItemDTO.getPartName()) == null ? baseItemDTO.getPartName() :
                                        (modelTypeDict.get(baseItemDTO.getPartName()).getLabel()))));
            }
        }
        jsonObject.put("baseItem", baseItem);
        jsonObject.put("integrationItem", integrationItem);
        return HttpResult.ok(jsonObject);
    }

    public PageRes selectDevice(DeviceQuery deviceQuery, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        PageHelper.startPage(deviceQuery.getPage(), deviceQuery.getPageSize());
//        List<ProjectDeviceVO> list = projectMapper.selectDeviceByProjectId(Long.parseLong(deviceQuery.getProjectId()));
        List<ProjectDeviceVO> list = projectMapper.selectDeviceList(deviceQuery);
        PageInfo<ProjectDeviceVO> info = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(info, list);
        }
        Map<String, SystemDict> deviceType = commonService.getDictByDictCode(DictEnum.DEVICE_TYPE);
        Map<String, SystemDict> company = commonService.getDictByDictCode(DictEnum.COMPANY);
        for (ProjectDeviceVO projectDeviceDTO : list) {
            Long id = projectDeviceDTO.getDeviceRelationId();
            KwsDeviceRelation deviceRelation = deviceRelationMapper.selectOne(new LambdaQueryWrapper<KwsDeviceRelation>()
                    .eq(KwsDeviceRelation::getId, id)
                    .eq(KwsDeviceRelation::getMountainId, headerData.getMountainId())
                    .eq(KwsDeviceRelation::getDelFlag, 0)
            );
            projectDeviceDTO.setDeviceModelName(projectDeviceDTO.getDeviceModelName() == null ? null :
                    (deviceType == null ? projectDeviceDTO.getDeviceModelName() : (
                            deviceType.get(projectDeviceDTO.getDeviceType()) == null ? projectDeviceDTO.getDeviceModelName() : deviceType.get(projectDeviceDTO.getDeviceType()).getLabel()
                    )));
            projectDeviceDTO.setManufacturer(projectDeviceDTO.getManufacturer() == null ? null :
                    (company == null ? projectDeviceDTO.getManufacturer() :
                            (company.get(projectDeviceDTO.getManufacturer()) == null ? projectDeviceDTO.getManufacturer() : company.get(projectDeviceDTO.getManufacturer()).getLabel())));
            if (deviceRelation != null) {
                projectDeviceDTO.setParentId(deviceRelation.getDeviceId().toString());
                KwsDevice kwsDevice = deviceMapper.selectByPrimaryKey(deviceRelation.getDeviceId());
                projectDeviceDTO.setParentName(kwsDevice == null ? null : kwsDevice.getName());
            }
            if (StringUtils.isNotBlank(projectDeviceDTO.getParentId())) {
                if (projectDeviceDTO.getId().equals(projectDeviceDTO.getParentId())) {
                    projectDeviceDTO.setParentName(null);
                } else {
                    KwsDevice device = deviceMapper.selectById(Long.parseLong(projectDeviceDTO.getParentId()));
                    projectDeviceDTO.setParentName(device == null ? null : device.getName());
                }
            }
        }
        return PageRes.build(info, list);
    }

    @Autowired
    KwsCompanyMapper companyMapper;


    @Transactional
    public HttpResult deviceBind(BindDevice bindDevice, HttpServletRequest request) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bindDevice.getInstallTime())) {
            return HttpResult.error("安装设备时间不能为空");
        }
        HeaderData headerData = commonService.getHeaderData(request);
        Long projectId = Long.parseLong(bindDevice.getProjectId());
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>().eq(KwsProject::getId, projectId));
        String mountainId = project.getMountainNewId();
        KwsCompany kwsCompany = companyMapper.selectByPrimaryKey(Long.parseLong(mountainId));
        if (kwsCompany == null) {
            log.error("projectId:{},mountainId:{}", projectId, mountainId);
            throw new BusinessException("公司信息获取异常");
        }
        List<Long> list = StringUtils.splitStrToList(bindDevice.getDeviceIds(), Long.class);
        String bindDeviceId = bindDevice.getBindDeviceId();
        //设备主从绑定
        List<KwsDeviceRelation> saveList = new ArrayList<>();
        StringBuilder deviceName = new StringBuilder();
        List<KwsDevice> kwsDevices = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
                .eq(KwsDevice::getDelFlag, 0)
                .in(KwsDevice::getId, list));
        if (CollectionUtils.isEmpty(kwsDevices)) {
            throw new BusinessException("需要关联设备不存在");
        }
        for (int i = 0; i < kwsDevices.size(); i++) {
            if (i != kwsDevices.size() - 1) {
                deviceName.append(kwsDevices.get(i).getName()).append(",");
            } else {
                deviceName.append(kwsDevices.get(i).getName());
            }
        }
        list.forEach(id -> {
            String deviceId = "";
            if (bindDeviceId == null) {
                //当主设备设置关联时,未关联主设备，即当前设备为主设备
                deviceId = String.valueOf(id);
            } else {
                deviceId = bindDeviceId;
            }
            KwsDeviceRelation deviceRelation = new KwsDeviceRelation();
            deviceRelation.setId(new IdWorker(NumberConstant.ONE).nextId());
            deviceRelation.setDeviceId(Long.parseLong(deviceId));
            deviceRelation.setMountainId(headerData.getMountainId());
            deviceRelation.setCompanyId(headerData.getCompanyId());
            deviceRelation.setRelateDeviceId(id);
            deviceRelation.setStatus(NumberConstant.ZERO);
            deviceRelation.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
            LocalDateTime now = LocalDateTime.now();
            deviceRelation.setCreateTime(now);
            deviceRelation.setUpdateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
            deviceRelation.setUpdateTime(now);
            deviceRelation.setDelFlag(NumberConstant.ZERO);
            saveList.add(deviceRelation);
        });
        deviceRelationRepository.saveBatch(saveList);
        //矿山与设备绑定
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(id -> {
                KwsProjectDevice device = new KwsProjectDevice();
                device.setId(new IdWorker(NumberConstant.ONE).nextId());
                device.setProjectId(projectId);
                device.setMountainId(headerData.getMountainId());
                device.setDeviceId(id);
                device.setStatus(NumberConstant.ONE);
                device.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
                LocalDateTime now = LocalDateTime.now();
                device.setCreateTime(now);
                device.setUpdateBy(headerData.getUpdateBy() == null ? Long.parseLong(headerData.getCreateBy()) : Long.parseLong(headerData.getUpdateBy()));
                device.setUpdateTime(now);
                device.setCompanyId(headerData.getCompanyId());
                projectDeviceMapper.insert(device);
            });
        }
        LocalDateTime localDateTime;
        if (StringUtils.isNotBlank(bindDevice.getInstallTime())) {
            String installTime = bindDevice.getInstallTime();
            localDateTime = DateUtil.strToLocalDateTime(installTime);
        } else {
            localDateTime = null;
        }
        //设备修改状态
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(id -> {
                String level = "1";
                String deviceCode = "";
                String companyAllCode = kwsCompany.getCompanyAllCode();
                String maxDeviceCode = deviceMapper.getMaxDeviceCodeAndSplit(15, 6);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(maxDeviceCode)) {
                    deviceCode = companyAllCode + maxDeviceCode;
                } else {
                    deviceCode = companyAllCode + StringUtils.addZeroForNum("1", 6);
                }
                if (bindDeviceId != null) {
                    KwsDevice kwsDevice = deviceMapper.selectByPrimaryKey(Long.parseLong(bindDeviceId));
                    if (kwsDevice == null) {
                        throw new BusinessException("所属主设备id错误!");
                    }
                    kwsDevice.setInstallTime(localDateTime);
                    kwsDevice.setRelated(1);
                    kwsDevice.setOnline(0);
                    kwsDevice.setRelevanceLevel(level);
                    kwsDevice.setUpdateTime(LocalDateTime.now());
                    kwsDevice.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
                    level = "2";
                    deviceMapper.updateById(kwsDevice);
                }
                KwsDevice kwsDevice = deviceMapper.selectByPrimaryKey(id);
                deviceMapper.update(null, new LambdaUpdateWrapper<KwsDevice>()
                        .eq(KwsDevice::getId, id)
                        .set(KwsDevice::getRelevanceLevel, level)
                        .set(KwsDevice::getInstallTime, localDateTime)
                        .set(KwsDevice::getRelated, 1)
                        .set(KwsDevice::getDeviceCode, deviceCode)
                        .set(KwsDevice::getStatus, DeviceEnum.BE_CHECKING.getCode())
                        .set(KwsDevice::getOnline, 0)
                        .set(KwsDevice::getAlias, bindDevice.getAlias() == null ? kwsDevice.getName() : bindDevice.getAlias())
                        .set(KwsDevice::getUpdateTime, LocalDateTime.now())
                        .set(KwsDevice::getUpdateBy, headerData.getUpdateBy() == null ? Long.parseLong(headerData.getCreateBy()) : Long.parseLong(headerData.getUpdateBy()))
                );
            });
        }
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("deviceName", deviceName.toString());
        commonService.insertLog(MessageLogEnum.ADD_NETWORKING_DEVICE, headerData, logMap, headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        return HttpResult.ok();
    }

    public PageRes deviceBindSelect(DeviceQuery deviceQuery, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        PageHelper.startPage(deviceQuery.getPage(), deviceQuery.getPageSize());
        //查询设备与项目没有绑定的数据
//        List<ProjectDeviceVO> list = projectMapper.selectNotBindDeviceList(deviceQuery, headerData);
        List<ProjectDeviceVO> list = projectMapper.selectNotBindProjectDeviceAll(deviceQuery, headerData);
        PageInfo<ProjectDeviceVO> info = new PageInfo<>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(info, list);
        }
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.DEVICE_TYPE);
        for (ProjectDeviceVO projectDeviceVO : list) {
            projectDeviceVO.setDeviceType(projectDeviceVO.getDeviceType() == null ? null :
                    (dictByDictCode == null ? projectDeviceVO.getDeviceType() :
                            (dictByDictCode.get(projectDeviceVO.getDeviceType()) == null ? projectDeviceVO.getDeviceType() :
                                    dictByDictCode.get(projectDeviceVO.getDeviceType()).getLabel())));
        }
        return PageRes.build(info, list);
    }

    public HttpResult deviceFind(DeviceQuery deviceQuery, HttpServletRequest request) {
        String projectId = deviceQuery.getProjectId();
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>().eq(KwsProject::getId, Long.parseLong(projectId)));
        if (project == null) {
            throw new BusinessException("项目查询错误！");
        }
        KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>().eq(KwsProjectArea::getProjectId, Long.parseLong(projectId)));
        List<AffiliationDeviceVO> list = deviceMapper.selectDeviceAllAndProjectData(projectId);
        ProjectAffiliationDeviceVO vo = new ProjectAffiliationDeviceVO();
        vo.setFence(area == null ? null : area.getFence());
        vo.setProjectId(projectId);
        vo.setProjectName(project.getName());
        vo.setDeviceList(list);
        return HttpResult.ok(vo);
    }

    /**
     * 边坡详情-设备要素折线图
     *
     * @param param   请求参数
     * @param request 请求头信息
     * @return 数据响应
     */
    public HttpResult chartLog(ProjectChartLogParam param, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        String latitude = param.getLatitude();
        String projectId = param.getProjectId();
        String type = param.getType();
        String startTime = "";
        String endTime = "";
        if ("4".equals(latitude)) {
            startTime = cn.hutool.core.date.DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 00:00:00";
            endTime = cn.hutool.core.date.DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 23:59:59";
        } else if ("3".equals(latitude)) {
            List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
            startTime = weekMondayAndSunday.get(0);
            endTime = weekMondayAndSunday.get(1);
        } else if ("2".equals(latitude)) {
            LocalDate firstDayOfMonth = com.sckw.excel.utils.DateUtil.getFirstDayOfMonth();
            startTime = com.sckw.excel.utils.DateUtil.dateToStr(firstDayOfMonth, "yyyy-MM-dd") /*+ " 00:00:00"*/;
            LocalDate lastDayOfMonth = com.sckw.excel.utils.DateUtil.getLastDayOfMonth();
            endTime = com.sckw.excel.utils.DateUtil.dateToStr(lastDayOfMonth, "yyyy-MM-dd")/* + " 23:59:59"*/;
        } else if ("1".equals(latitude)) {
            //查询全年每个月
            startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01";
            endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31";
        }
        if (String.valueOf(NumberConstant.FOUR).equals(latitude)) {
            String deviceId = param.getDeviceId();
            String mountainId = headerData.getMountainId();
            KwsDevice kwsDevice = deviceMapper.selectOne(new LambdaQueryWrapper<KwsDevice>()
                    .eq(KwsDevice::getId, Long.parseLong(deviceId))
                    .eq(KwsDevice::getMountainId, mountainId)
                    .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
            );
            if (kwsDevice == null) {
                return HttpResult.ok();
            }
            List<Map<String, ProjectCatLogVO>> returnList = new ArrayList<>();
            Map<String, SystemDict> dictByDictCode = new HashMap<>();
            if (Objects.nonNull(type)) {
                dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
                if (dictByDictCode.get(type) != null) {
                    //当前设备下的所有基本要素
                    basicItem(mountainId, projectId, deviceId, kwsDevice, startTime, endTime, returnList, type);
                } else {
                    //集成要素 折线图
                    //集成要素-测量值计算
                    integrationItem(headerData, deviceId, kwsDevice, startTime, endTime, returnList, type);
                }
            } else {
                //当前设备下的所有基本要素
                basicItem(mountainId, projectId, deviceId, kwsDevice, startTime, endTime, returnList, type);
                //集成要素 折线图
                //集成要素-测量值计算
                integrationItem(headerData, deviceId, kwsDevice, startTime, endTime, returnList, type);
            }
            returnList = returnList.stream().distinct().collect(Collectors.toList());
            return HttpResult.ok(returnList);
        } else if (String.valueOf(NumberConstant.THREE).equals(latitude)) {
            String deviceId = param.getDeviceId();
            String mountainId = headerData.getMountainId();
            KwsDevice kwsDevice = deviceMapper.selectOne(new LambdaQueryWrapper<KwsDevice>()
                    .eq(KwsDevice::getId, Long.parseLong(deviceId))
                    .eq(KwsDevice::getMountainId, mountainId)
                    .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
            );
            if (kwsDevice == null) {
                return HttpResult.ok();
            }
            List<Map<String, ProjectCatLogVO>> returnList = new ArrayList<>();
            Map<String, SystemDict> dictByDictCode = new HashMap<>();
            if (Objects.nonNull(type)) {
                dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
                if (dictByDictCode.get(type) != null) {
                    List<Date> dateTimeDay = DateUtil.getDateTimeDayToDate(LocalDateTime.now(), 7, new ArrayList<>());
                    //当前设备下的所有基本要素
                    basicItemByWeek(mountainId, projectId, deviceId, kwsDevice, returnList, dateTimeDay, type);
                } else {
                    //集成要素-测量值计算
                    integrationItemWeek(headerData, deviceId, kwsDevice, returnList, type);
                }
            } else {
                List<Date> dateTimeDay = DateUtil.getDateTimeDayToDate(LocalDateTime.now(), 7, new ArrayList<>());
                //当前设备下的所有基本要素
                basicItemByWeek(mountainId, projectId, deviceId, kwsDevice, returnList, dateTimeDay, type);
                integrationItemWeek(headerData, deviceId, kwsDevice, returnList, type);
            }
            return HttpResult.ok(returnList);
        } else if (String.valueOf(NumberConstant.TWO).equals(latitude)) {
        } else if (String.valueOf(NumberConstant.ONE).equals(latitude)) {
        } else {
            throw new BusinessException("数据传输异常");
        }
        return HttpResult.ok();
    }

    private void integrationItemWeek(HeaderData headerData, String deviceId, KwsDevice kwsDevice, List<Map<String, ProjectCatLogVO>> returnList, String type) {
        List<KwsDeviceIntegration> deviceIntegrations = deviceIntegrationMapper.selectList(new LambdaQueryWrapper<KwsDeviceIntegration>()
                .eq(KwsDeviceIntegration::getMountainId, headerData.getMountainId())
                .eq(KwsDeviceIntegration::getDeviceId, deviceId)
        );
        List<Long> longList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(deviceIntegrations)) {
            longList = deviceIntegrations.stream().map(KwsDeviceIntegration::getIntegrationId).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(longList)) {
            List<KwsIntegration> kwsIntegrations = integrationMapper.selectList(new LambdaQueryWrapper<KwsIntegration>()
                    .in(KwsIntegration::getId, longList)
                    .eq(org.apache.commons.lang3.StringUtils.isNotBlank(type), KwsIntegration::getIntegrationName, type));
            if (!CollectionUtils.isEmpty(kwsIntegrations) && kwsIntegrations.size() > 0) {
                kwsIntegrations.forEach(integration -> {
                    Map<String, ProjectCatLogVO> returnMap = new HashMap<>(NumberConstant.SIXTEEN);
                    ProjectCatLogVO projectCatLogVO = new ProjectCatLogVO();
                    String integrationName = integration.getIntegrationName();
                    String partNames = integration.getPartNames();
                    List<KwsDeviceReference> referenceList = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
                            .eq(KwsDeviceReference::getMountainId, headerData.getMountainId())
                            .eq(KwsDeviceReference::getDeviceId, Long.parseLong(deviceId))
                            .eq(KwsDeviceReference::getItem, integrationName)
                            .eq(KwsDeviceReference::getDelFlag, 0)
                            .eq(KwsDeviceReference::getType, 2)
                    );
                    //当前基准值
                    projectCatLogVO.setReference(CollectionUtils.isEmpty(referenceList) ? null :
                            (referenceList.get(0).getCurrentValue() == null ? null : referenceList.get(0).getCurrentValue()));
                    //当前要素阈值
                    List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                            .eq(KwsThreshold::getDelFlag, 0)
                            .eq(KwsThreshold::getItemName, integrationName)
                            .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                            .eq(KwsThreshold::getDeviceId, deviceId)
                    );
                    Map<Integer, List<KwsThreshold>> listMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(kwsThresholds)) {
                        listMap = kwsThresholds.stream().collect(Collectors.groupingBy(KwsThreshold::getLevel));
                    }
                    //阈值等级map
//                Map<String, Map<String, String>> thresholdMap = new HashMap<>();
//                Map<String, String> map = new HashMap<>();
                    ThresholdLevelVO thresholdLevelVO = new ThresholdLevelVO();
                    String thresholdMax = "";
                    String thresholdMin = "";
                    if (listMap.get(1) != null) {
                        KwsThreshold kwsThreshold = listMap.get(1).get(0);
                        thresholdMax = kwsThreshold.getMax();
                        thresholdMin = kwsThreshold.getMin();
                        thresholdLevelVO.setThresholdMax(thresholdMax);
                        thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                    }
//                thresholdMap.put("oneLevelAlarm", map);
                    projectCatLogVO.setOneLevelAlarm(thresholdLevelVO);
                    if (listMap.get(2) != null) {
                        KwsThreshold kwsThreshold = listMap.get(2).get(0);
                        thresholdMax = kwsThreshold.getMax();
                        thresholdMin = kwsThreshold.getMin();
                        thresholdLevelVO.setThresholdMax(thresholdMax);
                        thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                    }
//                thresholdMap.put("twoLevelAlarm", map);
                    projectCatLogVO.setTwoLevelAlarm(thresholdLevelVO);

                    if (listMap.get(3) != null) {
                        KwsThreshold kwsThreshold = listMap.get(3).get(0);
                        thresholdMax = kwsThreshold.getMax();
                        thresholdMin = kwsThreshold.getMin();
                        thresholdLevelVO.setThresholdMax(thresholdMax);
                        thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                    }
//                thresholdMap.put("threeLevelAlarm", map);
                    projectCatLogVO.setThreeLevelAlarm(thresholdLevelVO);

                    //当前测量值-TD获取
                    String formula = integration.getFormula();
                    List<String> stringList = StringUtils.splitStrToList(partNames, String.class);
                    if (!CollectionUtils.isEmpty(stringList)) {
                        for (String item : stringList) {
                            //当前仅有加速度
                            BigDecimal decimal = new BigDecimal("0.00");
                            Date date = new Date();
                            String dateStart = DateUtil.getDateTimeToHour(date, 23);
                            String dateEnd = DateUtil.localDateTimeFormat(LocalDateTime.now());
                            List<SlopeData> selected = null;
                            try {
                                selected = slopeDataMapper.selectLineList(kwsDevice.getSnCode(), item, dateStart, dateEnd);
                            } catch (Exception e) {
                                log.error("select tdengine devices error :{}", e.getMessage(), e);
                            }
                            List<DevicesAlarmLogVO> mapList = new ArrayList<>();
                            if (!CollectionUtils.isEmpty(selected)) {
                                for (int i = 0; i < selected.size(); i++) {
                                    DevicesAlarmLogVO map = new DevicesAlarmLogVO();
                                    SlopeData currSlopeData = selected.get(i);
//                                    String key = currSlopeData.getTs().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH"));
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
                                    String key = simpleDateFormat.format(currSlopeData.getTs());
                                    SlopeData lastSlopeData = selected.get(i + 1);
                                    Date localDateTime = currSlopeData.getTs();
                                    long epochMilli1 = 0L;
                                    String val2 = "0";
                                    Date localDateTime1 = lastSlopeData.getTs();
                                    if (lastSlopeData != null) {
//                                        epochMilli1 = localDateTime1.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                                        epochMilli1 = localDateTime1.getTime();
                                        val2 = lastSlopeData.getVal();
                                    }
//                                    long epochMilli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                                    long epochMilli = localDateTime.getTime();
//                                    epochMilli1 = localDateTime1.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                                    epochMilli1 = localDateTime1.getTime();
                                    String val1 = currSlopeData.getVal();
                                    long t = (epochMilli - epochMilli1) / (60 * 60 * 1000);
                                    long val = Long.parseLong(val1) - Long.parseLong(val2);
                                    decimal = BigDecimal.valueOf(val).divide((new BigDecimal(t).multiply(new BigDecimal(t))), 9, BigDecimal.ROUND_HALF_UP);
                                    map.setDateTime(key);
                                    map.setDataValue(decimal.toString());
                                    mapList.add(map);
                                }
                            } else {
                                List<String> dateTimeHour = DateUtil.getDateTimeHour(date, 23, new ArrayList<String>());
                                for (String s : dateTimeHour) {
                                    DevicesAlarmLogVO datemap = new DevicesAlarmLogVO();
                                    datemap.setDateTime(s);
                                    datemap.setDataValue("0");
                                    mapList.add(datemap);
                                }
                            }
                            projectCatLogVO.setType(integrationName);
                            projectCatLogVO.setMonitor(mapList);
                            returnMap.put(integrationName, projectCatLogVO);
                            returnList.add(returnMap);
                        }
                    }
                });
            }
        }
    }

    /**
     * 周为纬度  折线图计算
     *
     * @param mountainId 所属企业
     * @param projectId  所属项目
     * @param deviceId   所属设备
     * @param kwsDevice  设备信息
     * @param returnList 返回数据
     * @param dateList   时间范围
     */
    private void basicItemByWeek(String mountainId, String projectId, String deviceId, KwsDevice kwsDevice, List<Map<String, ProjectCatLogVO>> returnList, List<Date> dateList, String type) {
        List<ProjectDeviceVO> projectDeviceList = projectMapper.selectDeviceByProjectId(mountainId, Long.parseLong(projectId), Long.parseLong(deviceId), type);
        if (!CollectionUtils.isEmpty(projectDeviceList)) {
            for (ProjectDeviceVO projectDeviceVO : projectDeviceList) {
                Map<String, ProjectCatLogVO> returnMap = new HashMap<>();
                ProjectCatLogVO returnVO = new ProjectCatLogVO();
                String partName = projectDeviceVO.getPartName();
                Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
                String itemName = dictByDictCode.get(partName) == null ? partName : dictByDictCode.get(partName).getLabel();
                //设置过阈值的基本要素
                List<KwsDeviceReference> references = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
                        .eq(KwsDeviceReference::getDeviceId, deviceId)
                        .eq(KwsDeviceReference::getMountainId, mountainId)
                        .eq(KwsDeviceReference::getType, 1)
                        .eq(KwsDeviceReference::getItem, partName)
                        .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                );
                KwsDeviceReference deviceReference = new KwsDeviceReference();
                if (!CollectionUtils.isEmpty(references)) {
                    deviceReference = references.get(0);
                }
                //基准值
                BigDecimal currentValue = deviceReference.getCurrentValue();
                List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                        .eq(KwsThreshold::getDelFlag, 0)
                        .eq(KwsThreshold::getItemName, partName)
                        .eq(KwsThreshold::getMountainId, mountainId)
                        .eq(KwsThreshold::getDeviceId, deviceId)
                );
                Map<Integer, List<KwsThreshold>> listMap = new HashMap<>();
                if (!CollectionUtils.isEmpty(kwsThresholds)) {
                    listMap = kwsThresholds.stream().collect(Collectors.groupingBy(KwsThreshold::getLevel));
                }
                ThresholdLevelVO thresholdLevelVO = new ThresholdLevelVO();
                String thresholdMax = "";
                String thresholdMin = "";
                if (listMap.get(1) != null) {
                    KwsThreshold kwsThreshold = listMap.get(1).get(0);
                    thresholdMax = kwsThreshold.getMax();
                    thresholdMin = kwsThreshold.getMin();
                    thresholdLevelVO.setThresholdMax(thresholdMax);
                    thresholdLevelVO.setThresholdMin(thresholdMin);
                }
                returnVO.setOneLevelAlarm(thresholdLevelVO);
                if (listMap.get(2) != null) {
                    KwsThreshold kwsThreshold = listMap.get(2).get(0);
                    thresholdMax = kwsThreshold.getMax();
                    thresholdMin = kwsThreshold.getMin();
                    thresholdLevelVO.setThresholdMax(thresholdMax);
                    thresholdLevelVO.setThresholdMin(thresholdMin);
                }
                returnVO.setTwoLevelAlarm(thresholdLevelVO);
                if (listMap.get(3) != null) {
                    KwsThreshold kwsThreshold = listMap.get(3).get(0);
                    thresholdMax = kwsThreshold.getMax();
                    thresholdMin = kwsThreshold.getMin();
                    thresholdLevelVO.setThresholdMax(thresholdMax);
                    thresholdLevelVO.setThresholdMin(thresholdMin);
                }
                returnVO.setThreeLevelAlarm(thresholdLevelVO);
                //时间统计轴(当前数据检测值)
                List<DevicesAlarmLogVO> mapList = new ArrayList<>();
                if (currentValue != null) {
//                    Date date = new Date();
                    for (int i = 0; i < dateList.size(); i++) {
                        String dateStart = DateUtil.getDateTimeToHour(dateList.get(i), 23);
                        String dateEnd = DateUtil.localDateTimeFormat(LocalDateTime.now());
//                        String dateEnd = DateUtil.getDateTimeEndToHour(dateList.get(i), 23);
                        List<SlopeData> selected = null;
                        try {
                            selected = slopeDataMapper.selectLineList(kwsDevice.getSnCode(), partName, dateStart, dateEnd);
                        } catch (Exception e) {
                            log.error("select tdengine devices error :{}", e.getMessage(), e);
                        }
                        if (!CollectionUtils.isEmpty(selected)) {
                            for (SlopeData message : selected) {
                                /**存在经纬度海拔值的需要公式计算*/
                                List<String> itemList = new ArrayList<>();
                                itemList.add(DictItemEnum.LONGITUDE_X.getValue());
                                BigDecimal offsetValue = new BigDecimal("0.00");
                                DevicesAlarmLogVO datemap = new DevicesAlarmLogVO();
                                Date createTime = message.getTs();
//                                String key = createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH"));
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                                String key = simpleDateFormat.format(createTime);
                                String line = message.getLine();
                                String val1 = message.getVal();
                                if (itemList.contains(partName)) {
                                    if (Objects.nonNull(currentValue)) {
                                        SlopeData selectListByLine = slopeDataMapper.selectListByLine(kwsDevice.getSnCode(), DictItemEnum.LATITUDE_Y.getValue());
                                        double angleInRadians = Math.toRadians(selectListByLine == null ? 0L : Double.parseDouble(selectListByLine.getVal()));
                                        double cosValue = Math.cos(angleInRadians);
                                        if (org.apache.commons.lang3.StringUtils.isNotBlank(val1)) {
                                            double doubleValue = (new BigDecimal(val1).subtract(currentValue)).divide(new BigDecimal(360), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
                                            offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
                                        }
                                    }
                                }
                                itemList.clear();
                                itemList.add(DictItemEnum.LATITUDE_Y.getValue());
                                if (itemList.contains(partName)) {
                                    if (Objects.nonNull(currentValue)) {
                                        if (org.apache.commons.lang3.StringUtils.isNotBlank(line)) {
                                            SlopeData selectListByLine = slopeDataMapper.selectListByLine(kwsDevice.getSnCode(), DictItemEnum.LATITUDE_Y.getValue());
                                            offsetValue = selectListByLine == null ? new BigDecimal("0.00") : ((new BigDecimal(selectListByLine.getVal()).subtract(currentValue)).multiply(new BigDecimal(LATITUDE_REFERENCE)));
                                        }
                                    }
                                }
                                itemList.clear();
                                itemList.add(DictItemEnum.ALTITUDE_Z.getValue());
                                if (itemList.contains(partName)) {
                                    if (Objects.nonNull(currentValue)) {
                                        if (org.apache.commons.lang3.StringUtils.isNotBlank(line)) {
                                            SlopeData selectListByLine = slopeDataMapper.selectListByLine(kwsDevice.getSnCode(), DictItemEnum.ALTITUDE_Z.getValue());
                                            offsetValue = selectListByLine == null ? new BigDecimal("0.00") : new BigDecimal(selectListByLine.getVal()).divide(new BigDecimal(1000), 9, BigDecimal.ROUND_HALF_UP);
                                        }
                                    }
                                }
                                datemap.setDateTime(key);
                                datemap.setDataValue(offsetValue.toString());
                                mapList.add(datemap);
                            }
                        } else {
                            List<String> dateTimeHour = DateUtil.getDateTimeHour(dateList.get(i), 23, new ArrayList<String>());
                            for (String s : dateTimeHour) {
                                DevicesAlarmLogVO datemap = new DevicesAlarmLogVO();
                                datemap.setDateTime(s);
                                datemap.setDataValue("0");
                                mapList.add(datemap);
                            }
                        }
                    }
                }
                returnVO.setType(partName);
                returnVO.setMonitor(mapList);
                returnMap.put(itemName, returnVO);
                returnList.add(returnMap);
            }
        }
    }

    /**
     * 集成要素折线图计算
     */
    private void integrationItem(HeaderData headerData, String deviceId, KwsDevice kwsDevice, String startTime, String endTime, List<Map<String, ProjectCatLogVO>> returnList, String type) {
        List<KwsDeviceIntegration> deviceIntegrations = deviceIntegrationMapper.selectList(new LambdaQueryWrapper<KwsDeviceIntegration>()
                .eq(KwsDeviceIntegration::getMountainId, headerData.getMountainId())
                .eq(KwsDeviceIntegration::getDeviceId, deviceId)
        );
        List<Long> longList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(deviceIntegrations)) {
            longList = deviceIntegrations.stream().map(KwsDeviceIntegration::getIntegrationId).collect(Collectors.toList());
        }
        if (!CollectionUtils.isEmpty(longList)) {
            List<KwsIntegration> kwsIntegrations = integrationMapper.selectList(new LambdaQueryWrapper<KwsIntegration>()
                    .in(KwsIntegration::getId, longList)
                    .eq(org.apache.commons.lang3.StringUtils.isNotBlank(type), KwsIntegration::getIntegrationName, type));
            if (!CollectionUtils.isEmpty(kwsIntegrations) && kwsIntegrations.size() > 0) {
                kwsIntegrations.forEach(integration -> {
                    Map<String, ProjectCatLogVO> returnMap = new HashMap<>(NumberConstant.SIXTEEN);
                    ProjectCatLogVO projectCatLogVO = new ProjectCatLogVO();
                    String integrationName = integration.getIntegrationName();
                    String partNames = integration.getPartNames();
                    List<KwsDeviceReference> referenceList = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
                            .eq(KwsDeviceReference::getMountainId, headerData.getMountainId())
                            .eq(KwsDeviceReference::getDeviceId, Long.parseLong(deviceId))
                            .eq(KwsDeviceReference::getItem, integrationName)
                            .eq(KwsDeviceReference::getDelFlag, 0)
                            .eq(KwsDeviceReference::getType, 2)
                    );
                    //当前基准值
                    projectCatLogVO.setReference(CollectionUtils.isEmpty(referenceList) ? null :
                            (referenceList.get(0).getCurrentValue() == null ? null : referenceList.get(0).getCurrentValue()));
                    //当前要素阈值
                    List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                            .eq(KwsThreshold::getDelFlag, 0)
                            .eq(KwsThreshold::getItemName, integrationName)
                            .eq(KwsThreshold::getMountainId, headerData.getMountainId())
                            .eq(KwsThreshold::getDeviceId, deviceId)
                    );
                    Map<Integer, List<KwsThreshold>> listMap = new HashMap<>();
                    if (!CollectionUtils.isEmpty(kwsThresholds)) {
                        listMap = kwsThresholds.stream().collect(Collectors.groupingBy(KwsThreshold::getLevel));
                    }
                    //阈值等级map
//                Map<String, Map<String, String>> thresholdMap = new HashMap<>();
//                Map<String, String> map = new HashMap<>();
                    ThresholdLevelVO thresholdLevelVO = new ThresholdLevelVO();
                    String thresholdMax = "0";
                    String thresholdMin = "0";
                    if (listMap.get(1) != null) {
                        KwsThreshold kwsThreshold = listMap.get(1).get(0);
                        thresholdMax = kwsThreshold.getMax();
                        thresholdMin = kwsThreshold.getMin();
                        thresholdLevelVO.setThresholdMax(thresholdMax);
                        thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                    }
//                thresholdMap.put("oneLevelAlarm", map);
                    projectCatLogVO.setOneLevelAlarm(thresholdLevelVO);
                    if (listMap.get(2) != null) {
                        KwsThreshold kwsThreshold = listMap.get(2).get(0);
                        thresholdMax = kwsThreshold.getMax();
                        thresholdMin = kwsThreshold.getMin();
                        thresholdLevelVO.setThresholdMax(thresholdMax);
                        thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                    }
//                thresholdMap.put("twoLevelAlarm", map);
                    projectCatLogVO.setTwoLevelAlarm(thresholdLevelVO);

                    if (listMap.get(3) != null) {
                        KwsThreshold kwsThreshold = listMap.get(3).get(0);
                        thresholdMax = kwsThreshold.getMax();
                        thresholdMin = kwsThreshold.getMin();
                        thresholdLevelVO.setThresholdMax(thresholdMax);
                        thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                    }
//                thresholdMap.put("threeLevelAlarm", map);
                    projectCatLogVO.setThreeLevelAlarm(thresholdLevelVO);

                    //当前测量值-TD获取
                    String formula = integration.getFormula();
                    List<String> stringList = StringUtils.splitStrToList(partNames, String.class);
                    if (!CollectionUtils.isEmpty(stringList)) {
                        for (String item : stringList) {
                            //当前仅有加速度
                            BigDecimal decimal = new BigDecimal("0.00");
                            Date date = new Date();
                            String dateStart = DateUtil.getDateTimeToHour(date, 23);
                            String dateEnd = DateUtil.localDateTimeFormat(LocalDateTime.now());
                            String snCode = kwsDevice.getSnCode();
                            try {
                                InsTables insTables = insTablesMapper.selectTableIsExit("devicesv2_" + snCode);
                                if (insTables == null) {
                                    insTablesMapper.createTable("devicesv2_" + snCode);
                                }
                            } catch (Exception e) {
                                continue;
                            }
                            List<SlopeData> selected = null;
                            try {
                                selected = slopeDataMapper.selectLineList(kwsDevice.getSnCode(), item, dateStart, dateEnd);
                            } catch (Exception e) {
                                log.error("select tdengine devices error :{}", e.getMessage(), e);
                            }
                            List<DevicesAlarmLogVO> mapList = new ArrayList<>();
                            if (!CollectionUtils.isEmpty(selected)) {
                                for (int i = 0; i < selected.size(); i++) {
                                    DevicesAlarmLogVO map = new DevicesAlarmLogVO();
                                    SlopeData currSlopeData = selected.get(i);
//                                    String key = currSlopeData.getTs().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH"));
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");
                                    String key = simpleDateFormat.format(currSlopeData.getTs());
                                    if (i == selected.size() - 1) {
//                                        Date localDateTime = currSlopeData.getTs();
//                                        long epochMilli1 = 0L;
//                                        String val2 = "0";
//                                        long epochMilli = localDateTime.getTime();
//                                        String val1 = currSlopeData.getVal();
//                                        long t = (epochMilli - epochMilli1) / (60 * 60 * 1000);
//                                        long val = Long.parseLong(val1) - Long.parseLong(val2);
//                                        decimal = BigDecimal.valueOf(val).divide((new BigDecimal(t).multiply(new BigDecimal(t))), 9, BigDecimal.ROUND_HALF_UP);
                                        map.setDateTime(key);
                                        map.setDataValue(decimal.toString());
                                        mapList.add(map);
                                    } else {
                                        SlopeData lastSlopeData = selected.get(i + 1);
                                        Date localDateTime = currSlopeData.getTs();
                                        long epochMilli1 = 0L;
                                        String val2 = "0";
                                        Date localDateTime1 = lastSlopeData.getTs();
                                        if (lastSlopeData != null) {
//                                        epochMilli1 = localDateTime1.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                                            epochMilli1 = localDateTime1.getTime();
                                            val2 = lastSlopeData.getVal();
                                        }
//                                    long epochMilli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                                        long epochMilli = localDateTime.getTime();
//                                    epochMilli1= localDateTime1.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                                        epochMilli1 = localDateTime1.getTime();
                                        String val1 = currSlopeData.getVal();
                                        long t = (epochMilli - epochMilli1) / (60 * 60 * 1000);
                                        long val = Long.parseLong(val1) - Long.parseLong(val2);
                                        decimal = BigDecimal.valueOf(val).divide((new BigDecimal(t).multiply(new BigDecimal(t))), 9, BigDecimal.ROUND_HALF_UP);
//                                        map.put(key, decimal);
                                        map.setDataValue(decimal.toString());
                                        map.setDateTime(key);
                                        mapList.add(map);
                                    }
                                }
                                projectCatLogVO.setType(integrationName);
                                projectCatLogVO.setMonitor(mapList);
                                returnMap.put(integrationName, projectCatLogVO);
                                returnList.add(returnMap);
                            } else {
                                List<String> dateTimeHour = DateUtil.getDateTimeHour(date, 23, new ArrayList<String>());
                                dateTimeHour.forEach(dateTime -> {
                                    DevicesAlarmLogVO map = new DevicesAlarmLogVO();
                                    map.setDataValue("0");
                                    map.setDateTime(dateTime);
                                    mapList.add(map);
                                });
                            }
                        }
                    }
                });
            }
        }
    }

    /**
     * 折线图 基本要素
     */
    private void basicItem(String mountainId, String projectId, String deviceId, KwsDevice kwsDevice, String startTime, String endTime, List<Map<String, ProjectCatLogVO>> returnList, String type) {
        List<ProjectDeviceVO> projectDeviceList = projectMapper.selectDeviceByProjectId(mountainId, Long.parseLong(projectId), Long.parseLong(deviceId), type);
        if (!CollectionUtils.isEmpty(projectDeviceList)) {
            for (ProjectDeviceVO projectDeviceVO : projectDeviceList) {
                Map<String, ProjectCatLogVO> returnMap = new HashMap<>();
                ProjectCatLogVO returnVO = new ProjectCatLogVO();
                String partName = projectDeviceVO.getPartName();
                Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
                String itemName = dictByDictCode.get(partName) == null ? partName : dictByDictCode.get(partName).getLabel();
                //设置过阈值的基本要素
                List<KwsDeviceReference> references = deviceReferenceMapper.selectList(new LambdaQueryWrapper<KwsDeviceReference>()
                        .eq(KwsDeviceReference::getDeviceId, deviceId)
                        .eq(KwsDeviceReference::getMountainId, mountainId)
                        .eq(KwsDeviceReference::getType, 1)
                        .eq(KwsDeviceReference::getItem, partName)
                        .eq(KwsDeviceReference::getDelFlag, NumberConstant.ZERO)
                );
                KwsDeviceReference deviceReference = new KwsDeviceReference();
                if (!CollectionUtils.isEmpty(references)) {
                    deviceReference = references.get(0);
                }
                //基准值
                BigDecimal currentValue = deviceReference == null ? null : deviceReference.getCurrentValue();
                returnVO.setReference(currentValue);
                List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                        .eq(KwsThreshold::getDelFlag, 0)
                        .eq(KwsThreshold::getItemName, partName)
                        .eq(KwsThreshold::getMountainId, mountainId)
                        .eq(KwsThreshold::getDeviceId, deviceId)
                );
                Map<Integer, List<KwsThreshold>> listMap = new HashMap<>();
                if (!CollectionUtils.isEmpty(kwsThresholds)) {
                    listMap = kwsThresholds.stream().collect(Collectors.groupingBy(KwsThreshold::getLevel));
                }
                //阈值等级map
//                Map<String, Map<String, String>> thresholdMap = new HashMap<>();
//                Map<String, String> map = new HashMap<>();
                ThresholdLevelVO thresholdLevelVO = new ThresholdLevelVO();
                String thresholdMax = "0";
                String thresholdMin = "0";
                if (listMap.get(1) != null) {
                    KwsThreshold kwsThreshold = listMap.get(1).get(0);
                    thresholdMax = kwsThreshold.getMax();
                    thresholdMin = kwsThreshold.getMin();
                    thresholdLevelVO.setThresholdMax(thresholdMax);
                    thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                }
//                thresholdMap.put("oneLevelAlarm", map);
                returnVO.setOneLevelAlarm(thresholdLevelVO);
                if (listMap.get(2) != null) {
                    KwsThreshold kwsThreshold = listMap.get(2).get(0);
                    thresholdMax = kwsThreshold.getMax();
                    thresholdMin = kwsThreshold.getMin();
                    thresholdLevelVO.setThresholdMax(thresholdMax);
                    thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                }
//                thresholdMap.put("twoLevelAlarm", map);
                returnVO.setTwoLevelAlarm(thresholdLevelVO);

                if (listMap.get(3) != null) {
                    KwsThreshold kwsThreshold = listMap.get(3).get(0);
                    thresholdMax = kwsThreshold.getMax();
                    thresholdMin = kwsThreshold.getMin();
                    thresholdLevelVO.setThresholdMax(thresholdMax);
                    thresholdLevelVO.setThresholdMin(thresholdMin);
//                    map.put("thresholdMax", thresholdMax);
//                    map.put("thresholdMin", thresholdMin);
                }
//                thresholdMap.put("threeLevelAlarm", map);
                returnVO.setThreeLevelAlarm(thresholdLevelVO);
                //时间统计轴(当前数据检测值)
                List<DevicesAlarmLogVO> mapList = new ArrayList<>();
                Date date = new Date();
                if (currentValue != null) {
                    /**存在经纬度海拔值的需要公式计算*/
                    List<String> itemList = new ArrayList<>();
                    itemList.add(DictItemEnum.LONGITUDE_X.getValue());
                    String dateStart = DateUtil.getDateTimeToHour(date, 23);
                    String dateEnd = DateUtil.localDateTimeFormat(LocalDateTime.now());
                    List<SlopeData> selected = null;
                    try {
                        selected = slopeDataMapper.selectLineList(kwsDevice.getSnCode(), partName, dateStart, dateEnd);
                    } catch (Exception e) {
                        log.error("select tdengine devices error :{}", e.getMessage(), e);
                    }
                    if (!CollectionUtils.isEmpty(selected)) {
                        for (SlopeData message : selected) {
                            BigDecimal offsetValue = new BigDecimal("0.00");
                            DevicesAlarmLogVO datemap = new DevicesAlarmLogVO();
                            Date createTime = message.getTs();
//                            String key = createTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH"));
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH");
                            String key = format.format(createTime);
                            String line = message.getLine();
                            String val1 = message.getVal();
                            if (itemList.contains(partName)) {
                                if (Objects.nonNull(currentValue)) {
                                    SlopeData selectListByLine = slopeDataMapper.selectListByLine(kwsDevice.getSnCode(), DictItemEnum.LATITUDE_Y.getValue());
                                    double angleInRadians = Math.toRadians(selected == null ? 0L : (selectListByLine == null ? 0L : Double.parseDouble(selectListByLine.getVal())));
                                    double cosValue = Math.cos(angleInRadians);
                                    if (org.apache.commons.lang3.StringUtils.isNotBlank(val1)) {
                                        BigDecimal subtract = new BigDecimal(val1).subtract(currentValue);
                                        if (subtract.compareTo(new BigDecimal("0.00")) != 0) {
                                            double doubleValue = subtract.divide(new BigDecimal("360.00"), 9, BigDecimal.ROUND_HALF_UP).doubleValue();
                                            offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
                                        }
                                    }
                                }
                            }
                            itemList.clear();
                            itemList.add(DictItemEnum.LATITUDE_Y.getValue());
                            if (itemList.contains(partName)) {
                                if (Objects.nonNull(currentValue)) {
                                    SlopeData selectListByLine = slopeDataMapper.selectListByLine(kwsDevice.getSnCode(), DictItemEnum.LATITUDE_Y.getValue());
                                    if (org.apache.commons.lang3.StringUtils.isNotBlank(line)) {
                                        offsetValue = selectListByLine == null ? new BigDecimal("0.00") : ((new BigDecimal(selectListByLine.getVal()).subtract(currentValue)).multiply(new BigDecimal(LATITUDE_REFERENCE)));
                                    }
                                }
                            }
                            itemList.clear();
                            itemList.add(DictItemEnum.ALTITUDE_Z.getValue());
                            if (itemList.contains(partName)) {
                                if (Objects.nonNull(currentValue)) {
                                    if (org.apache.commons.lang3.StringUtils.isNotBlank(line)) {
                                        SlopeData selectListByLine = slopeDataMapper.selectListByLine(kwsDevice.getSnCode(), DictItemEnum.ALTITUDE_Z.getValue());
                                        offsetValue = selectListByLine == null ? new BigDecimal("0.00") : new BigDecimal(selectListByLine.getVal()).divide(new BigDecimal(1000), 9, BigDecimal.ROUND_HALF_UP);
                                    }
                                }
                            }
                            datemap.setDateTime(key);
                            datemap.setDataValue(offsetValue.toString());
                            mapList.add(datemap);
                        }
                    } else {
                        List<String> dateTimeHour = DateUtil.getDateTimeHour(date, 23, new ArrayList<String>());
                        for (String s : dateTimeHour) {
                            DevicesAlarmLogVO datemap = new DevicesAlarmLogVO();
                            datemap.setDateTime(s);
                            datemap.setDataValue("0");
                            mapList.add(datemap);
                        }
                    }
                } else {
                    List<String> dateTimeHour = DateUtil.getDateTimeHour(date, 23, new ArrayList<String>());
                    for (String s : dateTimeHour) {
                        DevicesAlarmLogVO datemap = new DevicesAlarmLogVO();
                        datemap.setDateTime(s);
                        datemap.setDataValue("0");
                        mapList.add(datemap);
                    }
                }
                returnVO.setType(partName);
                returnVO.setMonitor(mapList);
                returnMap.put(itemName, returnVO);
                returnList.add(returnMap);
            }
        }
    }


    /**
     * 项目关联设备删除
     *
     * @param deviceDelete 设备id
     * @param request      请求数据
     * @return 返回数据
     */
    public HttpResult deviceDelete(DeviceDeleteDTO deviceDelete, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        Long projectId = Long.parseLong(deviceDelete.getProjectId());
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>().eq(KwsProject::getId, projectId));
        String deviceId = deviceDelete.getDeviceId();
        String bindDeviceId = deviceDelete.getDeviceRelationId();
        String deviceParentId = deviceDelete.getDeviceParentId();
        if (StringUtils.isBlank(bindDeviceId)) {
            return HttpResult.error("删除id并未传递");
        }
        //设备主从解绑
        //如果删除主设备  子设备也要删除
        //id集合
        List<Long> deleteList = new ArrayList<>();
        List<String> deleteDiviceList = new ArrayList<>();
        if (deviceId.equals(deviceParentId)) {
            deleteList.add(Long.parseLong(bindDeviceId));
            deleteDiviceList.add(deviceId);
            List<KwsDeviceRelation> deviceRelationList = deviceRelationMapper.selectList(
                    new LambdaQueryWrapper<KwsDeviceRelation>()
                            .eq(KwsDeviceRelation::getDeviceId, deviceId)
                            .eq(KwsDeviceRelation::getDelFlag, 0)
                            .eq(KwsDeviceRelation::getMountainId, headerData.getMountainId())
                            .ne(KwsDeviceRelation::getRelateDeviceId, deviceId)
            );
            //主设备数据
            List<KwsDeviceRelation> deviceRelation = deviceRelationMapper.selectList(
                    new LambdaQueryWrapper<KwsDeviceRelation>()
                            .eq(KwsDeviceRelation::getDeviceId, deviceId)
                            .eq(KwsDeviceRelation::getDelFlag, 0)
                            .eq(KwsDeviceRelation::getMountainId, headerData.getMountainId())
                            .eq(KwsDeviceRelation::getRelateDeviceId, deviceId)
            );
            if (deviceRelation != null) {
                deleteList.addAll(deviceRelation.stream().map(KwsDeviceRelation::getId).distinct().collect(Collectors.toList()));
            }
            if (!CollectionUtils.isEmpty(deviceRelationList) && deviceRelationList.size() > 0) {
                deleteList = deviceRelationList.stream().map(KwsDeviceRelation::getId).collect(Collectors.toList());
                deleteList.add(Long.parseLong(bindDeviceId));
            }
            if (deleteList.size() > 0 && !CollectionUtils.isEmpty(deleteList)) {
                deviceRelationMapper.update(null, new LambdaUpdateWrapper<KwsDeviceRelation>()
                        .eq(KwsDeviceRelation::getMountainId, headerData.getMountainId())
                        .set(KwsDeviceRelation::getDelFlag, 1)
                        .in(KwsDeviceRelation::getId, deleteList)
                );
            }
        } else {
            deleteList.add(Long.parseLong(bindDeviceId));
            deleteList.add(Long.parseLong(deviceId));
            deleteList.add(Long.parseLong(deviceParentId));
            deleteDiviceList.add(deviceId);
            deleteDiviceList.add(bindDeviceId);
            deleteDiviceList.add(deviceParentId);
            deviceRelationMapper.update(null, new LambdaUpdateWrapper<KwsDeviceRelation>()
                    .eq(KwsDeviceRelation::getDeviceId, deviceParentId)
                    .eq(KwsDeviceRelation::getRelateDeviceId, deviceId)
                    .set(KwsDeviceRelation::getDelFlag, 1)
                    .in(KwsDeviceRelation::getId, deleteList)
            );
//            projectDeviceMapper.update(null,
//                    new LambdaUpdateWrapper<KwsProjectDevice>()
//                            .eq(KwsProjectDevice::getDeviceId,deviceId)
//                            .eq(KwsProjectDevice::getProjectId,projectId)
//            );
        }
        //矿山与设备解绑
        if (!CollectionUtils.isEmpty(deleteDiviceList)) {
            projectDeviceMapper.update(null, new LambdaUpdateWrapper<KwsProjectDevice>()
                    .set(KwsProjectDevice::getDelFlag, 1)
                    .set(KwsProjectDevice::getUpdateBy, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()))
                    .set(KwsProjectDevice::getUpdateTime, LocalDateTime.now())
                    .eq(KwsProjectDevice::getDelFlag, 0)
                    .eq(KwsProjectDevice::getProjectId, projectId)
                    .eq(KwsProjectDevice::getMountainId, headerData.getMountainId())
                    .in(KwsProjectDevice::getDeviceId, deleteDiviceList)
            );
        }
        //设备修改状态
        if (!CollectionUtils.isEmpty(deleteDiviceList)) {
            deviceMapper.update(null, new LambdaUpdateWrapper<KwsDevice>()
                    .in(KwsDevice::getId, deleteDiviceList)
                    .eq(KwsDevice::getMountainId, headerData.getMountainId())
                    .eq(KwsDevice::getDelFlag, 0)
                    .set(KwsDevice::getRelevanceLevel, 0)
                    .set(KwsDevice::getRelated, 0)
                    .set(KwsDevice::getOnline, 0)
                    .set(KwsDevice::getInstallTime, null)
                    .set(KwsDevice::getLogicAlt, null)
                    .set(KwsDevice::getDeviceCode, null)
                    .set(KwsDevice::getLogicLat, null)
                    .set(KwsDevice::getLogicLng, null)
                    .set(KwsDevice::getStatus, DeviceEnum.NOT_IN_USE.getCode())
                    .set(KwsDevice::getUpdateTime, LocalDateTime.now())
                    .set(KwsDevice::getUpdateBy, headerData.getUpdateBy() == null ? Long.parseLong(headerData.getCreateBy()) : Long.parseLong(headerData.getUpdateBy()))
            );
        }
        if (!CollectionUtils.isEmpty(deleteDiviceList)) {
            List<KwsDevice> kwsDevices = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>().in(KwsDevice::getId, deleteDiviceList).eq(KwsDevice::getDelFlag, 0));
            if (!CollectionUtils.isEmpty(kwsDevices)) {
                StringBuilder deviceName = new StringBuilder();
                for (int i = 0; i < kwsDevices.size(); i++) {
                    if (i != kwsDevices.size() - 1) {
                        deviceName.append(kwsDevices.get(i).getName()).append(",");
                    } else {
                        deviceName.append(kwsDevices.get(i).getName());
                    }
                }
                Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
                logMap.put("projectName", project.getName());
                logMap.put("deviceName", deviceName.toString());
                commonService.insertLog(MessageLogEnum.DELETE_NETWORKING_DEVICE, headerData, logMap, headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
            }
        }
        return HttpResult.ok("删除关联设备成功!");
    }

    public HttpResult selectAll(HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        List<KwsProject> kwsProjects = projectMapper.selectList(new LambdaQueryWrapper<KwsProject>()
                .eq(KwsProject::getDelFlag, 0)
                .eq(org.apache.commons.lang3.StringUtils.isNotBlank(headerData.getCompanyId()), KwsProject::getCompanyId, headerData.getCompanyId())
        );
        Map<Long, String> projectMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(kwsProjects)) {
            projectMap = kwsProjects.stream().collect(Collectors.toMap(KwsProject::getId, KwsProject::getName));
        }
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (projectMap != null) {
            for (Map.Entry<Long, String> longStringEntry : projectMap.entrySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", longStringEntry.getValue());
                map.put("value", longStringEntry.getKey());
                returnList.add(map);
            }
        }
        return HttpResult.ok(returnList);
    }

    @Autowired
    KwsAlarmMapper alarmMapper;

    @Autowired
    KwsAlarmDetailMapper alarmDetailMapper;

    public HttpResult dataScreening(String projectId, String companyId) {
        DataScreeningVO vo = new DataScreeningVO();
        LambdaQueryWrapper<KwsProject> wrapper = new LambdaQueryWrapper<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            wrapper.eq(KwsProject::getId, Long.parseLong(projectId));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {
            wrapper.eq(KwsProject::getCompanyId, Long.parseLong(companyId));
        }
        long count = projectMapper.selectList(wrapper.eq(KwsProject::getDelFlag, 0)).stream().count();
        vo.setProjectTotal(count);
        int deviceCount = deviceMapper.selectCountByProject(projectId, companyId);
        vo.setDeviceTotal(deviceCount);
        BigDecimal area = new BigDecimal("0.00");
        LambdaQueryWrapper<KwsProject> projectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        projectLambdaQueryWrapper.eq(KwsProject::getDelFlag, 0);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            projectLambdaQueryWrapper.eq(KwsProject::getId, Long.parseLong(projectId));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {
            projectLambdaQueryWrapper.eq(KwsProject::getCompanyId, Long.parseLong(companyId));
        }
        List<KwsProject> projectList = projectMapper.selectList(projectLambdaQueryWrapper
        );
        List<Long> projectIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(projectList) && projectList.size() > 0) {
            projectIdList = projectList.stream().map(KwsProject::getId).distinct().collect(Collectors.toList());
        }
        //统计全部面积
        LambdaQueryWrapper<KwsProjectArea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KwsProjectArea::getDelFlag, 0);
        if (!CollectionUtils.isEmpty(projectIdList) && projectIdList.size() > 0) {
            queryWrapper.in(KwsProjectArea::getProjectId, projectIdList);
            area = projectAreaMapper.selectList(queryWrapper).stream().map(KwsProjectArea::getArea).reduce(BigDecimal.ZERO,
                    BigDecimal::add);
        }
        vo.setProjectTotalArea(area);
        /**仅统计设备在线的数据*/
        int deviceOnline = deviceMapper.selectDeviceOnlineRateCountByProject(projectId, companyId);
        BigDecimal deviceOnlineRate = new BigDecimal("0.00");
        if (deviceOnline != 0) {
            deviceOnlineRate = new BigDecimal(deviceOnline).divide(new BigDecimal(deviceCount), 2, RoundingMode.HALF_UP).multiply(new BigDecimal("100.00"));
        }
        vo.setDeviceOnlineRate(deviceOnlineRate);
        LocalDateTime localDateTimeEnd = LocalDateTime.now();
        LocalDateTime localDateTimeStart = LocalDateTime.now().plusHours(-24);
        KwsProject project = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            project = projectMapper.selectById(projectId);
        }
        String mountainId = "";
        if (Objects.nonNull(project)) {
            mountainId = project.getMountainId();
        }
        LambdaQueryWrapper<KwsAlarm> alarmLambdaQueryWrapper = new LambdaQueryWrapper<KwsAlarm>()
                .eq(KwsAlarm::getStatus, 0)
                .eq(KwsAlarm::getDelFlag, 0);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            alarmLambdaQueryWrapper.eq(KwsAlarm::getProjectId, Long.parseLong(projectId));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {
            alarmLambdaQueryWrapper.eq(KwsAlarm::getCompanyId, Long.parseLong(companyId));
        }
        List<KwsAlarm> kwsAlarmsCount = alarmMapper.selectList(alarmLambdaQueryWrapper);
        int alarmTotal = 0;
        if (!CollectionUtils.isEmpty(kwsAlarmsCount)) {
            alarmTotal = kwsAlarmsCount.stream().mapToInt(KwsAlarm::getTriggerTimes).sum();
        }
//        vo.setAlarmTotal(CollectionUtils.isEmpty(kwsAlarmsCount) ? 0 : kwsAlarmsCount.size());
        vo.setAlarmTotal(alarmTotal);
        int unreadAlarmTotal = 0;
        if (kwsAlarmsCount.size() > 0 && (!CollectionUtils.isEmpty(kwsAlarmsCount))) {
            LambdaQueryWrapper<KwsAlarmDetail> eq = new LambdaQueryWrapper<KwsAlarmDetail>()
                    .eq(KwsAlarmDetail::getStatus, 0)
                    .eq(KwsAlarmDetail::getDelFlag, 0)
                    .in(KwsAlarmDetail::getAlarmId, kwsAlarmsCount.stream().map(KwsAlarm::getId).distinct().collect(Collectors.toList()));
            if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
                eq.eq(KwsAlarmDetail::getAlarmId, Long.parseLong(projectId));
            }
            List<KwsAlarmDetail> unreadKwsAlarms = alarmDetailMapper.selectList(eq);
            unreadAlarmTotal = CollectionUtils.isEmpty(unreadKwsAlarms) ? 0 : unreadKwsAlarms.size();
        }
        vo.setUnreadAlarmTotal(unreadAlarmTotal);
        LambdaQueryWrapper<KwsAlarm> eqed = new LambdaQueryWrapper<KwsAlarm>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            eqed.eq(KwsAlarm::getProjectId, Long.parseLong(projectId));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {
            eqed.eq(KwsAlarm::getCompanyId, Long.parseLong(companyId));
        }
        eqed.eq(KwsAlarm::getLevel, NumberConstant.ONE);
        List<KwsAlarm> oneThresholdAlarm = alarmMapper.selectList(eqed
        );
        int oneAlarmTotal = 0;
        if (!CollectionUtils.isEmpty(oneThresholdAlarm)) {
            oneAlarmTotal = oneThresholdAlarm.stream().mapToInt(KwsAlarm::getTriggerTimes).sum();
        }
//        vo.setOneAlarmTotal(CollectionUtils.isEmpty(oneThresholdAlarm) ? 0 : oneThresholdAlarm.size());
        vo.setOneAlarmTotal(oneAlarmTotal);
        List<KwsAlarm> alarms = null;
        LambdaQueryWrapper<KwsAlarm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(KwsAlarm::getDelFlag, 0);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            lambdaQueryWrapper.eq(KwsAlarm::getProjectId, projectId);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {
            lambdaQueryWrapper.eq(KwsAlarm::getCompanyId, companyId);
        }
        alarms = alarmMapper.selectList(lambdaQueryWrapper);
        LambdaQueryWrapper<KwsAlarmDetail> lt = new LambdaQueryWrapper<KwsAlarmDetail>()
                .eq(KwsAlarmDetail::getDelFlag, 0)
                .gt(KwsAlarmDetail::getCreateTime, localDateTimeStart).lt(KwsAlarmDetail::getCreateTime, localDateTimeEnd);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(mountainId)) {
            lt.eq(KwsAlarmDetail::getMountainId, Long.parseLong(mountainId));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId)) {
            lt.eq(KwsAlarmDetail::getCompanyId, Long.parseLong(companyId));
        }
        if (alarms.size() > 0 && (!CollectionUtils.isEmpty(alarms))) {
            lt.in(KwsAlarmDetail::getAlarmId, alarms.stream().map(KwsAlarm::getId).distinct().collect(Collectors.toList()));
        }
        List<KwsAlarmDetail> kwsAlarms = alarmDetailMapper.selectList(lt
        );
        vo.setTodayAlarmTotal(CollectionUtils.isEmpty(kwsAlarms) ? 0 : kwsAlarms.size());
        return HttpResult.ok("查询成功", vo);
    }

    public HttpResult projectList(String projectId, HeaderData headerData) {
        LambdaQueryWrapper<KwsProject> wrapper = new LambdaQueryWrapper<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectId)) {
            wrapper.eq(KwsProject::getId, projectId);
        }
        wrapper.eq(KwsProject::getDelFlag, NumberConstant.ZERO)
//                .eq(KwsProject::getStatus,NumberConstant.ZERO)
        ;
        wrapper.eq(KwsProject::getCompanyId, headerData.getCompanyId());
        List<KwsProject> projectList = projectMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(projectList)) {
            return HttpResult.ok();
        }
        List<ProjectDevicesListVO> returnList = new ArrayList<>(NumberConstant.TWELVE);
        projectList.forEach(project -> {
            ProjectDevicesListVO vo = new ProjectDevicesListVO();
            Long id = project.getId();
            KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>()
                    .eq(KwsProjectArea::getProjectId, id)
                    .eq(KwsProjectArea::getDelFlag, NumberConstant.ZERO)
            );
            vo.setFence(area == null ? null : area.getFence());
            vo.setProjectId(id.toString());
            vo.setProjectName(project.getName());
            List<AffiliationDeviceVO> deviceList = deviceMapper.selectDeviceAllAndProjectData(id.toString());
            if (!CollectionUtils.isEmpty(deviceList)) {
                List<DeviceListBean> beans = new ArrayList<>();
                deviceList.forEach(device -> {
                    DeviceListBean bean = new DeviceListBean();
                    bean.setName(device.getName());
                    bean.setAttribute(device.getAttribute());
                    bean.setLogicLat(device.getLogicLat());
                    bean.setLogicLng(device.getLogicLng());
                    bean.setLogicAlt(device.getLogicLat());
                    bean.setAlias(device.getAlias());
                    bean.setDeviceId(device.getDeviceId());
                    String deviceId = device.getDeviceId();
                    Map<String, String> map = getAlarmStatus(deviceId);
                    bean.setAlarmStatus(map.get("alarmStatus"));
                    bean.setThresholdId(map.get("thresholdId"));
                    beans.add(bean);
                });
                vo.setDeviceList(beans);
            }
            returnList.add(vo);
        });
        return HttpResult.ok(returnList);
    }

    private Map<String, String> getAlarmStatus(String deviceId) {
        String alarmStatus = "0";
        String thresholdId = null;
        Map<String, String> returnMap = new HashMap<>();
        List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
                .eq(KwsThreshold::getDeviceId, Long.parseLong(deviceId))
                .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
        );
        List<KwsAlarmDetail> deviceDetails = alarmDetailMapper.selectList(
                new LambdaQueryWrapper<KwsAlarmDetail>()
                        .in(KwsAlarmDetail::getPid, deviceId)
                        .eq(KwsAlarmDetail::getDelFlag, NumberConstant.ZERO)
                        .eq(KwsAlarmDetail::getStatus, NumberConstant.ZERO)
        );
        if (!CollectionUtils.isEmpty(deviceDetails) && deviceDetails.size() > 0) {
            alarmStatus = "1";
            thresholdId = deviceDetails.get(0).getAlarmId().toString();
            returnMap.put("alarmStatus", alarmStatus);
            returnMap.put("thresholdId", thresholdId);
            return returnMap;
        }
        if (!CollectionUtils.isEmpty(kwsThresholds)) {
            List<Long> longList = kwsThresholds.stream().map(KwsThreshold::getId).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(longList) && longList.size() > 0) {
                List<KwsAlarmDetail> details = alarmDetailMapper.selectList(
                        new LambdaQueryWrapper<KwsAlarmDetail>()
                                .in(KwsAlarmDetail::getPid, longList)
                                .eq(KwsAlarmDetail::getDelFlag, NumberConstant.ZERO)
                                .eq(KwsAlarmDetail::getStatus, NumberConstant.ZERO)
                );
                if (!CollectionUtils.isEmpty(details) && details.size() > 0) {
                    List<Long> thresholdIds = details.stream().map(KwsAlarmDetail::getPid).distinct().collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(thresholdIds)) {
                        List<KwsThreshold> thresholds = thresholdMapper.selectList(
                                new LambdaQueryWrapper<KwsThreshold>()
                                        .in(KwsThreshold::getId, thresholdIds)
                                        .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
                                        .eq(KwsThreshold::getStatus, NumberConstant.ZERO)
                        );
                        if (!CollectionUtils.isEmpty(thresholds)) {
                            List<Integer> levelList = thresholds.stream().map(KwsThreshold::getLevel).sorted().distinct().collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(levelList)) {
                                alarmStatus = String.valueOf(levelList.get(0));
                            }
                            List<String> objects = new ArrayList<>();
                            objects.add("1");
                            objects.add("2");
                            objects.add("3");
                            if (objects.contains(alarmStatus)) {
                                for (KwsThreshold threshold : thresholds) {
                                    if (alarmStatus.equals(String.valueOf(threshold.getLevel()))) {
                                        List<KwsAlarmDetail> alarmDetails = alarmDetailMapper.selectList(
                                                new LambdaQueryWrapper<KwsAlarmDetail>()
                                                        .eq(KwsAlarmDetail::getPid, threshold.getId())
                                                        .eq(KwsAlarmDetail::getStatus, 0)
                                                        .eq(KwsAlarmDetail::getDelFlag, 0)
                                        );
                                        if (!CollectionUtils.isEmpty(alarmDetails) && alarmDetails.size() > 0) {
                                            thresholdId = alarmDetails.get(0).getAlarmId().toString();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        returnMap.put("alarmStatus", alarmStatus);
        returnMap.put("thresholdId", thresholdId);
        return returnMap;
    }

    /**
     * 修改组网设备-关联设备-查询
     *
     * @param id
     * @param request
     * @return
     */
    public HttpResult updateDeviceBindSelect(String id, HttpServletRequest request) {
        KwsDeviceRelation deviceRelation = deviceRelationMapper.selectOne(
                new LambdaQueryWrapper<KwsDeviceRelation>()
                        .eq(KwsDeviceRelation::getId, Long.parseLong(id))
                        .eq(KwsDeviceRelation::getDelFlag, NumberConstant.ZERO)
        );
        UpdateDeviceBindSelectVO bindSelectVO = new UpdateDeviceBindSelectVO();
        if (deviceRelation != null) {
            Long deviceId1 = deviceRelation.getDeviceId();
            KwsDevice kwsDevice = deviceMapper.selectById(deviceId1);
            bindSelectVO.setId(deviceRelation.getId());
            bindSelectVO.setDeviceId(deviceId1);
            bindSelectVO.setDeviceName(kwsDevice == null ? null : kwsDevice.getName());
            bindSelectVO.setDeviceNameAlias(kwsDevice == null ? null : kwsDevice.getAlias());
            Long relateDeviceId = deviceRelation.getRelateDeviceId();
            KwsDevice relateDevice = deviceMapper.selectById(relateDeviceId);
            bindSelectVO.setRelateDeviceId(relateDeviceId);
            bindSelectVO.setRelateDeviceName(relateDevice == null ? null : relateDevice.getName());
            bindSelectVO.setRelateDeviceAlias(relateDevice == null ? null : relateDevice.getAlias());
            bindSelectVO.setInstallTime(kwsDevice.getInstallTime() == null ? null :
                    cn.hutool.core.date.DateUtil.format(kwsDevice.getInstallTime(), "yyyy-MM-dd"));
        }
        return HttpResult.ok(bindSelectVO);
    }

    @Transactional
    public HttpResult updateDeviceBind(BindDevice bindDevice, HttpServletRequest request) {
        if (org.apache.commons.lang3.StringUtils.isBlank(bindDevice.getInstallTime())) {
            return HttpResult.error("安装设备时间不能为空");
        }
        String deviceRelationId = bindDevice.getDeviceRelationId();
        if (StringUtils.isBlank(deviceRelationId)) {
            return HttpResult.error("关联主键id不能为空");
        }
        String bindDeviceId = bindDevice.getBindDeviceId();
        String deviceIds = bindDevice.getDeviceIds();
        String alias = bindDevice.getAlias();
        String onlyId = bindDevice.getId();
        KwsDeviceRelation kwsDeviceRelation = deviceRelationMapper.selectOne(new LambdaQueryWrapper<KwsDeviceRelation>()
                .eq(KwsDeviceRelation::getId, Long.parseLong(onlyId))
                .eq(KwsDeviceRelation::getDelFlag, NumberConstant.ZERO)
        );
        if (kwsDeviceRelation == null) {
            return HttpResult.error("修改id传递错误");
        }
        HeaderData headerData = commonService.getHeaderData(request);
        /**验证主设备是否存在子设备*/
//        List<KwsDeviceRelation> deviceRelations = deviceRelationMapper.selectList(
//                new LambdaQueryWrapper<KwsDeviceRelation>()
//                        .ne(KwsDeviceRelation::getDeviceId,deviceIds)
//                        .eq(KwsDeviceRelation::getRelateDeviceId,deviceIds)
//        );
        if (!deviceIds.equals(bindDeviceId)) {
            KwsDevice selectById = deviceMapper.selectById(bindDeviceId);
            if ("2".equals(selectById.getRelevanceLevel())) {
                return HttpResult.error("所选所属设备是二级设备不可作为主设备");
            }
        }
        /**删除所存在的关联设备组网关系*/
        deviceRelationMapper.update(null,
                new LambdaUpdateWrapper<KwsDeviceRelation>()
                        .set(KwsDeviceRelation::getDelFlag, 1)
                        .set(KwsDeviceRelation::getUpdateBy, headerData.getUpdateBy())
                        .set(KwsDeviceRelation::getUpdateTime, LocalDateTime.now())
                        .eq(KwsDeviceRelation::getId, Long.parseLong(deviceRelationId))
        );

        /**删除所存在的项目设备关联关系*/
        projectDeviceMapper.update(null,
                new LambdaUpdateWrapper<KwsProjectDevice>()
                        .set(KwsProjectDevice::getDelFlag, 1)
                        .set(KwsProjectDevice::getUpdateBy, headerData.getUpdateBy())
                        .set(KwsProjectDevice::getUpdateTime, LocalDateTime.now())
                        .eq(KwsProjectDevice::getDeviceId, Long.parseLong(deviceIds))
                        .eq(KwsProjectDevice::getProjectId, Long.parseLong(bindDevice.getProjectId()))
        );


        /**新增组网设备*/
        Long projectId = Long.parseLong(bindDevice.getProjectId());
        KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>().eq(KwsProject::getId, projectId));
        String companyId = project.getCompanyId();
        List<Long> list = StringUtils.splitStrToList(deviceIds, Long.class);
        //设备主从绑定
        List<KwsDeviceRelation> saveList = new ArrayList<>();
        StringBuilder deviceName = new StringBuilder();
        List<KwsDevice> kwsDevices = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
                .eq(KwsDevice::getDelFlag, 0)
                .in(KwsDevice::getId, list));
        if (CollectionUtils.isEmpty(kwsDevices)) {
            throw new BusinessException("需要关联设备不存在");
        }
        for (int i = 0; i < kwsDevices.size(); i++) {
            if (i != kwsDevices.size() - 1) {
                deviceName.append(kwsDevices.get(i).getName()).append(",");
            } else {
                deviceName.append(kwsDevices.get(i).getName());
            }
        }
        list.forEach(id -> {
            String deviceId = "";
            if (!bindDeviceId.equals(String.valueOf(id))) {
                //当主设备设置关联时,未关联主设备，即当前设备为主设备
                deviceId = bindDeviceId;
            } else {
                deviceId = String.valueOf(id);
            }
            KwsDeviceRelation deviceRelation = new KwsDeviceRelation();
            deviceRelation.setId(new IdWorker(NumberConstant.ONE).nextId());
            deviceRelation.setDeviceId(Long.parseLong(deviceId));
            deviceRelation.setMountainId(headerData.getMountainId());
            deviceRelation.setRelateDeviceId(id);
            deviceRelation.setStatus(NumberConstant.ZERO);
            deviceRelation.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
            LocalDateTime now = LocalDateTime.now();
            deviceRelation.setCreateTime(now);
            deviceRelation.setUpdateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
            deviceRelation.setUpdateTime(now);
            deviceRelation.setDelFlag(NumberConstant.ZERO);
            saveList.add(deviceRelation);
        });
        deviceRelationRepository.saveBatch(saveList);
        //矿山与设备绑定
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(id -> {
                KwsProjectDevice device = new KwsProjectDevice();
                device.setId(new IdWorker(NumberConstant.ONE).nextId());
                device.setProjectId(projectId);
                device.setMountainId(headerData.getMountainId());
                device.setDeviceId(id);
                device.setStatus(NumberConstant.ONE);
                device.setCreateBy(headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
                LocalDateTime now = LocalDateTime.now();
                device.setCreateTime(now);
                device.setUpdateBy(headerData.getUpdateBy() == null ? Long.parseLong(headerData.getCreateBy()) : Long.parseLong(headerData.getUpdateBy()));
                device.setUpdateTime(now);
                device.setCompanyId(headerData.getCompanyId());
                projectDeviceMapper.insert(device);
            });
        }
        LocalDateTime localDateTime;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(bindDevice.getInstallTime())) {
            String installTime = bindDevice.getInstallTime();
            installTime = installTime + " 00:00:00";
            localDateTime = LocalDateTime.parse(installTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } else {
            localDateTime = null;
        }
        //设备修改状态
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(id -> {
                String level = "1";
                if (bindDeviceId != null) {
                    KwsDevice kwsDevice = deviceMapper.selectByPrimaryKey(Long.parseLong(bindDeviceId));
                    if (kwsDevice == null) {
                        throw new BusinessException("所属主设备id错误!");
                    }
                    kwsDevice.setAlias(alias);
                    kwsDevice.setRelated(1);
                    kwsDevice.setInstallTime(localDateTime);
                    kwsDevice.setRelevanceLevel(level);
                    kwsDevice.setOnline(0);
                    kwsDevice.setUpdateTime(LocalDateTime.now());
                    kwsDevice.setUpdateBy(headerData.getUpdateBy() == null ? null : Long.parseLong(headerData.getUpdateBy()));
                    level = "2";
                    deviceMapper.updateById(kwsDevice);
                }
                KwsDevice kwsDevice = deviceMapper.selectByPrimaryKey(id);
                deviceMapper.update(null, new LambdaUpdateWrapper<KwsDevice>()
                        .eq(KwsDevice::getId, id)
                        .set(KwsDevice::getRelevanceLevel, level)
                        .set(KwsDevice::getStatus, DeviceEnum.BE_CHECKING.getCode())
                        .set(KwsDevice::getInstallTime, localDateTime)
                        .set(KwsDevice::getOnline, 0)
                        .set(KwsDevice::getRelated, 1)
                        .set(KwsDevice::getAlias, bindDevice.getAlias() == null ? kwsDevice.getName() : bindDevice.getAlias())
                        .set(KwsDevice::getUpdateTime, LocalDateTime.now())
                        .set(KwsDevice::getUpdateBy, headerData.getUpdateBy() == null ? Long.parseLong(headerData.getCreateBy()) : Long.parseLong(headerData.getUpdateBy()))
                );
            });
        }
        Map<String, Object> logMap = new HashMap<>(NumberConstant.SIXTEEN);
        logMap.put("projectName", project.getName());
        logMap.put("deviceName", deviceName.toString());
        commonService.insertLog(MessageLogEnum.UPDATE_NETWORKING_DEVICE, headerData, logMap, headerData.getCreateBy() == null ? null : Long.parseLong(headerData.getCreateBy()));
        return HttpResult.ok();
    }
}
