package com.sckw.slope.detection.service;

import cn.hutool.core.date.DateUtil;
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.DictEnum;
import com.sckw.core.model.enums.DictItemEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.model.vo.BaseList;
import com.sckw.core.model.vo.PublicBaseList;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.web.response.HttpResult;
import com.sckw.slope.detection.dao.mysql.*;
import com.sckw.slope.detection.dao.tdengine.DevicesMapper;
import com.sckw.slope.detection.model.dos.mysql.*;
import com.sckw.slope.detection.model.dos.tdengine.Devices;
import com.sckw.slope.detection.model.dto.HeaderData;
import com.sckw.slope.detection.model.dto.SystemDict;
import com.sckw.slope.detection.model.param.AlarmLogThresholdExport;
import com.sckw.slope.detection.model.param.AlarmLogThresholdQuery;
import com.sckw.slope.detection.model.param.AlarmStatisticsQuery;
import com.sckw.slope.detection.model.vo.*;
import com.sckw.slope.detection.model.vo.excel.KwsAlarmExportVO;
import com.sckw.slope.detection.model.vo.excel.ThresholdRecordDetailExportVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lfdc
 * @description 告警service
 * @date 2023-11-10 15:11:29
 */
@Slf4j
@Service
public class KwsAlarmService {

    @Autowired
    CommonService commonService;

    @Autowired
    KwsDeviceMapper deviceMapper;

    @Autowired
    KwsIntegrationMapper integrationMapper;

    @Autowired
    KwsDeviceReferenceMapper deviceReferenceMapper;

    @Autowired
    KwsThresholdMapper thresholdMapper;

    @Autowired
    KwsProjectMapper projectMapper;

    @Autowired
    KwsAlarmMapper alarmMapper;

    @Autowired
    DevicesMapper devicesMapper;

    public PageRes logSelectAll(AlarmLogThresholdQuery query) {
        PageHelper.startPage(query.getPage(), query.getPageSize());
//        List<KwsAlarm> kwsAlarms = alarmMapper.selectList(new LambdaQueryWrapper<KwsAlarm>()
//                .eq(KwsAlarm::getStatus, 0)
//                .orderByDesc(KwsAlarm::getCreateTime));
        int page = query.getPage();
        int newPage = page - 1;
        List<AlarmLogThresholdVO> list = alarmMapper.selectDetailList(newPage, query.getPageSize());
        PageInfo<AlarmLogThresholdVO> info = new PageInfo<AlarmLogThresholdVO>(list);
//        List<AlarmLogThresholdVO> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(info, list);
        }
        Map<String, SystemDict> thresholdLevel = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        Map<String, SystemDict> modelPart = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        if (!CollectionUtils.isEmpty(list)) {
            for (AlarmLogThresholdVO vo : list) {
                vo.setId(vo.getId());
                vo.setMountainId(vo.getMountainId());
                vo.setItemName(vo.getVal() == null ? null : (modelPart == null ? vo.getVal() :
                        (modelPart.get(vo.getVal()) == null ? vo.getVal() : modelPart.get(vo.getVal()).getLabel())));
                vo.setTitle(vo.getTitle());
                KwsProject project = projectMapper.selectById(Long.parseLong(vo.getProjectId()));
                vo.setProjectId(vo.getProjectId());
                vo.setProjectName(project == null ? null : project.getName());
//                vo.setContent(KwsAlarm.getContent());
                vo.setLevel(vo.getLevel() == null ? null :
                        (thresholdLevel == null ? String.valueOf(vo.getLevel()) :
                                (thresholdLevel.get(vo.getLevel()) == null ? vo.getLevel().toString() : thresholdLevel.get(vo.getLevel()).getLabel())));
                vo.setCreateTime(vo.getCreateTime());
//                list.add(vo);
            }
        }
//        int count= alarmMapper.selectDetailCount();
//        info.setPageNum(query.getPage());
//        info.setPageSize(query.getPageSize());
//        info.setTotal(count);
//        int totalPages = (int) Math.ceil((double) count / query.getPageSize());
//        info.setPages(totalPages);
        return PageRes.build(info, list);
    }

    public PageRes select(AlarmLogThresholdQuery query, HttpServletRequest request) {
        HeaderData headerData = commonService.getHeaderData(request);
        PageHelper.startPage(query.getPage(), query.getPageSize());
        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(headerData.getMountainId())){
            wrapper.eq(StringUtils.isNotBlank(headerData.getMountainId()), KwsAlarm::getMountainId, headerData.getMountainId());
        }
        if (StringUtils.isNotBlank(headerData.getCompanyId())){
            wrapper.eq(StringUtils.isNotBlank(headerData.getCompanyId()), KwsAlarm::getCompanyId, headerData.getCompanyId());
        }
        wrapper.eq(KwsAlarm::getStatus, query.getStatus())
                .gt(KwsAlarm::getTriggerTimes, 0)
        ;
        if (StringUtils.isNotBlank(query.getProjectId())) {
            wrapper.eq(KwsAlarm::getProjectId, Long.parseLong(query.getProjectId()));
        }
        if (Objects.nonNull(query.getAlarmLevel()) && (0 != query.getAlarmLevel())) {
            wrapper.eq(KwsAlarm::getLevel, query.getAlarmLevel());
        }
        if (StringUtils.isNotBlank(query.getAlarmInfo())) {
            wrapper.eq(KwsAlarm::getTitle, query.getAlarmInfo());
        }
        if (StringUtils.isNotBlank(query.getDeviceId())) {
            wrapper.like(KwsAlarm::getDeviceId, query.getDeviceId());
        }
        wrapper.orderByDesc(KwsAlarm::getCreateTime);
        List<KwsAlarm> list = alarmMapper.selectListByQuery(query, headerData.getMountainId(), headerData.getCompanyId());
//        List<KwsAlarm> list = alarmMapper.selectList(wrapper);
        List<KwsAlarmVO> alarmVOS = new ArrayList<>();
        PageInfo<KwsAlarm> info = new PageInfo<KwsAlarm>(list);
        if (CollectionUtils.isEmpty(list)) {
            return PageRes.build(info, alarmVOS);
        }
        Map<String, SystemDict> thresholdLevel = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
        Map<String, SystemDict> alarmDetailType = commonService.getDictByDictCode(DictEnum.ALARM_DETAIL_TYPE);
        for (KwsAlarm kwsAlarm : list) {
            KwsDevice kwsDevice = deviceMapper.selectOne(new LambdaQueryWrapper<KwsDevice>()
                    .eq(StringUtils.isNotBlank(headerData.getMountainId()), KwsDevice::getMountainId, headerData.getMountainId())
                    .eq(KwsDevice::getId, kwsAlarm.getDeviceId()));
            KwsProject project = projectMapper.selectOne(new LambdaQueryWrapper<KwsProject>()
                    .eq(KwsProject::getId, Long.parseLong(kwsAlarm.getProjectId()))
                    .eq(StringUtils.isNotBlank(headerData.getMountainId()), KwsProject::getMountainId, headerData.getMountainId())
            );
            KwsAlarmVO vo = new KwsAlarmVO();
            BeanUtils.copyProperties(kwsAlarm, vo);
            vo.setDeviceId(kwsAlarm.getDeviceId().toString());
            vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                    (thresholdLevel == null ? String.valueOf(kwsAlarm.getLevel()) : thresholdLevel.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
            vo.setType(kwsAlarm.getType() == null ? null :
                    (alarmType == null ? String.valueOf(kwsAlarm.getType()) : alarmType.get(String.valueOf(kwsAlarm.getType())).getLabel()));
            vo.setDeviceName(kwsDevice == null ? kwsAlarm.getDeviceId().toString() : kwsDevice.getName());
            vo.setProjectName(project == null ? kwsAlarm.getProjectId() : project.getName());
            vo.setTitle(kwsAlarm.getTitle() == null ? null :
                    (alarmDetailType == null ? kwsAlarm.getTitle() : (alarmDetailType.get(kwsAlarm.getTitle()) == null ? kwsAlarm.getTitle() : alarmDetailType.get(kwsAlarm.getTitle()).getLabel())));
            vo.setStartTime(kwsAlarm.getCreateTime());
            vo.setEndTime(kwsAlarm.getUpdateTime());
//            Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>().eq(KwsAlarmDetail::getAlarmId, kwsAlarm.getId()));
            vo.setTriggerTimes(kwsAlarm.getTriggerTimes());
            alarmVOS.add(vo);
        }
//        Map<Integer, List<KwsAlarm>> listMap = list.stream().collect(Collectors.groupingBy(KwsAlarm::getType));
        return PageRes.build(info, alarmVOS);
    }

    @Autowired
    KwsProjectDeviceMapper projectDeviceMapper;

    @Autowired
    KwsProjectAreaMapper projectAreaMapper;


    public HttpResult read1(BaseList baseList, HttpServletRequest request) {
        String ids = baseList.getIds();
        List<Long> list = com.sckw.core.utils.StringUtils.splitStrToList(ids, Long.class);
        list.forEach(id -> {
            KwsAlarm alarm = alarmMapper.selectById(id);
            /**历史表新增数据*/
            LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<KwsAlarm>()
                    .eq(KwsAlarm::getLevel, alarm.getLevel())
                    .eq(KwsAlarm::getDeviceId, alarm.getDeviceId())
                    .eq(KwsAlarm::getStatus, NumberConstant.ZERO)
                    .eq(KwsAlarm::getType, alarm.getType())
                    .eq(KwsAlarm::getProjectId, alarm.getProjectId())
                    .eq(KwsAlarm::getMountainId, alarm.getMountainId())
                    .eq(KwsAlarm::getCompanyId, alarm.getCompanyId())
                    .orderByDesc(KwsAlarm::getCreateTime);
            List<KwsAlarm> alarms = alarmMapper.selectList(wrapper);
            List<KwsAlarmDetail> details = alarmDetailMapper.selectList(new LambdaUpdateWrapper<KwsAlarmDetail>()
                    .eq(KwsAlarmDetail::getDelFlag, 0)
                    .eq(KwsAlarmDetail::getAlarmId, alarm.getId())
            );
            /**修改当前数据为已读*/
            Integer historyCount = alarm.getTriggerTimes();
            alarm.setTriggerTimes(0);
            alarmMapper.updateById(alarm);
            alarmDetailMapper.update(null, new LambdaUpdateWrapper<KwsAlarmDetail>()
                    .set(KwsAlarmDetail::getStatus, 1)
                    .eq(KwsAlarmDetail::getAlarmId, id)
            );

        });
        return HttpResult.ok("消息已读");
    }

    public HttpResult read(BaseList baseList, HttpServletRequest request) {
        String ids = baseList.getIds();
        List<Long> list = com.sckw.core.utils.StringUtils.splitStrToList(ids, Long.class);
        for (Long id : list) {
            KwsAlarm alarm = alarmMapper.selectById(id);
            /**前端误调用 进行排除*/
            if (1 == alarm.getIsHistory()) {
                continue;
            }
            Integer historyCount = alarm.getTriggerTimes();
            List<KwsAlarmDetail> details = alarmDetailMapper.selectList(new LambdaUpdateWrapper<KwsAlarmDetail>()
                    .eq(KwsAlarmDetail::getIsHistory, 0)
                    .eq(KwsAlarmDetail::getDelFlag, 0)
                    .eq(KwsAlarmDetail::getAlarmId, alarm.getId())
            );
            /**历史触发次数累积*/
            KwsAlarm historyAlarm = alarmMapper.selectOne(new LambdaQueryWrapper<KwsAlarm>()
                    .eq(KwsAlarm::getStatus, 1)
                    .eq(KwsAlarm::getType, alarm.getType())
                    .eq(KwsAlarm::getLevel, alarm.getLevel())
                    .eq(KwsAlarm::getMountainId, alarm.getMountainId())
                    .eq(KwsAlarm::getProjectId, alarm.getProjectId())
                    .eq(KwsAlarm::getDeviceId, alarm.getDeviceId())
                    .eq(KwsAlarm::getCompanyId, alarm.getCompanyId())
                    .eq(KwsAlarm::getIsHistory, NumberConstant.ONE)
                    .eq(KwsAlarm::getDelFlag, NumberConstant.ZERO)
            );
            if (historyAlarm != null) {
                alarmMapper.update(null, new LambdaUpdateWrapper<KwsAlarm>()
                        .set(KwsAlarm::getStatus, 1)
                        .set(KwsAlarm::getTriggerTimes, historyAlarm.getTriggerTimes() + historyCount)
                        .set(KwsAlarm::getUpdateTime, LocalDateTime.now())
                        .eq(KwsAlarm::getId, historyAlarm.getId())
                );
                details.forEach(alarmDetail -> {
                    KwsAlarmDetail historyAlarmDetail = new KwsAlarmDetail();
                    historyAlarmDetail.setId(new IdWorker(NumberConstant.ONE).nextId());
                    historyAlarmDetail.setMountainId(alarmDetail.getMountainId());
                    historyAlarmDetail.setCompanyId(alarmDetail.getCompanyId());
                    historyAlarmDetail.setAlarmId(historyAlarm.getId());
                    historyAlarmDetail.setPid(alarmDetail.getPid());
                    historyAlarmDetail.setVal(alarmDetail.getVal());
                    historyAlarmDetail.setLat(alarmDetail.getLat());
                    historyAlarmDetail.setLng(alarmDetail.getLng());
                    historyAlarmDetail.setAlt(alarmDetail.getAlt());
                    historyAlarmDetail.setCreateTime(alarmDetail.getCreateTime());
                    historyAlarmDetail.setUpdateTime(alarmDetail.getUpdateTime());
                    historyAlarmDetail.setStatus(1);
                    historyAlarmDetail.setIsHistory(1);
                    historyAlarmDetail.setDelFlag(0);
                    alarmDetailMapper.insert(historyAlarmDetail);
                });
            } else {
                KwsAlarm newAlarm = new KwsAlarm();
                BeanUtils.copyProperties(alarm, newAlarm);
                long alarmId = new IdWorker(NumberConstant.ONE).nextId();
                newAlarm.setStatus(1);
                newAlarm.setIsHistory(1);
                newAlarm.setDelFlag(0);
                newAlarm.setId(alarmId);
                newAlarm.setCreateTime(LocalDateTime.now());
                newAlarm.setUpdateTime(LocalDateTime.now());
                alarmMapper.updateById(newAlarm);

                details.forEach(alarmDetail -> {
                    KwsAlarmDetail historyAlarmDetail = new KwsAlarmDetail();
                    historyAlarmDetail.setId(new IdWorker(NumberConstant.ONE).nextId());
                    historyAlarmDetail.setMountainId(alarmDetail.getMountainId());
                    historyAlarmDetail.setCompanyId(alarmDetail.getCompanyId());
                    historyAlarmDetail.setAlarmId(alarmId);
                    historyAlarmDetail.setPid(alarmDetail.getPid());
                    historyAlarmDetail.setVal(alarmDetail.getVal());
                    historyAlarmDetail.setLat(alarmDetail.getLat());
                    historyAlarmDetail.setLng(alarmDetail.getLng());
                    historyAlarmDetail.setAlt(alarmDetail.getAlt());
                    historyAlarmDetail.setCreateTime(alarmDetail.getCreateTime());
                    historyAlarmDetail.setUpdateTime(alarmDetail.getUpdateTime());
                    historyAlarmDetail.setStatus(1);
                    historyAlarmDetail.setIsHistory(1);
                    historyAlarmDetail.setDelFlag(0);
                    alarmDetailMapper.insert(historyAlarmDetail);
                });

            }
            /**修改当前数据为已读*/
            alarm.setTriggerTimes(0);
            alarmMapper.updateById(alarm);
            alarmDetailMapper.update(null, new LambdaUpdateWrapper<KwsAlarmDetail>()
                    .eq(KwsAlarmDetail::getAlarmId, id)
                    .set(KwsAlarmDetail::getStatus, NumberConstant.ONE)
                    .set(KwsAlarmDetail::getDelFlag, NumberConstant.ONE)
            );
        }
        return HttpResult.ok("消息已读");
    }


    public List<KwsAlarmExportVO> export(AlarmLogThresholdExport query, HttpServletRequest request, HttpServletResponse response) {
        List<Long> idsList = null;
        String ids = query.getIds();
        if (StringUtils.isNotBlank(ids) && (!"all".equals(ids))) {
            idsList = com.sckw.core.utils.StringUtils.splitStrToList(ids, Long.class);
        }
        HeaderData headerData = commonService.getHeaderData(request);
        LambdaQueryWrapper<KwsAlarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(headerData.getMountainId()), KwsAlarm::getMountainId, headerData.getMountainId())
                .eq(KwsAlarm::getStatus, query.getStatus())
                .eq(KwsAlarm::getIsHistory, query.getStatus())
                .eq(KwsAlarm::getDelFlag, 0)
                .gt(KwsAlarm::getTriggerTimes, 0)
                .orderByDesc(KwsAlarm::getCreateTime)
        ;
        if (StringUtils.isNotBlank(query.getProjectId())) {
            wrapper.eq(KwsAlarm::getProjectId, Long.parseLong(query.getProjectId()));
        }
        if (!CollectionUtils.isEmpty(idsList) && idsList.size() > 0) {
            wrapper.in(KwsAlarm::getId, idsList);
        }
        List<KwsAlarm> list = alarmMapper.selectExportListByQuery(query, headerData.getMountainId(), idsList);
//        List<KwsAlarm> list = alarmMapper.selectList(wrapper);
        List<KwsAlarmExportVO> alarmVOS = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            return alarmVOS;
        }
        Map<String, SystemDict> thresholdLevel = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
        Map<String, SystemDict> alarmDetailType = commonService.getDictByDictCode(DictEnum.ALARM_DETAIL_TYPE);
        List<KwsProject> projectList = projectMapper.selectList(null);
        Map<Long, String> projectMap = projectList.stream().collect(Collectors.toMap(KwsProject::getId, KwsProject::getName));
        List<KwsDevice> deviceList = deviceMapper.selectList(null);
        Map<Long, String> deviceMap = deviceList.stream().collect(Collectors.toMap(KwsDevice::getId, KwsDevice::getName));
        for (KwsAlarm kwsAlarm : list) {
            KwsAlarmExportVO vo = new KwsAlarmExportVO();
            BeanUtils.copyProperties(kwsAlarm, vo);
            vo.setLevel(kwsAlarm.getLevel() == null ? null : (thresholdLevel.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
            vo.setType(kwsAlarm.getType() == null ? null : (alarmType.get(String.valueOf(kwsAlarm.getType())).getLabel()));
            vo.setDeviceName(deviceMap == null ? kwsAlarm.getDeviceId().toString() : deviceMap.get(kwsAlarm.getDeviceId()));
            vo.setProjectName(projectMap == null ? kwsAlarm.getProjectId() : projectMap.get(Long.parseLong(kwsAlarm.getProjectId())));
            vo.setAlarmLevel(kwsAlarm.getTitle() == null ? null : (alarmDetailType.get(kwsAlarm.getTitle()).getLabel()));
            vo.setStartTime(kwsAlarm.getCreateTime());
            vo.setEndTime(kwsAlarm.getUpdateTime());
            LocalDateTime now = LocalDateTime.now();
            System.out.println(now);
//            Long count = alarmDetailMapper.selectCount(new LambdaQueryWrapper<KwsAlarmDetail>().eq(KwsAlarmDetail::getAlarmId, kwsAlarm.getId()));
            LocalDateTime now1 = LocalDateTime.now();
            System.out.println(now1);
            //todo 不使用缓存  使用新字段处理
            /**结合到mqtt阈值触发数据存储*/
//            if (AlarmTypeEnum.ALARM_ONE.getStatus().equals(String.valueOf(kwsAlarm.getType()))) {
//                /**阈值次数存redis*/
//                String key = Global.REDIS_SYS_ALARM_PREFIX + Global.POUND + String.valueOf(id) + Global.POUND + AlarmTypeEnum.ALARM_ONE.getStatus()
//                        + Global.POUND + AlarmTitleEnum.ALARM_TITLE_TWO.getStatus();
//                count = RedissonUtils.getString(key);
//            } else {
//                /**阈值次数存redis*/
//                String key = Global.REDIS_SYS_ALARM_PREFIX + Global.POUND + String.valueOf(id) + Global.POUND + AlarmTypeEnum.ALARM_TWO.getStatus()
//                        + Global.POUND + AlarmTitleEnum.ALARM_TITLE_ONE.getStatus();
//                count = RedissonUtils.getString(key);
//            }
            vo.setTriggerTimes(kwsAlarm.getTriggerTimes() == null ? null : kwsAlarm.getTriggerTimes().toString());
            alarmVOS.add(vo);
        }
        return alarmVOS;
    }

    @Autowired
    KwsAlarmDetailMapper alarmDetailMapper;

    public PageRes thresholdDetail(PublicBaseList baseList, HttpServletRequest request) {
        String id = baseList.getId();
        KwsAlarm kwsAlarm = alarmMapper.selectById(id);
        PageHelper.startPage(baseList.getPage(), baseList.getPageSize());
        List<KwsAlarmDetail> detailList = alarmDetailMapper.selectList(new LambdaQueryWrapper<KwsAlarmDetail>()
                        .eq(KwsAlarmDetail::getAlarmId, Long.parseLong(id))
                        .eq(KwsAlarmDetail::getDelFlag, 0)
//                .eq(KwsAlarmDetail::getStatus, 0)
        );
        PageInfo<ThresholdRecordDetailVO> info = new PageInfo(detailList);
        if (CollectionUtils.isEmpty(detailList)) {
            return PageRes.build(info, detailList);
        }
        List<ThresholdRecordDetailVO> list = new ArrayList<>();
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
//        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
        Map<String, SystemDict> thresholdLevel = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        if ("1".equals(kwsAlarm.getType())) {
            for (KwsAlarmDetail detail : detailList) {
                Long pid = detail.getPid();
                KwsDevice kwsDevice = deviceMapper.selectById(pid);
                ThresholdRecordDetailVO vo = new ThresholdRecordDetailVO();
                vo.setId(detail.getId());
                vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                        (thresholdLevel == null ? String.valueOf(kwsAlarm.getLevel()) : thresholdLevel.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
//                vo.setType(kwsThreshold.getItemName() == null ? null :
//                        (dictByDictCode == null ? kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getLabel()));
//                vo.setValue(detail.getVal());
//                vo.setItemName(kwsThreshold.getItemName());
                vo.setPhone("");
                StringBuilder location = new StringBuilder();
                if (StringUtils.isNotBlank(kwsDevice.getLogicLng())) {
                    String remark = dictByDictCode.get(DictItemEnum.LONGITUDE_X.getValue()).getRemark();
                    location.append(kwsDevice.getLogicLng()).append(remark).append(";");
                }
                if (StringUtils.isNotBlank(kwsDevice.getLogicLat())) {
                    String remark = dictByDictCode.get(DictItemEnum.LATITUDE_Y.getValue()).getRemark();
                    location.append(kwsDevice.getLogicLat()).append(remark).append(";");
                }
                if (StringUtils.isNotBlank(kwsDevice.getLogicAlt())) {
                    String remark = dictByDictCode.get(DictItemEnum.ALTITUDE_Z.getValue()).getRemark();
                    location.append(kwsDevice.getLogicAlt()).append(";");
                }
                vo.setLocation(location.toString());
                vo.setCreateTime(detail.getCreateTime());
                list.add(vo);
            }
        } else {
            for (KwsAlarmDetail detail : detailList) {
                Long pid = detail.getPid();
                KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
                if (kwsThreshold == null) {
                    kwsThreshold = thresholdMapper.selectByPrimaryKey(pid);
                }
                ThresholdRecordDetailVO vo = new ThresholdRecordDetailVO();
                vo.setId(detail.getId());
                vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                        (thresholdLevel == null ? String.valueOf(kwsAlarm.getLevel()) : thresholdLevel.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
                vo.setType(kwsThreshold == null ? null : (kwsThreshold.getItemName() == null ? null :
                        (dictByDictCode == null ? kwsThreshold.getItemName() : (dictByDictCode.get(kwsThreshold.getItemName()) == null ? kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getLabel()))));
//                List<String> list1=new ArrayList<>();
//                list1.add(DictItemEnum.LONGITUDE_X.getValue());
//                list1.add(DictItemEnum.LATITUDE_Y.getValue());
//                list1.add(DictItemEnum.ALTITUDE_Z.getValue());
                if (dictByDictCode.get(kwsThreshold.getItemName()) == null) {
                    String itemName = kwsThreshold.getItemName();
                    KwsIntegration kwsIntegration = integrationMapper.selectOne(new LambdaQueryWrapper<KwsIntegration>()
                            .eq(KwsIntegration::getIntegrationName, itemName));
                    String unit = "";
                    if (kwsIntegration != null) {
                        Map<String, SystemDict> dictCode = commonService.getDictByDictCode(DictEnum.INTEGRATION_UNIT);
                        unit = dictCode.get(kwsIntegration.getUnit()).getDescription();
                    }
                    vo.setValue(detail.getVal() + unit);
                } else {
                    vo.setValue(detail.getVal());
                }

                vo.setItemName(kwsThreshold == null ? null : kwsThreshold.getItemName());
                vo.setPhone(kwsThreshold == null ? null : kwsThreshold.getPhones());
                KwsDevice kwsDevice = deviceMapper.selectById(kwsThreshold == null ? null : kwsThreshold.getDeviceId());
                StringBuilder location = new StringBuilder();
                if (StringUtils.isNotBlank(kwsDevice.getLogicLng())) {
                    String remark = dictByDictCode.get(DictItemEnum.LONGITUDE_X.getValue()).getRemark();
                    location.append(kwsDevice.getLogicLng()).append(remark).append(";");
                }
                if (StringUtils.isNotBlank(kwsDevice.getLogicLat())) {
                    String remark = dictByDictCode.get(DictItemEnum.LATITUDE_Y.getValue()).getRemark();
                    location.append(kwsDevice.getLogicLat()).append(remark).append(";");
                }
                if (StringUtils.isNotBlank(kwsDevice.getLogicAlt())) {
                    String remark = dictByDictCode.get(DictItemEnum.ALTITUDE_Z.getValue()).getRemark();
                    location.append(kwsDevice.getLogicAlt()).append(remark).append(";");
                }
//                vo.setLocation(kwsDevice == null ? null : kwsDevice.getLogicAlt() + ";" + kwsDevice.getLogicLat() + ";" + kwsDevice.getLogicLng());
                vo.setLocation(location.toString());
                vo.setCreateTime(detail.getCreateTime());
                list.add(vo);
            }
        }
        return PageRes.build(info, list);
    }

    public HttpResult detail(String id, HttpServletRequest request) {
        ThresholdLogDetailVO vo = new ThresholdLogDetailVO();
        KwsAlarmDetail kwsAlarmDetail = alarmDetailMapper.selectById(Long.parseLong(id));
        if (kwsAlarmDetail == null) {
            throw new BusinessException("数据不存在");
        }
        Long alarmId = kwsAlarmDetail.getAlarmId();
        Long pid = kwsAlarmDetail.getPid();
        KwsAlarm kwsAlarm = alarmMapper.selectById(alarmId);
        Integer type = kwsAlarm.getType();
        if (2 == type) {
            KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
            if (kwsThreshold == null) {
                return HttpResult.ok(vo);
            }
            String itemName = kwsThreshold.getItemName();
            Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
            itemName = itemName == null ? null :
                    (dictByDictCode == null ?
                            itemName : (dictByDictCode.get(itemName) == null ?
                            itemName : dictByDictCode.get(itemName).getLabel()));
            Long deviceId = kwsThreshold.getDeviceId();
            KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                    .eq(KwsDeviceReference::getDelFlag, 0)
                    .eq(KwsDeviceReference::getDeviceId, deviceId)
                    .eq(KwsDeviceReference::getItem, kwsThreshold.getItemName())
            );
            KwsDevice device = deviceMapper.selectById(deviceId);
            if (device == null) {
                return HttpResult.ok(vo);
            }
            List<String> list = new ArrayList<>();
            list.add(DictItemEnum.LONGITUDE_X.getValue());
            list.add(DictItemEnum.LATITUDE_Y.getValue());
            list.add(DictItemEnum.ALTITUDE_Z.getValue());
            Devices devices = null;
            try {
                devices = devicesMapper.selectLastDataByCodeAndItemName(device.getSnCode(), kwsThreshold.getItemName());
            } catch (Exception e) {
                log.error("select tdengine device error :{}", e.getMessage(), e);
//                throw new RuntimeException(e);
            }
            vo.setAlarmId(kwsAlarm.getId().toString());
            Long deviceId1 = device.getId();
            ProjectVo project = projectDeviceMapper.selectNotDeleteProjectByDeviceId(deviceId1);
            if (Objects.nonNull(project.getProjectId())) {
                KwsProjectArea area = projectAreaMapper.selectOne(new LambdaQueryWrapper<KwsProjectArea>().eq(KwsProjectArea::getProjectId, project.getProjectId()));
                vo.setFence(area == null ? null : area.getFence());
            }
            vo.setLogicAlt(device.getLogicAlt());
            vo.setLogicLat(device.getLogicLat());
            vo.setLogicLng(device.getLogicLng());
            vo.setAlarmDetailId(id);
            vo.setDeviceId(deviceId.toString());
            vo.setItemName(itemName);
            String unit = "";
            String url = "";
            if (devices != null) {
                String val = devices.getVal();
                if (list.contains(kwsThreshold.getItemName())) {
                    if (deviceReference != null) {
                        unit = kwsThreshold.getItemName() == null ? null :
                                (dictByDictCode == null ?
                                        kwsThreshold.getItemName() : (dictByDictCode.get(kwsThreshold.getItemName()) == null ?
                                        kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getRemark()));
                        url = kwsThreshold.getItemName() == null ? null :
                                (dictByDictCode == null ?
                                        kwsThreshold.getItemName() : (dictByDictCode.get(kwsThreshold.getItemName()) == null ?
                                        kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getUrl()));
                        BigDecimal computeOffset = commonService.computeOffset(val, kwsThreshold.getItemName(), deviceReference);
                        BigDecimal computeOriginalOffset = commonService.computeOriginalOffset(val, kwsThreshold.getItemName(), deviceReference);
                        vo.setCurrentValue(deviceReference.getCurrentValue() + unit);
                        vo.setCurrentOffset(computeOffset.setScale(2, RoundingMode.HALF_UP) + url);
                        vo.setOriginalValue(deviceReference.getOriginalValue() + unit);
                        vo.setOriginalOffset(computeOriginalOffset.setScale(2, RoundingMode.HALF_UP) + url);
                    }
                } else {
                    vo.setCurrentValue(deviceReference == null ? null : deviceReference.getCurrentValue() + unit);
                    vo.setOriginalValue(deviceReference == null ? null : deviceReference.getOriginalValue() + unit);
                }

            }
            vo.setLastReferenceValue(deviceReference == null ? null : deviceReference.getCurrentValue() + unit);
        }
        Map<String, SystemDict> levelDict = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        Map<String, SystemDict> typeDict = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
        Map<String, SystemDict> alarmDetailTypeDict = commonService.getDictByDictCode(DictEnum.ALARM_DETAIL_TYPE);
        vo.setAlarmType(kwsAlarm.getType() == null ? null :
                (typeDict == null ? String.valueOf(kwsAlarm.getType()) : typeDict.get(String.valueOf(kwsAlarm.getType())).getLabel()));
        vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                (levelDict == null ? String.valueOf(kwsAlarm.getLevel()) : levelDict.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
        vo.setAlarmTitle(kwsAlarm.getTitle() == null ? null :
                (alarmDetailTypeDict == null ? kwsAlarm.getTitle() : alarmDetailTypeDict.get(kwsAlarm.getTitle()).getLabel()));
        vo.setAlarmTime(kwsAlarmDetail.getCreateTime());
        return HttpResult.ok(vo);
    }

    public HttpResult dataAlarm(AlarmStatisticsQuery query, HttpServletRequest request) {
        int type = 2;
        String startTime = query.getStartTime();
        String endTime = query.getEndTime();
        String latitude = query.getLatitude();
        String projectId = query.getProjectId();
        String level = query.getLevel();
        HeaderData headerData = commonService.getHeaderData(request);
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(latitude)) {
            List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
            startTime = weekMondayAndSunday.get(0);
            String dateTimeFormat = startTime;
            endTime = weekMondayAndSunday.get(1);
            //按照天纬度统计
            returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(), headerData.getCompanyId(), dateTimeFormat, type);
        } else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            String dateTimeFormat = startTime;
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            //统计小时的纬度统计
            returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getCompanyId(), headerData.getCompanyId(), dateTimeFormat, type);
        } else {
            if (latitude != null) {

                if ("1".equals(latitude)) {
                    startTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 00:00:00";
                    endTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 23:59:59";
                    returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(), headerData.getCompanyId(), type);
                } else if ("2".equals(latitude)) {
                    List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
                    startTime = weekMondayAndSunday.get(0);
                    String dateTimeFormat = startTime;
                    endTime = weekMondayAndSunday.get(1);
                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getCompanyId(), headerData.getCompanyId(), dateTimeFormat, type);
                } else if ("3".equals(latitude)) {
                    LocalDate firstDayOfMonth = com.sckw.excel.utils.DateUtil.getFirstDayOfMonth();
                    startTime = com.sckw.excel.utils.DateUtil.dateToStr(firstDayOfMonth, "yyyy-MM-dd") /*+ " 00:00:00"*/;
                    String dateTimeFormat = startTime;
                    LocalDate lastDayOfMonth = com.sckw.excel.utils.DateUtil.getLastDayOfMonth();
                    endTime = com.sckw.excel.utils.DateUtil.dateToStr(lastDayOfMonth, "yyyy-MM-dd")/* + " 23:59:59"*/;
                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(), headerData.getCompanyId(), dateTimeFormat, type);
                } else if ("4".equals(latitude)) {
                    //查询全年每个月份
                    startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01";
                    endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31";
                    returnList = getDataAlarmToYear(startTime, endTime, level, projectId, headerData.getMountainId(), headerData.getCompanyId(), type);
                }
            }
        }
        return HttpResult.ok(returnList);
    }

    public HttpResult projectAlarm(AlarmStatisticsQuery query, HttpServletRequest request) {
        String startTime = query.getStartTime();
        String endTime = query.getEndTime();
        String latitude = query.getLatitude();
        String projectId = query.getProjectId();
        String level = query.getLevel();
        HeaderData headerData = commonService.getHeaderData(request);
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(latitude)) {
            //按照天纬度统计
            List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
            startTime = weekMondayAndSunday.get(0);
            endTime = weekMondayAndSunday.get(1);
        } else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            //统计小时的纬度统计
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        } else {
            if (latitude != null) {
                if ("1".equals(latitude)) {
                    startTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 00:00:00";
                    endTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 23:59:59";
                } else if ("2".equals(latitude)) {
                    List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
                    startTime = weekMondayAndSunday.get(0);
                    endTime = weekMondayAndSunday.get(1);
                } else if ("3".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 ("4".equals(latitude)) {
                    //查询全年每个月份
                    startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01" + " 00:00:00";
                    endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31" + " 23:59:59";
                }
            }
        }
        returnList = getProjectAlarmList(startTime, endTime, level, projectId, headerData.getCompanyId(), 2);
        if (!CollectionUtils.isEmpty(returnList)) {
            for (Map<String, Object> map : returnList) {
                String id = map.get("projectId").toString();
                KwsProject project = projectMapper.selectById(Long.parseLong(id));
                map.put("projectName", project == null ? id : project.getName());
            }
        }
        return HttpResult.ok(returnList);
    }

    private List<Map<String, Object>> getProjectAlarmList(String startTime, String endTime, String level, String projectId, String companyId, Integer type) {
        List<Map<String, Object>> list = alarmMapper.getProjectAlarmList(startTime, endTime, level, projectId, companyId, type);
        return list;
    }

    private List<Map<String, Object>> getDataAlarmToYear(String startTime, String endTime, String level, String projectId, String mountainId, String companyId, Integer type) {
        List<Map<String, Object>> list = alarmMapper.getDataAlarmToYear(startTime, endTime, level, projectId, mountainId,companyId, type);
        return list;
    }

    private List<Map<String, Object>> getDataAlarmToWeek(String startTime, String endTime, String level, String projectId, String mountainId, String companyId, String dateTimeFormat, Integer type) {
        List<Map<String, Object>> list = alarmMapper.getDataAlarmToWeek(startTime, endTime, level, projectId, mountainId, companyId, dateTimeFormat, type);
        return list;
    }

    private List<Map<String, Object>> getDataAlarmToDay(String startTime, String endTime, String level, String projectId, String mountainId, String companyId, Integer type) {
        List<Map<String, Object>> list = alarmMapper.getDataAlarmToDay(startTime, endTime, level, projectId, mountainId, companyId, type);
        return list;
    }


    public HttpResult deviceAlarm(AlarmStatisticsQuery query, HttpServletRequest request) {
        int type = 1;
        String startTime = query.getStartTime();
        String endTime = query.getEndTime();
        String latitude = query.getLatitude();
        String projectId = query.getProjectId();
        String level = query.getLevel();
        HeaderData headerData = commonService.getHeaderData(request);
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(latitude)) {
            List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
            startTime = weekMondayAndSunday.get(0);
            String dateTimeFormat = startTime;
            endTime = weekMondayAndSunday.get(1);
            //按照天纬度统计
            returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(),headerData.getCompanyId(), dateTimeFormat, type);
        } else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            //统计小时的纬度统计
            returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(),headerData.getCompanyId(), type);
        } else {
            if (latitude != null) {
                if ("1".equals(latitude)) {
                    startTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 00:00:00";
                    endTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 23:59:59";
                    returnList = getDataAlarmToDay(startTime, endTime, level, projectId, headerData.getMountainId(),headerData.getCompanyId(), type);
                } else if ("2".equals(latitude)) {
                    List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
                    startTime = weekMondayAndSunday.get(0);
                    String dateTimeFormat = startTime;
                    endTime = weekMondayAndSunday.get(1);
                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(),headerData.getCompanyId(), dateTimeFormat, type);
                } else if ("3".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"*/;
                    String dateTimeFormat = startTime;
                    returnList = getDataAlarmToWeek(startTime, endTime, level, projectId, headerData.getMountainId(),headerData.getCompanyId(), dateTimeFormat, type);
                } else if ("4".equals(latitude)) {
                    //查询全年每个月份
                    startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01";
                    endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31";
                    returnList = getDataAlarmToYear(startTime, endTime, level, projectId, headerData.getMountainId(),headerData.getCompanyId(), type);
                }
            }
        }
        return HttpResult.ok(returnList);
    }

    public HttpResult deviceAlarmProject(AlarmStatisticsQuery query, HttpServletRequest request) {
        String startTime = query.getStartTime();
        String endTime = query.getEndTime();
        String latitude = query.getLatitude();
        String projectId = query.getProjectId();
        String level = query.getLevel();
        HeaderData headerData = commonService.getHeaderData(request);
        List<Map<String, Object>> returnList = new ArrayList<>();
        if (StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime) && StringUtils.isBlank(latitude)) {
            //按照天纬度统计
            List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
            startTime = weekMondayAndSunday.get(0);
            endTime = weekMondayAndSunday.get(1);
        } else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            //统计小时的纬度统计
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        } else {
            if (latitude != null) {
                if ("1".equals(latitude)) {
                    startTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 00:00:00";
                    endTime = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd") + " 23:59:59";
                } else if ("2".equals(latitude)) {
                    List<String> weekMondayAndSunday = com.sckw.excel.utils.DateUtil.getWeekMondayAndSunday();
                    startTime = weekMondayAndSunday.get(0);
                    endTime = weekMondayAndSunday.get(1);
                } else if ("3".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 ("4".equals(latitude)) {
                    //查询全年每个月份
                    startTime = com.sckw.excel.utils.DateUtil.getYearFirstMonth() + "-01" + " 00:00:00";
                    endTime = com.sckw.excel.utils.DateUtil.getYearLastMonth() + "-31" + " 23:59:59";
                }
            }
        }
        returnList = getProjectAlarmList(startTime, endTime, level, projectId, headerData.getCompanyId(), 1);
        if (!CollectionUtils.isEmpty(returnList)) {
            for (Map<String, Object> map : returnList) {
                String id = map.get("projectId").toString();
                KwsProject project = projectMapper.selectById(Long.parseLong(id));
                map.put("projectName", project == null ? id : project.getName());
            }
        }
        return HttpResult.ok(returnList);
    }

    public List<ThresholdRecordDetailExportVO> exportDetail(BaseList baseList, HttpServletRequest request) {
        List<ThresholdRecordDetailExportVO> list = new ArrayList<>();
        String parentId = baseList.getParentId();
        if (StringUtils.isBlank(parentId)) {
            return list;
        }
        String ids = baseList.getIds();
        List<Long> idsList = new ArrayList<>();
        if (StringUtils.isNotBlank(ids) && (!"all".equals(ids))) {
            idsList = com.sckw.core.utils.StringUtils.splitStrToList(ids, Long.class);
        }
        List<KwsAlarmDetail> detailList = alarmDetailMapper.selectList(new LambdaQueryWrapper<KwsAlarmDetail>()
                .eq(KwsAlarmDetail::getAlarmId, Long.parseLong(parentId))
                .in(!CollectionUtils.isEmpty(idsList), KwsAlarmDetail::getId, idsList)
                .orderByAsc(KwsAlarmDetail::getCreateTime)
        );
        if (CollectionUtils.isEmpty(detailList)) {
            return list;
        }
        KwsAlarm kwsAlarm = alarmMapper.selectById(detailList.get(0).getAlarmId());
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        Map<String, SystemDict> alarmType = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        if ("1".equals(kwsAlarm.getType())) {

        } else {
            for (KwsAlarmDetail detail : detailList) {
                Long pid = detail.getPid();
                KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
                if (kwsThreshold == null) {
                    kwsThreshold = thresholdMapper.selectByPrimaryKey(pid);
                }
                ThresholdRecordDetailExportVO vo = new ThresholdRecordDetailExportVO();
                vo.setId(detail.getId());
                vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                        (alarmType == null ? String.valueOf(kwsAlarm.getLevel()) : alarmType.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
                vo.setType(kwsThreshold == null ? null : (kwsThreshold.getItemName() == null ? null :
                        (dictByDictCode == null ? kwsThreshold.getItemName() :
                                (dictByDictCode.get(kwsThreshold.getItemName()) == null ? kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getLabel()))));
                vo.setValue(detail.getVal());
                vo.setItemName(kwsThreshold.getItemName());
                vo.setPhone(kwsThreshold.getPhones());
                KwsDevice kwsDevice = deviceMapper.selectById(kwsThreshold.getDeviceId());
                StringBuilder location = new StringBuilder();
                if (StringUtils.isNotBlank(kwsDevice.getLogicAlt())) {
                    location.append(kwsDevice.getLogicAlt()).append(";");
                }
                if (StringUtils.isNotBlank(kwsDevice.getLogicLat())) {
                    location.append(kwsDevice.getLogicLat()).append(";");
                }
                if (StringUtils.isNotBlank(kwsDevice.getLogicLng())) {
                    location.append(kwsDevice.getLogicLng());
                }
                vo.setLocation(location.toString());
                vo.setCreateTime(detail.getCreateTime());
                list.add(vo);
            }
        }
        return list;
    }

    public List<ThresholdLogDetailVO> exportDetailById(String id, HttpServletRequest request) {
        List<ThresholdLogDetailVO> exportList = new ArrayList<>();
        ThresholdLogDetailVO vo = new ThresholdLogDetailVO();
        KwsAlarmDetail kwsAlarmDetail = alarmDetailMapper.selectById(Long.parseLong(id));
        if (kwsAlarmDetail == null) {
            return exportList;
        }
        Long alarmId = kwsAlarmDetail.getAlarmId();
        Long pid = kwsAlarmDetail.getPid();
        KwsAlarm kwsAlarm = alarmMapper.selectById(alarmId);
        Integer type = kwsAlarm.getType();
        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.MODEL_PART);
        if (2 == type) {
            KwsThreshold kwsThreshold = thresholdMapper.selectById(pid);
            if (kwsThreshold == null) {
                return exportList;
            }
            String itemName = kwsThreshold.getItemName();
            Long deviceId = kwsThreshold.getDeviceId();
            KwsDeviceReference deviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                    .eq(KwsDeviceReference::getDelFlag, 0)
                    .eq(KwsDeviceReference::getDeviceId, deviceId)
                    .eq(KwsDeviceReference::getItem, itemName)
            );
            List<String> list = new ArrayList<>();
            list.add(DictItemEnum.LONGITUDE_X.getValue());
            list.add(DictItemEnum.LATITUDE_Y.getValue());
            list.add(DictItemEnum.ALTITUDE_Z.getValue());
            if (deviceReference != null) {
//                if (list.contains(itemName)){
//
//                }

                vo.setItemName(itemName);
                String unit = kwsThreshold.getItemName() == null ? null :
                        (dictByDictCode == null ?
                                kwsThreshold.getItemName() : (dictByDictCode.get(kwsThreshold.getItemName()) == null ?
                                kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getRemark()));
                vo.setCurrentValue(deviceReference.getCurrentValue() + unit);
                vo.setCurrentOffset(deviceReference.getOffset().toString());
                vo.setOriginalValue(deviceReference.getOriginalValue() + unit);
                vo.setOriginalOffset("0.00");
                KwsDeviceReference lastDeviceReference = deviceReferenceMapper.selectOne(new LambdaQueryWrapper<KwsDeviceReference>()
                        .eq(KwsDeviceReference::getDelFlag, 1)
                        .eq(KwsDeviceReference::getDeviceId, deviceId)
                        .eq(KwsDeviceReference::getItem, itemName)
                        .orderByDesc(KwsDeviceReference::getUpdateTime)
                        .last("limit 1")
                );
                vo.setLastReferenceValue(lastDeviceReference == null ? null : lastDeviceReference.getCurrentValue() + unit);
            }
        }
        Map<String, SystemDict> levelDict = commonService.getDictByDictCode(DictEnum.THRESHOLD_LEVEL);
        Map<String, SystemDict> typeDict = commonService.getDictByDictCode(DictEnum.ALARM_TYPE);
        Map<String, SystemDict> alarmDetailTypeDict = commonService.getDictByDictCode(DictEnum.ALARM_DETAIL_TYPE);
        vo.setAlarmType(kwsAlarm.getType() == null ? null :
                (typeDict == null ? String.valueOf(kwsAlarm.getType()) : typeDict.get(String.valueOf(kwsAlarm.getType())).getValue()));
        vo.setAlarmLevel(kwsAlarm.getLevel() == null ? null :
                (levelDict == null ? String.valueOf(kwsAlarm.getLevel()) : levelDict.get(String.valueOf(kwsAlarm.getLevel())).getLabel()));
        vo.setAlarmTitle(kwsAlarm.getTitle() == null ? null :
                (alarmDetailTypeDict == null ? kwsAlarm.getTitle() : alarmDetailTypeDict.get(kwsAlarm.getTitle()).getLabel()));
        vo.setAlarmTime(kwsAlarmDetail.getCreateTime());
        exportList.add(vo);
        return exportList;
    }
}
