package com.ho.business.service.impl;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.PageInfo;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.*;
import com.ho.business.feignclient.FlowFeignClient;
import com.ho.business.feignclient.TdFeignClient;
import com.ho.business.service.*;
import com.ho.business.vo.DeviceColTransfer;
import com.ho.business.vo.DeviceTransfer;
import com.ho.business.vo.req.DeviceReqVO;
import com.ho.business.vo.req.DeviceTypeColReqVO;
import com.ho.business.vo.req.oneClickSequentialControl.OneClickSequentialControlQueryReq;
import com.ho.business.vo.req.point.*;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.VirtualDeviceColResp;
import com.ho.business.vo.req.configure.*;
import com.ho.business.vo.resp.point.*;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.DefineConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.constant.TableConstant;
import com.ho.common.tools.entity.PointCurveSrcCol;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.CustomTimeUtils;
import com.ho.common.tools.util.PageResult;
import com.ho.common.tools.util.PageUtils;
import com.ho.common.tools.vo.req.PointData;
import com.ho.common.tools.vo.req.StatisticsCurve;
import com.ho.datacollect.api.constant.DataCollectConstant;
import com.ho.datacollect.api.vo.req.add.TdBase;
import com.ho.flow.vo.req.event.EventDemoReqVo;
import com.ho.flow.vo.resp.event.EventDemo;
import com.ho.td.api.entity.query.TdBaseTimeQuery;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author gyan
 * @desc: TODO
 * @DateTime: 2023/3/26 14:14
 */
@Service
@Slf4j
public class PointDemoServiceImpl implements PointDemoService {


    @Autowired
    StationService stationService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @Autowired
    ModelDeviceService modelDeviceService;

    @Autowired
    RedisService redisService;

    @Autowired
    TdFeignClient feignClient;

    @Autowired
    FlowFeignClient flowFeignClient;

    @Autowired
    VirtualDeviceColService virtualDeviceColService;

    @Autowired
    ConvertService convertService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    ColCountService colCountService;

    @Autowired
    PlanningCurveIssueService issueService;

    @Autowired
    PlanningCurveService planningService;

    @Autowired
    DynamicConfigService dynamicConfigService;

    @Override
    public List<PointRespVO> getPointList(PointReq pointReq) {
        Integer stationId = pointReq.getStationId();
        Integer srcId = pointReq.getSrcId();
        boolean virtualDevice = false;
        Integer virtualId = null;
        Integer realSrcId = null;
        Device deviceInfo = null;
        if (CommonConstant.ONE.equals(pointReq.getIsSave()) && srcId == null) {
            log.info("isSave等于1的同时，点表列表设备类型为空");
            return new ArrayList<>();
        }
        if (srcId != null) {
            deviceInfo = deviceService.selectByStationIdAndSrcIdAndLng(stationId, srcId,pointReq.getLang());
            if (deviceInfo != null && CommonConstant.ONE.equals(deviceInfo.getVirtual())) {
                realSrcId = deviceInfo.getFromId();
                virtualDevice = true;
                virtualId = deviceInfo.getSrcId();
                String deviceName = deviceInfo.getDeviceName();
                deviceInfo = deviceService.selectByStationIdAndSrcIdAndLng(stationId, realSrcId,pointReq.getLang());
                deviceInfo.setDeviceName(deviceName);
            }
        }else{
//            List<DeviceRespVO> deviceList = deviceService.getListByDeviceType(stationId, DeviceTypeConstant.PCS);
//            if (deviceList.isEmpty()) {
//                deviceList = deviceService.getListByFuzzyDeviceType(stationId, DeviceTypeConstant.PCS);
//            }
            DeviceReqVO deviceReqVO = new DeviceReqVO();
            deviceReqVO.setStationId(stationId);
            deviceReqVO.setNeedFilter(CommonConstant.ONE);
            deviceReqVO.setNeedDeviceTypeNotNull(CommonConstant.ONE);
            List<DeviceRespVO> deviceList = deviceService.getList(deviceReqVO);
            deviceList = deviceList.stream().filter(i -> CommonConstant.ZERO.equals(i.getVirtual())).collect(Collectors.toList());
            if(deviceList!=null && deviceList.size()>0){
                deviceInfo = deviceList.get(0);
            }else{
                log.info("没有设备类型不为空的真设备");
                return new ArrayList<>();
            }
        }
        List<Integer> srcIdList = new ArrayList<>();
        //先根据srcIdList查到设备类型，然后组装redisKey查询缓存中的数据

        //返回的数据内存分页
        List<PointRespVO> pointList = new ArrayList<>(1024);
        //根据页大小和当前页计算应该显示多少数据
        Integer pageNum = pointReq.getPageNum();
        Integer pageSize = pointReq.getPageSize();
        int total = pageNum * pageSize;
        int i = 0;
        Map<String, String> colMap = new HashMap<>();
        boolean flag = CommonConstant.ONE.equals(pointReq.getIsSave());
        List<String> deviceTypeList = new ArrayList<>();
        deviceTypeList.add(deviceInfo.getDeviceType());
        DeviceTypeColReqVO deviceTypeColReqVO = new DeviceTypeColReqVO();
        deviceTypeColReqVO.setDeviceTypeList(deviceTypeList);
        if (flag) {
            deviceTypeColReqVO.setIsSave(pointReq.getIsSave());
        } else {
            deviceTypeColReqVO.setIsSave(null);
        }
        deviceTypeColReqVO.setName("".equals(pointReq.getName()) ? null : pointReq.getName());
        deviceTypeColReqVO.setSensType(pointReq.getSensType());
        deviceTypeColReqVO.setLang(pointReq.getLang());
        //增加单位
        List<DeviceTypeCol> deviceTypeCols = modelDeviceService.selectByDeviceTypeList(deviceTypeColReqVO);
        Map<String, String> deviceColMap = new HashMap<>();
        Map<String, String> deviceColNameMap = new HashMap<>();
        for (DeviceTypeCol deviceTypeCol : deviceTypeCols) {
            colMap.put(deviceTypeCol.getDeviceType() + "_" + deviceTypeCol.getCol(), deviceTypeCol.getUnit());
            deviceColMap.put(deviceTypeCol.getDeviceType() + "_" + deviceTypeCol.getCol(), deviceTypeCol.getDeviceType() + "_" + deviceTypeCol.getCol());
            deviceColNameMap.put(deviceTypeCol.getDeviceType() + "_" + deviceTypeCol.getCol(), deviceTypeCol.getColName());
        }
        Map<String, List<DeviceTypeCol>> colList = deviceTypeCols.stream().filter(n -> n.getDeviceType() != null).collect(Collectors.groupingBy(s -> s.getDeviceType()));
        //根据每一个设备从缓存中拿数据
        String redisKey = deviceInfo.getDeviceType() + ":" + stationId + ":" + deviceInfo.getSrcId();
        Date date = new Date();
        String updateTime = DateUtil.format(date, CommonConstant.DATE);
        Map<Object, Object> dataMap = new HashMap<>();
        if (redisService.hasKey(redisKey)) {
            dataMap = redisService.hgetall(redisKey);
            //去除ts createTime updateTime 3 个字段
            date = (Date) dataMap.get(DataCollectConstant.UPDATE_TIME);
            if (dataMap.containsKey(DataCollectConstant.TS)) {
                dataMap.remove(DataCollectConstant.TS);
            }
            if (dataMap.containsKey(DataCollectConstant.CREATE_TIME)) {
                dataMap.remove(DataCollectConstant.CREATE_TIME);
            }
            if (dataMap.containsKey(DataCollectConstant.UPDATE_TIME)) {
                dataMap.remove(DataCollectConstant.UPDATE_TIME);
            }
        }
        List<DeviceTypeCol> deviceList = colList.get(deviceInfo.getDeviceType());
        if (virtualDevice && deviceList != null) {
            //如果是虚拟设备,限定该设备所包含的col
            VirtualDeviceCol virtualDeviceColReq = new VirtualDeviceCol();
            virtualDeviceColReq.setStationId(stationId);
            virtualDeviceColReq.setSrcId(virtualId);
            List<VirtualDeviceColResp> virtualList = virtualDeviceColService.getList(virtualDeviceColReq);
            //
            Map<String, List<VirtualDeviceColResp>> virtualColMap = virtualList.stream().collect(Collectors.groupingBy(VirtualDeviceColResp::getCol));
            List<DeviceTypeCol> deviceListNew = new ArrayList<>();
            for (DeviceTypeCol deviceTypeCol : deviceList) {
                if (virtualColMap.containsKey(deviceTypeCol.getCol())) {
                    deviceListNew.add(deviceTypeCol);
                }
            }
            deviceList = deviceListNew;
        }
        if (null != deviceList) {
            for (DeviceTypeCol device : deviceList) {
                if (flag && null == deviceColMap.get(deviceInfo.getDeviceType() + "_" + device.getCol())) {
                    //colMap不包含的数据全部丢弃
                    continue;
                }
                DeviceTransfer deviceTransfer = null;
                Object obj = dataMap.get(device.getCol());
                if (null != obj) {
                    deviceTransfer = (DeviceTransfer) obj;
                }
                PointRespVO point = new PointRespVO();
                point.setId(device.getId());
                point.setStationId(deviceInfo.getStationId());
                point.setSrcId(deviceInfo.getSrcId());
                point.setDeviceType(deviceInfo.getDeviceType());
                point.setDeviceName(deviceInfo.getDeviceName());
                point.setCol(device.getCol());
                point.setSensType(device.getSensType());
                point.setColName(deviceColNameMap.get(deviceInfo.getDeviceType() + "_" + device.getCol()));
                point.setUnit(colMap.get(deviceInfo.getDeviceType() + "_" + device.getCol()));
                if (null == deviceTransfer) {
                    point.setValue(NumberUtil.round(new BigDecimal(CommonConstant.ZERO), 3));
                    point.setUpdateTime(updateTime);
                } else {
                    BigDecimal value = deviceTransfer.getValue();
                    //如果是命令下发界面，即isSave是1，则取原始数据；以下三目运算是为了防止原始数据没有取到值
                    point.setValue(NumberUtil.round(flag ? (deviceTransfer.getSrcValue() == null ? value : deviceTransfer.getSrcValue()) : value, 3));
                    point.setUpdateTime(DateUtil.format(deviceTransfer.getUpdateTime(), CommonConstant.DATE));
                }
                point.setMaxValue(device.getMaxValue());
                point.setMinValue(device.getMinValue());
                ++i;
                pointList.add(point);
            }
        }

        //对点表的数据进行分类处理
        //返回的数据内存分页
        List<PointRespVO> list = new ArrayList<>(1024);
        if (pointReq.getSensType() == null) {        //当为空时
            list = pointList;
        } else if (CommonConstant.ONE.equals(pointReq.getSensType())) {    //当为1遥信时
            for (PointRespVO pointRespVO : pointList) {
                if (pointRespVO.getCol() == null) {
                    continue;
                } else if (CommonConstant.ONE.equals(pointRespVO.getSensType())) {
                    list.add(pointRespVO);
                }
            }
        } else if (CommonConstant.TWO.equals(pointReq.getSensType())) { //当为 2遥测时
            for (PointRespVO pointRespVO : pointList) {
                if (pointRespVO.getCol() == null) {
                    continue;
                } else if (CommonConstant.TWO.equals(pointRespVO.getSensType())) {
                    list.add(pointRespVO);
                }
            }
        } else if (CommonConstant.THREE.equals(pointReq.getSensType())) { //当为 3遥控
            for (PointRespVO pointRespVO : pointList) {
                if (pointRespVO.getCol() == null) {
                    continue;
                } else if (CommonConstant.THREE.equals(pointRespVO.getSensType())) {
                    list.add(pointRespVO);
                }
            }
        }
        //对结果值进行筛选
        List<PointRespVO> resultList = new ArrayList<>();
        if (pointReq.getValue1() == null) {
            resultList.addAll(list);
        } else {
            for (PointRespVO pointRespVO : list) {
                if (CommonConstant.ONE.equals(pointReq.getValue2().intValue())) {
                    //大于1
                    if (pointRespVO.getValue().compareTo(pointReq.getValue1()) == CommonConstant.ONE) {
                        resultList.add(pointRespVO);
                    }
                } else if (CommonConstant.TWO.equals(pointReq.getValue2().intValue())) {
                    //小于2
                    if (pointRespVO.getValue().compareTo(pointReq.getValue1()) == CommonConstant.NEGATIV_ONE) {
                        resultList.add(pointRespVO);
                    }
                } else if (CommonConstant.THREE.equals(pointReq.getValue2().intValue())) {
                    // 等于3
                    if (pointRespVO.getValue().compareTo(pointReq.getValue1()) == CommonConstant.ZERO) {
                        resultList.add(pointRespVO);
                    }
                } else if (CommonConstant.FOUR.equals(pointReq.getValue2().intValue())) {
                    //大于等于4
                    if (pointRespVO.getValue().compareTo(pointReq.getValue1()) > CommonConstant.NEGATIV_ONE) {
                        resultList.add(pointRespVO);
                    }
                } else if (CommonConstant.FIVE.equals(pointReq.getValue2().intValue())) {
                    //小于等于5
                    if (pointRespVO.getValue().compareTo(pointReq.getValue1()) < CommonConstant.ONE) {
                        resultList.add(pointRespVO);
                    }
                }
            }
        }
        return resultList;
    }

    @Override
    public List<PointListRespVo> pointList(PointReq pointReq) {
        List<PointRespVO> pointList = getPointList(pointReq);
        Map<Integer, List<PointRespVO>> srcMap = pointList.stream().collect(Collectors.groupingBy(PointRespVO::getSrcId));
        List<PointListRespVo> resultList = new ArrayList<>();
        PointListRespVo q = null;
        for (Map.Entry<Integer, List<PointRespVO>> m : srcMap.entrySet()) {
            q = new PointListRespVo();
            q.setSrcId(m.getKey());
            if (m.getValue() != null && m.getValue().size() > 0) {
                q.setDeviceName(m.getValue().get(0).getDeviceName());
            }
            q.setDeviceTypeColList(m.getValue());
            resultList.add(q);
        }
        return resultList;
    }

    @Override
    public PointRespVO getPointRespVO(PointOneReq pointReq) {
        //根据每一个设备从缓存中拿数据
        String redisKey = pointReq.getDeviceType() + ":" + pointReq.getStationId() + ":" + pointReq.getSrcId();
        PointRespVO point = new PointRespVO();
        point.setStationId(pointReq.getStationId());
        point.setSrcId(pointReq.getSrcId());
        point.setDeviceType(pointReq.getDeviceType());
        point.setDeviceName(pointReq.getDeviceName());
        point.setCol(pointReq.getCol());
        point.setColName(pointReq.getColName());
        point.setMaxValue(pointReq.getMaxValue());
        point.setMinValue(pointReq.getMinValue());
        point.setSensType(pointReq.getSensType());
        point.setValue(pointReq.getValue());
        point.setUnit(pointReq.getUnit());
        point.setUpdateTime(pointReq.getUpdateTime());
        if (redisService.hasKey(redisKey)) {
            Map<Object, Object> dataMap = redisService.hgetall(redisKey);
            //去除ts createTime updateTime 3 个字段
            Date date = (Date) dataMap.get(DataCollectConstant.UPDATE_TIME);
            String updateTime = DateUtil.format(date, CommonConstant.DATE);
            if (dataMap.containsKey(DataCollectConstant.TS)) {
                dataMap.remove(DataCollectConstant.TS);
            }
            if (dataMap.containsKey(DataCollectConstant.CREATE_TIME)) {
                dataMap.remove(DataCollectConstant.CREATE_TIME);
            }
            if (dataMap.containsKey(DataCollectConstant.UPDATE_TIME)) {
                dataMap.remove(DataCollectConstant.UPDATE_TIME);
            }
            // HashMap<String, Object> value = (HashMap<String, Object>) dataMap.get(pointReq.getCol());
            DeviceTransfer deviceTransfer = (DeviceTransfer) dataMap.get(pointReq.getCol());
            if (null == deviceTransfer) {
                point.setValue(NumberUtil.round(new BigDecimal(CommonConstant.ZERO), 3));
                point.setUpdateTime(updateTime);
            } else {
                point.setValue(NumberUtil.round(deviceTransfer.getValue(), 3));
                point.setUpdateTime(DateUtil.format(deviceTransfer.getUpdateTime(), CommonConstant.DATE));
            }
        }
        return point;
    }


    @Override
    public List<QueryPointRespVo> queryPoint(PointVo vo) {
        List<QueryPointRespVo> queryPointRespVoList = new ArrayList<>();
        if (vo.getSrcIdList() != null) {
            List<Integer> srcIdList = vo.getSrcIdList();
            for (Integer srcId : srcIdList) {
                QueryPointRespVo queryPointRespVo = new QueryPointRespVo();
                List<Point> deviceTypeColList = new ArrayList<>();
                Device device = deviceService.selectByStationIdAndSrcId(vo.getStationId(), srcId);
                //虚拟设备,查询从virtual_device_col中查数据,因为虚拟设备的字段来自于真实设备col,所以
                List<DeviceTypeCol> deviceTypeCols = new ArrayList<>();
                if (device != null && device.getDeviceType() != null) {
                    //实体设备
                    if (device.getVirtual() == 0) {
                        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
                        if (deviceTypeConfig != null) {
                            deviceTypeCols = deviceTypeColService.selectByDeviceType(deviceTypeConfig.getDeviceType(),vo.getLang());
                            queryPointRespVo.setDeviceTypeName(deviceTypeConfig.getName());
                        }
                    } else if (device.getVirtual() == 1) {
                        //虚拟设备,来自于虚拟映射表
                        VirtualDeviceCol virtualDeviceColReq = new VirtualDeviceCol();
                        virtualDeviceColReq.setStationId(vo.getStationId());
                        virtualDeviceColReq.setSrcId(srcId);
                        virtualDeviceColReq.setLang(vo.getLang());
                        List<VirtualDeviceColResp> virtualColList = virtualDeviceColService.getList(virtualDeviceColReq);
                        for (VirtualDeviceColResp virtualDeviceColResp : virtualColList) {
                            DeviceTypeCol deviceTypeCol = new DeviceTypeCol();
                            deviceTypeCol.setId(virtualDeviceColResp.getDeviceColId());
                            deviceTypeCol.setCol(virtualDeviceColResp.getCol());
                            deviceTypeCol.setColName(virtualDeviceColResp.getColName());
                            deviceTypeCols.add(deviceTypeCol);
                        }
                    }
                    queryPointRespVo.setSrcId(srcId);
                    queryPointRespVo.setDeviceName(device.getDeviceName());
                }


                for (DeviceTypeCol deviceTypeCol : deviceTypeCols) {
                    Point point = new Point();
                    point.setId(deviceTypeCol.getId());
                    point.setCol(deviceTypeCol.getCol());
                    point.setColName(deviceTypeCol.getColName());
                    deviceTypeColList.add(point);
                }
                if (!deviceTypeColList.isEmpty()) {
                    queryPointRespVo.setDeviceTypeColList(deviceTypeColList);
                    queryPointRespVoList.add(queryPointRespVo);
                }
            }
        }

        return queryPointRespVoList;
    }

    @Override
    public List<QueryPointRespVo> queryVirtualPoint(PointVo vo) {
        List<QueryPointRespVo> queryPointRespVoList = new ArrayList<>();
        if (vo.getSrcIdList() != null) {
            List<Integer> srcIdList = vo.getSrcIdList();
            for (Integer srcId : srcIdList) {
                QueryPointRespVo queryPointRespVo = new QueryPointRespVo();
                List<Point> deviceTypeColList = new ArrayList<>();
                Device device = deviceService.selectByStationIdAndSrcId(vo.getStationId(), srcId);
                //虚拟设备,查询从virtual_device_col中查数据,因为虚拟设备的字段来自于真实设备col,所以
                List<DeviceTypeCol> deviceTypeCols = new ArrayList<>();
                if (device != null && device.getDeviceType() != null) {
                    //实体设备
                    if (device.getVirtual() == 0) {
                        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
                        if (deviceTypeConfig != null) {
                            deviceTypeCols = deviceTypeColService.selectByDeviceType(deviceTypeConfig.getDeviceType(),vo.getLang());
                            queryPointRespVo.setDeviceTypeName(deviceTypeConfig.getName());
                        }
                    }
                    queryPointRespVo.setSrcId(srcId);
                    queryPointRespVo.setDeviceName(device.getDeviceName());
                }
                device = new Device();
                device.setStationId(vo.getStationId());
                device.setFromId(srcId);
                List<Device> realDevice = deviceService.getRealDevice(device);
                List<Integer> srcIdLists = realDevice.stream().map(Device::getSrcId).collect(Collectors.toList());
                VirtualDeviceCol vCol = new VirtualDeviceCol();
                vCol.setStationId(vo.getStationId());
                vCol.setSrcIdList(srcIdLists);
                List<VirtualDeviceColResp> list = virtualDeviceColService.getList(vCol);
                Map<Integer, Integer> mapId = list.stream().collect(Collectors.toMap(VirtualDeviceColResp::getDeviceColId, VirtualDeviceColResp::getDeviceColId, (k1, k2) -> k2));
                //根据电站id和deviceTypeColId 进行查询 0:未使用 1:已使用
                for (DeviceTypeCol deviceTypeCol : deviceTypeCols) {
                    Point point = new Point();
                    point.setId(deviceTypeCol.getId());
                    point.setStationId(vo.getStationId());
                    point.setCol(deviceTypeCol.getCol());
                    point.setColName(deviceTypeCol.getColName());
                    if (mapId.get(deviceTypeCol.getId()) == null) {
                        point.setUse(CommonConstant.ZERO);
                    } else {
                        point.setUse(CommonConstant.ONE);
                    }
                    deviceTypeColList.add(point);
                }

                if (!deviceTypeColList.isEmpty()) {
                    queryPointRespVo.setDeviceTypeColList(deviceTypeColList);
                    queryPointRespVoList.add(queryPointRespVo);
                }
            }
        }

        return queryPointRespVoList;
    }

    @Override
    public List<PointRespVO> queryControlPoint(OneClickSequentialControlQueryReq vo) {
        List<PointRespVO> pointList = new ArrayList<>();
        Integer srcId = vo.getSrcId();
        if (srcId != null) {
            PointReq pointReq = new PointReq();
            //查询可控点
            pointReq.setIsSave(CommonConstant.ONE);
            pointReq.setStationId(vo.getStationId());
            pointReq.setSrcId(srcId);
            pointList = getPointList(pointReq);
//            List<OneClickSequentialControl> list = controlService.getListByParam(vo);
//            Map<String, String> colMap = list.stream().collect(Collectors.toMap(OneClickSequentialControl::getCol, OneClickSequentialControl::getCol, (k1, k2) -> k2));
//            for (PointRespVO deviceTypeCol:pointList) {
//                if (colMap.get(deviceTypeCol.getCol()) == null) {
//                    deviceTypeCol.setUse(CommonConstant.ZERO);
//                } else {
//                    deviceTypeCol.setUse(CommonConstant.ONE);
//                }
//            }
        }
        return pointList;
    }

    /**
     * 只有一个时间段
     *
     * @param nowTime   需要进行判断的时间
     * @param beginTime
     * @param endTime
     * @return boolean
     */
    //判断是否在规定的时间内签到 nowTime 当前时间 beginTime规定开始时间 endTime规定结束时间
    @Override
    public boolean timeCalendar(Date nowTime, Date beginTime, Date endTime) {
        //设置当前时间
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        //设置开始时间
        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);//开始时间
        //设置结束时间
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);//上午结束时间
        //处于开始时间之后，和结束时间之前的判断
        if ((date.after(begin) && date.before(end))) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public PointCurveReq getPointCurveReq(HomePageReqVo vo) {
        PointCurveReq pointCurveReq = new PointCurveReq();
        List<PointCurveSrcCol> deviceIdList = new ArrayList<>();
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(vo.getStationId());
        deviceReqVO.setSrcId(vo.getSrcId());
        List<DeviceRespVO> deviceList = deviceService.getList(deviceReqVO);
        //当是总充总放时，优先查配置
        if (DataCollectConstant.Elec_Meter.TOTAL_CHARGE.equals(vo.getModelCol()) || DataCollectConstant.Elec_Meter.TOTAL_DISCHARGE.equals(vo.getModelCol())) {
            String deviceType = colCountService.getDeviceType(vo.getStationId());
            if (null != deviceType) {
                vo.setDeviceType(deviceType);
            }
        }
        // 联城电站需要，增加以下代码
        if (null != vo.getSrcId() && !deviceList.isEmpty()) {
            //虚拟设备直接放行
            if (!deviceList.get(0).getDeviceType().contains(vo.getDeviceType()) && !CommonConstant.ONE.equals(deviceList.get(0).getVirtual())) {
                deviceList = deviceService.getListByDeviceTypeAndPid(vo.getStationId(), deviceList.get(0).getPid(), vo.getDeviceType());
                deviceList = deviceList.stream().filter(i -> null != vo.getDeviceName() && i.getDeviceName().contains(vo.getDeviceName())).collect(Collectors.toList());
            }
        }
        if (null == vo.getSrcId()) {
            deviceList = deviceList.stream().filter(i -> null != i.getDeviceType() && i.getDeviceType().contains(vo.getDeviceType())).collect(Collectors.toList());
        }
        List<ModelDeviceColComp> compList = null;
        PointCurveSrcCol pointCurveSrcCol = null;
        List<String> cols = null;
        Map<String, BigDecimal> map = null;
        for (DeviceRespVO device : deviceList) {
            pointCurveSrcCol = new PointCurveSrcCol();
            if (CommonConstant.ZERO.equals(device.getVirtual())) {
                compList = modelDeviceService.getCompListByType(CommonConstant.ModelDeviceType.DEVICE, device.getDeviceType(), vo.getModelCol());
                if (null != compList && compList.size() > 0) {
                    pointCurveSrcCol.setSrcId(device.getSrcId());
                    pointCurveSrcCol.setDeviceType(device.getDeviceType());
                    cols = new ArrayList<>();
                    cols.add(compList.get(0).getDeviceCol());
                    pointCurveSrcCol.setCols(cols);
                    deviceIdList.add(pointCurveSrcCol);
                }
            } else if (CommonConstant.ONE.equals(device.getVirtual())) {
                //虚拟设备,来自于虚拟映射表
                VirtualDeviceCol virtualDeviceColReq = new VirtualDeviceCol();
                virtualDeviceColReq.setStationId(vo.getStationId());
                virtualDeviceColReq.setType(vo.getModelCol());
                virtualDeviceColReq.setSrcId(vo.getSrcId());
                List<VirtualDeviceColResp> virtualColList = virtualDeviceColService.getList(virtualDeviceColReq);
                if (null != virtualColList && virtualColList.size() > 0) {
                    pointCurveSrcCol.setSrcId(device.getFromId());
                    pointCurveSrcCol.setDeviceType(device.getDeviceType());
                    cols = new ArrayList<>();
                    cols.add(virtualColList.get(0).getCol());
                    map = new HashMap<>();
                    map.put(virtualColList.get(0).getCol(), virtualColList.get(0).getFactor());
                    pointCurveSrcCol.setMap(map);
                    pointCurveSrcCol.setCols(cols);
                    deviceIdList.add(pointCurveSrcCol);
                }
            }
        }
        pointCurveReq.setStationId(vo.getStationId());
        pointCurveReq.setDeviceIdList(deviceIdList);
        pointCurveReq.setBeginTime(vo.getBeginTime());
        pointCurveReq.setEndTime(vo.getEndTime());
        return pointCurveReq;
    }

    @Override
    public int getTimeDifference(String beginTime, String endTime) {
        //一、时间减法可以用Calendar对象加法中，把第二个参数换成负数可以时间，这边就不列举了；使用第二种方式做时间减法
        //1、指定两个Date对象，业务中可以以参数的形式传递，不用new当前时间。
        int diffMinute = 0;
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date begin = dateFormat.parse(beginTime);
            Date end = dateFormat.parse(endTime);
            //2、时间戳相减
            long endDateTime = end.getTime();
            long beginDateTime = begin.getTime();
            BigDecimal result = new BigDecimal(endDateTime).subtract(new BigDecimal(beginDateTime));//毫秒
            //换算成分钟
            BigDecimal minute = result.divide(new BigDecimal(1000));//60秒等于1分钟
            BigDecimal divide = minute.divide(new BigDecimal(60), 1, BigDecimal.ROUND_UP);
            diffMinute = divide.intValue();
        } catch (Exception e) {

        }
        return diffMinute;
    }

    @Override
    public PageResult<List<Object>> pointDataShow(PointCurveReq pointCurveReq) {
        //根据电站id查询电站信息
        Station station = stationService.selectById(pointCurveReq.getStationId());
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        List<Object> list = new ArrayList<>();
        //获取设备和点表字段的集合
        List<PointCurveSrcCol> deviceIdList = pointCurveReq.getDeviceIdList();
        //查询所要的时序数据的表名
        Map<Integer, String> map = new HashMap<>();
        //存储srcId以及config名字
        Map<Integer, String> srcIdAndNameMap = new HashMap<>();
        Map<Integer, String> srcIdAndDeviceTypeMap = new HashMap<>();

        Map<String, String> colNameMap = new HashMap<>();
        Map<String, BigDecimal> colMaxMap = new HashMap<>();
        Map<String, BigDecimal> colMinMap = new HashMap<>();
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            Device device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId(),pointCurveReq.getLang());
            DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
            if (device != null && device.getDeviceType() != null) {
                deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
            }
            if (deviceTypeConfig != null) {
                map.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getModelName());
                srcIdAndNameMap.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getName());
                srcIdAndDeviceTypeMap.put(pointCurveSrcCol.getSrcId(), device.getDeviceType());
                pointCurveSrcCol.setDeviceType(device.getDeviceType());
            }
            List<DeviceTypeCol> deviceTypeCols = deviceTypeColService.selectDeviceTypeColList(pointCurveSrcCol.getDeviceType(), pointCurveSrcCol.getCols(),pointCurveReq.getLang());
            Map<String, String> nameMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getColName));
            Map<String, BigDecimal> maxMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getMaxValue));
            Map<String, BigDecimal> minMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getMinValue));;
            colNameMap.putAll(nameMap);
            colMaxMap.putAll(maxMap);
            colMinMap.putAll(minMap);
        }
        //根据map做判断分别调用不同的mapper查询
        TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
        tdBaseTimeQuery.setBeginTime(pointCurveReq.getBeginTime());
        tdBaseTimeQuery.setEndTime(pointCurveReq.getEndTime());
        tdBaseTimeQuery.setStationId(pointCurveReq.getStationId());
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        tdBaseTimeQuery.setMap(map);
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        tdBaseTimeQuery.setBeginNum((pointCurveReq.getPageNum() - 1) * pointCurveReq.getPageSize());
        tdBaseTimeQuery.setPageSize(pointCurveReq.getPageSize());

        //根据查询条件分组
        Map<String, List<PointData>> colMap = new HashMap<>();

        int totalNum = 0;
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            tdBaseTimeQuery.setSrcId(pointCurveSrcCol.getSrcId());
            List<String> cols = pointCurveSrcCol.getCols();
            for (String col : cols) {
                tdBaseTimeQuery.setCol(col);
                int num = feignClient.getCountPointDataShow(tdBaseTimeQuery);
                //每次拿到后判断是否成功
                totalNum = Math.max(totalNum, num);
            }
        }
        log.info("最大条数totalNum:{}", totalNum);
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            tdBaseTimeQuery.setSrcId(pointCurveSrcCol.getSrcId());
            List<String> cols = pointCurveSrcCol.getCols();
            for (String col : cols) {
                tdBaseTimeQuery.setCol(col);
                DataResult<List<PointData>> pointDataShow = feignClient.getPointDataShow(tdBaseTimeQuery);
                //每次拿到后判断是否成功
                List<PointData> data = pointDataShow.getData();
                if (!pointDataShow.isSuccess() || data == null) {
                    log.error("pointDataShow is Error");
                } else {
                    if (!data.isEmpty()) {
                        colMap.put(pointCurveSrcCol.getSrcId() + col, data);
                    }
                }
            }
        }
        Set<Map.Entry<String, List<PointData>>> entries = colMap.entrySet();
        List<Map.Entry<String, List<PointData>>> collect = entries.stream().sorted((s1, s2) -> {
            return s1.getValue().size() - s2.getValue().size();
        }).collect(Collectors.toList());
        //获取集合数量最大的值
        int maxSize = 0;
        if (collect.size() > 0) {
            maxSize = collect.get(collect.size() - 1).getValue().size();
        }

        for (int i = 0; i < maxSize; i++) {
//            List<PointData> points = new ArrayList<>();
//            for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
//                List<String> cols = pointCurveSrcCol.getCols();
//                for (String col : cols) {
//                    if (colMap.get(pointCurveSrcCol.getSrcId() + col).size() - 1 > i) {
//                        PointData pointData = colMap.get(pointCurveSrcCol.getSrcId() + col).get(i);
//                        points.add(pointData);
//                    }
//                }
//            }
//            list.add(points);
            Map<String, Object> dataMap = new LinkedHashMap<>();
            int pNum = 0, len = 0, cNum = 0;
            for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
                List<String> cols = pointCurveSrcCol.getCols();
                len = cols.size();
                cNum = 0;
                for (String col : cols) {
                    if (colMap.get(pointCurveSrcCol.getSrcId() + col) != null && colMap.get(pointCurveSrcCol.getSrcId() + col).size() > i) {
                        PointData pointData = colMap.get(pointCurveSrcCol.getSrcId() + col).get(i);
                        dataMap.put(DeviceTypeConstant.POINT_DATA.ROW_NAME_DATE + (pNum * len + cNum), DeviceTypeConstant.TIME);
                        dataMap.put(DeviceTypeConstant.POINT_DATA.DATE + (pNum * len + cNum), pointData.getDate());
                        dataMap.put(DeviceTypeConstant.POINT_DATA.ROW_NAME_DIGITAL + (pNum * len + cNum), colNameMap.get(pointCurveSrcCol.getDeviceType() + "_" + col));
                        dataMap.put(DeviceTypeConstant.POINT_DATA.DIGITAL + (pNum * len + cNum), pointData.getDigital());
                        //上海售后需求-BMS直接过滤超过测点设置的最大值最小的数据
                        if(pointCurveSrcCol.getDeviceType() != null && pointCurveSrcCol.getDeviceType().contains("bms")){
                            BigDecimal maxValue = colMaxMap.get(pointCurveSrcCol.getDeviceType() + "_" + col);
                            BigDecimal minValue = colMinMap.get(pointCurveSrcCol.getDeviceType() + "_" + col);
                            if((maxValue != null &&  pointData.getDigital()>Double.parseDouble(maxValue.toString()))
                                    ||(minValue != null &&  pointData.getDigital()<Double.parseDouble(minValue.toString()))){
                                dataMap.put(DeviceTypeConstant.POINT_DATA.DIGITAL + (pNum * len + cNum), null);
                            }
                        }
                        cNum++;
                    }
                }
                pNum++;
            }
            list.add(dataMap);
        }
        PageResult pageResult = new PageResult<>();
        if (!list.isEmpty()) {
            pageResult = PageUtils.getPageResult(new PageInfo<>(list));
            pageResult.setTotalRows(totalNum);
            pageResult.setTotalPages(totalNum / pointCurveReq.getPageSize() + 1);
        } else {
            pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }
        return pageResult;
    }

    @Override
    public List<PageResult> pointDataShowList(PointCurveReq pointCurveReq) {
        //根据电站id查询电站信息
        String beginTime = pointCurveReq.getBeginTime();
        String endTime = pointCurveReq.getEndTime();
        try {
            DateUtil.parse(beginTime, CommonConstant.DATE);
            DateUtil.parse(endTime, CommonConstant.DATE);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(BaseResponseCode.METHODARGUMENTNOTVALIDEXCEPTION);
        }
        Station station = stationService.selectById(pointCurveReq.getStationId());
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        //获取设备和点表字段的集合
        List<PointCurveSrcCol> deviceIdList = pointCurveReq.getDeviceIdList();
        //查询所要的时序数据的表名
        Map<Integer, String> map = new HashMap<>();
        //存储srcId以及config名字
        Map<Integer, String> srcIdAndNameMap = new HashMap<>();
        Map<Integer, String> srcIdAndDeviceTypeMap = new HashMap<>();

        Map<String, String> colNameMap = new HashMap<>();
        Map<String, BigDecimal> colMaxMap = new HashMap<>();
        Map<String, BigDecimal> colMinMap = new HashMap<>();

        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            Device device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId(),pointCurveReq.getLang());
            DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
            if (device != null && device.getDeviceType() != null) {
                //若是虚拟设备，则取来自的真实设备
                if (device.getSrcId() < 0) {
                    device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), device.getFromId(),pointCurveReq.getLang());
                    pointCurveSrcCol.setSrcId(device.getSrcId());
                }
                pointCurveSrcCol.setDeviceName(device.getDeviceName());
                deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
            }
            if (deviceTypeConfig != null) {
                map.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getModelName());
                srcIdAndNameMap.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getName());
                srcIdAndDeviceTypeMap.put(pointCurveSrcCol.getSrcId(), device.getDeviceType());
                pointCurveSrcCol.setDeviceType(device.getDeviceType());
            }
            List<DeviceTypeCol> deviceTypeCols = deviceTypeColService.selectDeviceTypeColList(pointCurveSrcCol.getDeviceType(), pointCurveSrcCol.getCols(),pointCurveReq.getLang());
            Map<String, String> nameMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getColName));
            Map<String, BigDecimal> maxMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getMaxValue));
            Map<String, BigDecimal> minMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getMinValue));;
            colNameMap.putAll(nameMap);
            colMaxMap.putAll(maxMap);
            colMinMap.putAll(minMap);

        }
        //根据map做判断分别调用不同的mapper查询
        TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
        tdBaseTimeQuery.setBeginTime(pointCurveReq.getBeginTime());
        tdBaseTimeQuery.setEndTime(pointCurveReq.getEndTime());
        tdBaseTimeQuery.setStationId(pointCurveReq.getStationId());
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        tdBaseTimeQuery.setMap(map);
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        tdBaseTimeQuery.setBeginNum((pointCurveReq.getPageNum() - 1) * pointCurveReq.getPageSize());
        tdBaseTimeQuery.setPageSize(pointCurveReq.getPageSize());

        List<PageResult> resultList = new ArrayList<>();
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            tdBaseTimeQuery.setSrcId(pointCurveSrcCol.getSrcId());
            List<String> cols = pointCurveSrcCol.getCols();
            for (String col : cols) {
                tdBaseTimeQuery.setCol(col);
                DataResult<List<PointData>> pointDataShow = feignClient.getPointDataShow(tdBaseTimeQuery);
                int totalNum = feignClient.getCountPointDataShow(tdBaseTimeQuery);
                //每次拿到后判断是否成功
                List<PointData> data = pointDataShow.getData();
                if (!pointDataShow.isSuccess() || data == null) {
                    log.error("pointDataShow is Error");
                } else {
                    //获取集合数量最大的值
                    PageResult pageResult = new PageResult<>();
                    if (!data.isEmpty()) {
                        List<Object> list = new ArrayList<>();
                        for (PointData pointData : data) {
                            Map<String, Object> dataMap = new LinkedHashMap<>();
                            dataMap.put(DeviceTypeConstant.POINT_DATA.ROW_NAME_DATE + CommonConstant.ZERO, DeviceTypeConstant.TIME);
                            dataMap.put(DeviceTypeConstant.POINT_DATA.DATE + CommonConstant.ZERO, pointData.getDate());
                            dataMap.put(DeviceTypeConstant.POINT_DATA.ROW_NAME_DIGITAL + CommonConstant.ZERO, pointCurveSrcCol.getDeviceName() + "_" + colNameMap.get(pointCurveSrcCol.getDeviceType() + "_" + col));
                            dataMap.put(DeviceTypeConstant.POINT_DATA.DIGITAL + CommonConstant.ZERO, pointData.getDigital());
                            dataMap.put(DeviceTypeConstant.POINT_DATA.SRC_ID + CommonConstant.ZERO, pointCurveSrcCol.getSrcId());
                            dataMap.put(DeviceTypeConstant.POINT_DATA.COL + CommonConstant.ZERO, col);
                            //上海售后需求-BMS直接过滤超过测点设置的最大值最小的数据
                            if(pointCurveSrcCol.getDeviceType() != null && pointCurveSrcCol.getDeviceType().contains("bms")){
                                BigDecimal maxValue = colMaxMap.get(pointCurveSrcCol.getDeviceType() + "_" + col);
                                BigDecimal minValue = colMinMap.get(pointCurveSrcCol.getDeviceType() + "_" + col);
                                if((maxValue != null &&  pointData.getDigital()>Double.parseDouble(maxValue.toString()))
                                        ||(minValue != null &&  pointData.getDigital()<Double.parseDouble(minValue.toString()))){
                                    dataMap.put(DeviceTypeConstant.POINT_DATA.DIGITAL + CommonConstant.ZERO,null);
                                }
                            }
                            list.add(dataMap);
                        }
                        pageResult = PageUtils.getPageResult(new PageInfo<>(list));
                        pageResult.setTotalRows(totalNum);
                        pageResult.setTotalPages(totalNum / pointCurveReq.getPageSize() + 1);
                    } else {
                        pageResult = PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
                    }
                    resultList.add(pageResult);
                }
            }
        }
        return resultList;
    }

    @Override
    public List<PointCurveResp> pointCurve(PointCurveReq pointCurveReq) {
        //创建返回对象
        List<PointCurveResp> pointCurveRespList = new ArrayList<>();
        //根据电站id查询电站信息
        Station station = stationService.selectById(pointCurveReq.getStationId());
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        //获取设备和点表字段的集合
        List<PointCurveSrcCol> deviceIdList = pointCurveReq.getDeviceIdList();
        //查询所要的时序数据的表名
        Map<Integer, String> map = new HashMap<>();
        Map<String, BigDecimal> colMaxMap = new HashMap<>();
        Map<String, BigDecimal> colMinMap = new HashMap<>();

        //存储srcId以及config名字
        Map<Integer, String> srcIdAndNameMap = new HashMap<>();
        Map<Integer, String> srcIdAndDeviceTypeMap = new HashMap<>();
        //判断list中的数据 col字段中是否存在遥信值，将遥信和遥测值分开进行查询
        //遥测List
        List<PointCurveSrcCol> ycList = new ArrayList<>();
        //遥信List
        List<PointCurveSrcCol> yxList = new ArrayList<>();
//        DeviceTypeConfig deviceTypeConfig = null;
//        Integer id = null;
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
//            Device device = deviceService.selectByStationIdAndSrcId(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId());
//            //是虚拟设备
//            if (CommonConstant.ONE.equals(device.getVirtual())) {
//                device = deviceService.selectByStationIdAndSrcId(pointCurveReq.getStationId(), device.getFromId());
//                //此时把 pointCurveSrcCol 的设备id设置为真实设备id
//                pointCurveSrcCol.setSrcId(device.getFromId());
//            }
//            id = device.getSrcId();
//            if (device.getDeviceType() != null) {
//                deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
//            }
//            if (deviceTypeConfig != null) {
//                map.put(id, deviceTypeConfig.getModelName());
//                srcIdAndNameMap.put(id, device.getDeviceName());
//                srcIdAndDeviceTypeMap.put(id, device.getDeviceType());
//            }
            Device device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId(),pointCurveReq.getLang());
            Integer realSrcId = device.getFromId();
            if (device != null && device.getVirtual() == 1) {
                device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), device.getFromId(),pointCurveReq.getLang());
                //此时把 pointCurveSrcCol 的设备id设置为真实设备id
                pointCurveSrcCol.setSrcId(realSrcId);
            }
            if (!CommonConstant.ONE.equals(device.getVirtual())) {
                DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
                if (device != null && device.getDeviceType() != null) {
                    deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
                }
                if (deviceTypeConfig != null) {
                    map.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getModelName());
                    srcIdAndNameMap.put(pointCurveSrcCol.getSrcId(), device.getDeviceName());
                    srcIdAndDeviceTypeMap.put(pointCurveSrcCol.getSrcId(), device.getDeviceType());
                }
            } else {
                DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
                if (device != null && device.getDeviceType() != null) {
                    deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
                }
                if (deviceTypeConfig != null) {
                    map.put(device.getPid(), deviceTypeConfig.getModelName());
                    srcIdAndNameMap.put(device.getPid(), device.getDeviceName());
                    srcIdAndDeviceTypeMap.put(device.getPid(), device.getDeviceType());
                }
            }
            List<String> cols = pointCurveSrcCol.getCols();
            if (!cols.isEmpty()) {
                PointCurveSrcCol yxSrcCol = new PointCurveSrcCol();
                PointCurveSrcCol ycSrcCol = new PointCurveSrcCol();
                yxSrcCol.setDeviceType(device.getDeviceType());
                yxSrcCol.setSrcId(pointCurveSrcCol.getSrcId());
                ycSrcCol.setDeviceType(device.getDeviceType());
                ycSrcCol.setSrcId(pointCurveSrcCol.getSrcId());
                List<String> yxCols = new ArrayList<>();
                List<String> ycCols = new ArrayList<>();
                for (String col : cols) {
                    DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(col, device.getDeviceType(),pointCurveReq.getLang());
                    if (deviceTypeCol != null) {
                        if (CommonConstant.ONE.equals(pointCurveReq.getIsOriginal())) {
                            yxCols.add(col);
                        } else {
                            //1是遥信
                            if (CommonConstant.ONE.equals(deviceTypeCol.getSensType())) {
                                yxCols.add(col);
                            } else {
                                ycCols.add(col);
                                if(deviceTypeCol.getDeviceType().contains("bms")){
                                    colMaxMap.put(pointCurveSrcCol.getSrcId()+"_"+deviceTypeCol.getCol(),deviceTypeCol.getMaxValue());
                                    colMinMap.put(pointCurveSrcCol.getSrcId()+"_"+deviceTypeCol.getCol(),deviceTypeCol.getMinValue());
                                }
                            }
                        }

                    }
                }
                if (!yxCols.isEmpty()) {
                    yxSrcCol.setCols(yxCols);
                    yxList.add(yxSrcCol);
                }
                if (!ycCols.isEmpty()) {
                    ycSrcCol.setCols(ycCols);
                    ycList.add(ycSrcCol);
                }
            }
        }

        //先将遥测的list进行比对，
        Map<Integer, List<PointCurveSrcCol>> yxMapList = yxList.stream().collect(Collectors.groupingBy(i -> i.getSrcId()));
        List<String> needCols = null;
        for (PointCurveSrcCol pointCurveSrcCol : ycList) {
            needCols = new ArrayList<>();
            List<String> cols = pointCurveSrcCol.getCols();
            //只要查到的都已经转为遥信
            List<String> colsValue = convertService.selectByCols(station.getId(), pointCurveSrcCol.getSrcId(), cols);
            if (colsValue.size() > 0) {
                List<PointCurveSrcCol> pointCurveSrcCols = yxMapList.get(pointCurveSrcCol.getSrcId());
                if (pointCurveSrcCols == null) {
                    pointCurveSrcCols = new ArrayList<>();
                    PointCurveSrcCol point = new PointCurveSrcCol();
                    point.setSrcId(pointCurveSrcCol.getSrcId());
                    point.setDeviceType(pointCurveSrcCol.getDeviceType());
                    point.setCols(colsValue);
                    pointCurveSrcCols.add(point);
                    yxMapList.put(pointCurveSrcCol.getSrcId(), pointCurveSrcCols);
                } else {
                    List<String> cols1 = pointCurveSrcCols.get(0).getCols();
                    cols1.addAll(colsValue);
                    pointCurveSrcCols.get(0).setCols(cols1);
                }
            }
            //colMap.put(pointCurveSrcCol.getSrcId(),colsValue);
            Map<String, String> colsValueMap = colsValue.stream().collect(Collectors.toMap(Function.identity(), Function.identity()));
            for (String str : cols) {
                if (colsValueMap.get(str) == null) {
                    needCols.add(str);
                }
            }
            pointCurveSrcCol.setCols(needCols);
        }
        if (yxMapList.size() > 0) {
            yxList = new ArrayList<>();
            for (Map.Entry<Integer, List<PointCurveSrcCol>> m : yxMapList.entrySet()) {
                yxList.addAll(m.getValue());
            }
        }
        ycList = ycList.stream().filter(i -> i.getCols().size() > 0).collect(Collectors.toList());

        //计算(采样率)出开始时间与结束时间的差 （大于1440 采样率是 时间/60）
        Integer samlRate = null;
//        int timeDifference = getTimeDifference(pointCurveReq.getBeginTime(), pointCurveReq.getEndTime());
//        int timeDifference = CustomTimeUtils.getTimeDifferenceBySecond(pointCurveReq.getBeginTime(), pointCurveReq.getEndTime());
//        if (timeDifference <= 1441) {
//            samlRate = 1;
//        } else {
//            double divisor = 1441;
//            double flag = Math.ceil(timeDifference / divisor);        //向上取整计算
//            samlRate = (int) flag;
//        }
        samlRate = CustomTimeUtils.getSamlRate(pointCurveReq.getBeginTime(), pointCurveReq.getEndTime(), DateField.SECOND);
        //传采样率 srcId 电站id groupId 字段col
        //根据map做判断分别调用不同的mapper查询
        TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
//        tdBaseTimeQuery.setTime(samlRate + "m");
        tdBaseTimeQuery.setTime(samlRate + "s");
        if(CommonConstant.ONE.equals(pointCurveReq.getIsStrategy())){
            samlRate = CommonConstant.ONE;
            tdBaseTimeQuery.setTime(samlRate + "m");
        }
        tdBaseTimeQuery.setBeginTime(pointCurveReq.getBeginTime());
        tdBaseTimeQuery.setEndTime(pointCurveReq.getEndTime());
        tdBaseTimeQuery.setTimeInterval(samlRate);
        tdBaseTimeQuery.setStationId(pointCurveReq.getStationId());
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        tdBaseTimeQuery.setMap(map);
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        DataResult<List<PointCurveResp>> result = new DataResult<>();
        List<PointCurveResp> dataList = new ArrayList<>();
        //遥信
        if (!yxList.isEmpty()) {
            tdBaseTimeQuery.setDeviceIdList(yxList);
            DataResult<List<PointCurveResp>> yxResult = feignClient.querySignalValue(tdBaseTimeQuery);
            dataList.addAll(yxResult.getData());
        }
        //遥测
        if (!ycList.isEmpty()) {
            tdBaseTimeQuery.setDeviceIdList(ycList);
            DataResult<List<PointCurveResp>> ycResult = feignClient.queryPointTable(tdBaseTimeQuery);
            //遥测数据筛选BMS超过最大最小值数据
            List<PointCurveResp> ycResultByFilter =  new ArrayList<>();
            for(PointCurveResp pointCurveResp:ycResult.getData()){
                if(pointCurveResp.getStaticCurveList() != null || !pointCurveResp.getStaticCurveList().isEmpty()){
                    //获取最大值最小值
                    BigDecimal maxValue = colMaxMap.get(pointCurveResp.getSrcId()+"_"+pointCurveResp.getCol());
                    BigDecimal minValue = colMinMap.get(pointCurveResp.getSrcId()+"_"+pointCurveResp.getCol());
                    if(maxValue != null && minValue != null){
                        List<StatisticsCurve> staticCurveList = pointCurveResp.getStaticCurveList().stream()
                                .filter(e -> (e.getDigital() == null )||
                                        ( e.getDigital()>= Double.parseDouble(minValue.toString())&& e.getDigital()<= Double.parseDouble(maxValue.toString())))
                                .collect(Collectors.toList());
                        pointCurveResp.setStaticCurveList(staticCurveList);
                    }
                }
                ycResultByFilter.add(pointCurveResp);
            }
            dataList.addAll(ycResultByFilter);
        }
        result.setData(dataList);

        List<PointCurveResp> data = result.getData();
        pointCurveRespList.addAll(data);
        if (!pointCurveRespList.isEmpty()) {
            for (PointCurveResp pointCurveResp : pointCurveRespList) {
                if (!pointCurveResp.getStaticCurveList().isEmpty() || pointCurveResp.getStaticCurveList() != null) {
                    for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
                        if (pointCurveResp.getSrcId().equals(pointCurveSrcCol.getSrcId())) {
                            Device device = deviceService.selectByStationIdAndSrcId(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId());
                            //根据deviceType和col进行在deviceTypeCol表
                            DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(pointCurveResp.getCol(), device.getDeviceType(),pointCurveReq.getLang());
                            if (deviceTypeCol != null) {
                                pointCurveResp.setUnit(deviceTypeCol.getUnit());
                                pointCurveResp.setColName(deviceTypeCol.getColName());
                                pointCurveResp.setUnit(deviceTypeCol.getUnit());
                                pointCurveResp.setDeviceName(srcIdAndNameMap.get(pointCurveResp.getSrcId()));
                                continue;
                            }
                        }

                    }
                } else {
                    String deviceType = srcIdAndDeviceTypeMap.get(pointCurveResp.getSrcId());
                    PointCurveResp point = new PointCurveResp();
                    point.setSrcId(pointCurveResp.getSrcId());
                    point.setCol(pointCurveResp.getCol());
                    point.setDeviceName(srcIdAndNameMap.get(pointCurveResp.getSrcId()));
                    //根据deviceType 和col进行查询colName
                    DeviceTypeCol deviceTypeCol = deviceTypeColService.selectTypeAndCol(pointCurveResp.getCol(), deviceType,pointCurveReq.getLang());
                    point.setColName(deviceTypeCol.getColName());
                    point.setStaticCurveList(new ArrayList<>());
                    point.setUnit(deviceTypeCol.getUnit());
                    pointCurveRespList.remove(pointCurveResp);
                    pointCurveRespList.add(point);
                    continue;
                }
            }
        } else {
            for (int i = 0; i < srcIdAndNameMap.size(); i++) {
                PointCurveSrcCol pointCurveSrcCol = deviceIdList.get(i);
                String deviceType = srcIdAndDeviceTypeMap.get(pointCurveSrcCol.getSrcId());
                List<String> cols = pointCurveSrcCol.getCols();
                DeviceTypeCol deviceTypeCol = new DeviceTypeCol();
                for (String col : cols) {
                    PointCurveResp pointCurveResp = new PointCurveResp();
                    pointCurveResp.setSrcId(pointCurveSrcCol.getSrcId());
                    pointCurveResp.setCol(col);
                    pointCurveResp.setDeviceName(srcIdAndNameMap.get(pointCurveSrcCol.getSrcId()));
                    //根据deviceType 和col进行查询colName
                    deviceTypeCol = deviceTypeColService.selectTypeAndCol(pointCurveResp.getCol(), deviceType,pointCurveReq.getLang());
                    pointCurveResp.setColName(deviceTypeCol.getColName());
                    pointCurveResp.setStaticCurveList(new ArrayList<>());
                    pointCurveResp.setUnit(deviceTypeCol.getUnit());
                    pointCurveRespList.add(pointCurveResp);
                }
            }
        }
        //判断返回值中所包含的list是否全部为空，全部为空则提示，所选择的指标则无数据
        //只要有一个list数据存在，则不进行报错
        pointCurveRespList = pointCurveRespList.stream().map(s -> {
            if (s.getStaticCurveList() == null) {
                s.setStaticCurveList(new ArrayList<>());
            }
            return s;
        }).collect(Collectors.toList());
        return pointCurveRespList;
    }

    /**
     * 1:遥测 2:遥信   对遥信返回数据进行处理
     * @param pointCurveRespList
     * @param beginTime
     * @param endTime
     * @param isStrategy 是否为策略总览页面(1:是;0:否)
     * @return
     */
    private List<PointCurveResp> getSignalValue(List<PointCurveResp> pointCurveRespList, String beginTime,
                                                String endTime,Integer isStrategy) {
        //返回值
        List<PointCurveResp> signalList = new ArrayList<>();
        //判断是否只有遥信数据:如果存在两种类型的数据，将遥测数据的时间生成一个单独的List<String>
        List<StatisticsCurve> statisticsList = new ArrayList<>();
        for (PointCurveResp pointCurveResp : pointCurveRespList) {
            if (!CommonConstant.ONE.equals(pointCurveResp.getIdentifier())) {
                for (StatisticsCurve statisticsRespVO : pointCurveResp.getStaticCurveList()) {
                    StatisticsCurve statistics = new StatisticsCurve();
                    statistics.setDate(statisticsRespVO.getDate());
                    statisticsList.add(statistics);
                }
                break;
            }

        }
        //如果只有遥信，则根据开始结束时间生成1440个数据点位
        List<DateTime> dateTimeList = new ArrayList<>();
        if (statisticsList.isEmpty()) {
//            int timeDifference = getTimeDifference(beginTime, endTime);
//            int timeDifference = CustomTimeUtils.getTimeDifferenceBySecond(beginTime, endTime);
//            int samlRate = 0;
//            if (timeDifference <= 1441) {
//                samlRate = 1;
//            } else {
//                double divisor = 1441;
//                double flag = Math.ceil(timeDifference / divisor);        //向上取整计算
//                samlRate = (int) flag;
//            }
            int samlRate = CustomTimeUtils.getSamlRate(beginTime, endTime, DateField.SECOND);
            if(CommonConstant.ONE.equals(isStrategy)){
                samlRate = CommonConstant.ONE;
                dateTimeList = DateUtil.rangeToList(DateUtil.parse(beginTime, CommonConstant.DATE),
                        DateUtil.parse(endTime, CommonConstant.DATE), DateField.MINUTE, samlRate);
            }else{
                dateTimeList = DateUtil.rangeToList(DateUtil.parse(beginTime, CommonConstant.DATE),
                        DateUtil.parse(endTime, CommonConstant.DATE), DateField.SECOND, samlRate);
            }
            for (DateTime dateTime : dateTimeList) {
                StatisticsCurve statistics = new StatisticsCurve();
                statistics.setDate(DateUtil.format(dateTime, CommonConstant.DATE));
                statisticsList.add(statistics);
            }
        }
        // 根据时间List 对时间进行对比赋值
        Date beginParse = null;
        Date endParse = null;
        DateTime date = null;
        for (PointCurveResp pointCurveResp : pointCurveRespList) {
            if (CommonConstant.ONE.equals(pointCurveResp.getIdentifier())) {
                List<StatisticsCurve> staticCurveList = pointCurveResp.getStaticCurveList();
                if (CommonConstant.TWO.equals(staticCurveList.size()) &&
                        staticCurveList.get(0).getDigital() == null && staticCurveList.get(1).getDigital() == null) {
                    pointCurveResp.setStaticCurveList(new ArrayList<>());
                } else {
                    List<StatisticsCurve> curveList = mapperFacade.mapAsList(statisticsList, StatisticsCurve.class);
                    //原始数据
                    int xhnum = 0;
                    int len = curveList.size(), num = 0;
                    for (int i = 1; i < staticCurveList.size(); i++) {
                        //需要比较的时间(原始数据的第一条数据和第二条数据为一个区间)
                        StatisticsCurve statisticsRespVO = staticCurveList.get(i - 1);
                        //开始时间
                        beginParse = DateUtil.parse(statisticsRespVO.getDate(), CommonConstant.DATE);
                        StatisticsCurve statisticsResp = staticCurveList.get(i);
                        //结束时间
                        endParse = DateUtil.parse(statisticsResp.getDate(), CommonConstant.DATE);
                        //需要赋值的数据
//                        for (StatisticsCurve respVO : curveList) {
//                            if (respVO.getDate().equals(statisticsRespVO.getDate())) {
//                                respVO.setDigital(statisticsRespVO.getDigital());
//                            } else if (respVO.getDate().equals(statisticsResp.getDate())) {
//                                respVO.setDigital(statisticsResp.getDigital());
//                            } else {
//                                date = DateUtil.parse(respVO.getDate(), CommonConstant.DATE);
//                                boolean isExist = timeCalendar(date, beginParse, endParse);
//                                if (isExist) {
//                                    respVO.setDigital(statisticsRespVO.getDigital());
//                                } else {
//                                    continue;
//                                }
//                            }
//                        }
//                    for (int j = 1; j < curveList.size(); j++) {
//                        StatisticsCurve vo = curveList.get(j);
//                        if (vo.getDigital() == null) {
//                            StatisticsCurve resp = curveList.get(j - 1);
//                            vo.setDigital(resp.getDigital());
//                        }
//                    }
                        Date cDate = null;
                        StatisticsCurve respVO = null;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                        String strBeginParse = sdf.format(beginParse);
                        String strEndParse = sdf.format(endParse);
                        for (int j = num; j < len; j++) {
                            respVO = curveList.get(j);
                            cDate = DateUtil.parse(respVO.getDate(), CommonConstant.DATE);
/*                            String strCDate = sdf.format(cDate);
                            int strBeginParseDate = Integer.parseInt(strBeginParse.substring(11, 13) + strBeginParse.substring(14, 16));
                            ;
                            int strEndParseDate = Integer.parseInt(strEndParse.substring(11, 13) + strEndParse.substring(14, 16));
                            ;
                            int strCDateDate = Integer.parseInt(strCDate.substring(11, 13) + strCDate.substring(14, 16));
                            ;
                            if(strCDateDate == strEndParseDate){
                                respVO.setDigital(statisticsResp.getDigital());
                            }
                            if ((strCDateDate >= strBeginParseDate && strCDateDate <= strEndParseDate)) {
                                respVO.setDigital(statisticsRespVO.getDigital());
                            } else {
                                num = j;
                                break;
                            }*/

                            //在区间内
                            if (cDate.getTime() - beginParse.getTime() >= 0 && cDate.getTime() - endParse.getTime() <= 0) {
                                respVO.setDigital(statisticsRespVO.getDigital());
                            } else if (cDate.getTime() - endParse.getTime() > 0) {
                                if(j>0){
                                    respVO = curveList.get(j-1);
                                }else{
                                    respVO = curveList.get(j);
                                }
                                if(respVO != null){
                                    respVO.setDigital(statisticsRespVO.getDigital());
                                }
                                num = j;
                                break;
                            }
                            xhnum++;
                        }

                    }
                    log.info("循环次数:{}", xhnum);
                    pointCurveResp.setStaticCurveList(curveList);
                    signalList.add(pointCurveResp);
                }

            } else {
                signalList.add(pointCurveResp);
            }
        }
        return signalList;
    }

    @Override
    public List<PointCurveResp> getPointCurve(PointCurveReq pointCurveReq) {
        List<PointCurveResp> list = pointCurve(pointCurveReq);
        //调用补齐遥信数据接口
        List<PointCurveResp> pointCurveRespList = getSignalValue(list, pointCurveReq.getBeginTime(), pointCurveReq.getEndTime(),pointCurveReq.getIsStrategy());
        return pointCurveRespList;
    }


    @Override
    public void getHisExportExcel(PointCurveReq pointCurveReq, HttpServletResponse response) {
        List<PointCurveResp> pointCurve = new ArrayList<>();
        if (CommonConstant.ONE.equals(pointCurveReq.getPageType())) {
            //取表格的值
            pointCurve = getPointDataShowList(pointCurveReq);

        } else {
            pointCurve = getPointCurve(pointCurveReq);
        }
        //判断是否为策略总览页面查询
        if (pointCurveReq.getIsStrategy() != null && pointCurveReq.getIsStrategy() == 1) {
            PointCurveResp pointCurveResp = getPlanCurve(pointCurveReq.getStationId());
            if (pointCurveResp != null) {
                pointCurve.add(pointCurveResp);
            }
        }
        List<String> titleList = new ArrayList<>();
        String time;
        if(CommonConstant.langTemp.EN_US.equals(pointCurveReq.getLang())){
            time = DefineConstant.PointDemo.TIME_EN;
        }else if(CommonConstant.langTemp.FR_FR.equals(pointCurveReq.getLang())){
            time = DefineConstant.PointDemo.TIME_FRA;
        }else if(CommonConstant.langTemp.ES_ES.equals(pointCurveReq.getLang())){
            time = DefineConstant.PointDemo.TIME_SPA;
        }else if(CommonConstant.langTemp.AR_EG.equals(pointCurveReq.getLang())){
            time = DefineConstant.PointDemo.TIME_ARA;
        }else if(CommonConstant.langTemp.DE_DE.equals(pointCurveReq.getLang())){
            time = DefineConstant.PointDemo.TIME_DE;
        }else if(CommonConstant.langTemp.PL_PL.equals(pointCurveReq.getLang())){
            time = DefineConstant.PointDemo.TIME_PL;
        }else{
            time  = DefineConstant.PointDemo.TIME;
        }
        if (!CommonConstant.ONE.equals(pointCurveReq.getPageType())) {
            titleList.add(time);
        }
        for (PointCurveResp pointCurveResp : pointCurve) {
            if (CommonConstant.ONE.equals(pointCurveReq.getPageType())) {
                titleList.add(pointCurveResp.getColName() + "-"+time);
            }
            if (pointCurveResp.getUnit() == null) {
                titleList.add(pointCurveResp.getDeviceName() + "-" + pointCurveResp.getColName());
            } else {
                titleList.add(pointCurveResp.getDeviceName() + "-" + pointCurveResp.getColName() + "(" + pointCurveResp.getUnit() + ")");
            }
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        //将SXSSFWorkbook工作簿添加到表
        Sheet sheet = wb.createSheet();
        //创建行，  0：代表第一个单元格
        Row row = sheet.createRow(0);
        //给单元格设置样式，添加到工作簿的样式表中
        CellStyle cellStyle = wb.createCellStyle();
        //创建一个新字体，并添加到工作簿的字体表中
        Font font = wb.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 12);
        //设置字体加粗
        font.setBold(true);
        //给字体设置样式
        cellStyle.setFont(font);
        //设置单元格背景颜色
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //设置单元格填充样式（使用纯色背景颜色填充）
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        //填充表头数据
        int titleLength = 0;
        for (int i = 0; i < titleList.size(); i++) {
            if (titleList.get(i).getBytes().length * 2 * 128 > titleLength) {
                titleLength = titleList.get(i).getBytes().length * 2 * 128;
            }
        }

        for (int i = 0; i < titleList.size(); i++) {
            //创建新单元格
            Cell cell = row.createCell(i);
            //放入 标题单元格的数值
            cell.setCellValue(titleList.get(i));
            //为单元格设置样式
            cell.setCellStyle(cellStyle);
            //设置列的宽度
            sheet.setColumnWidth(i, titleLength);
        }
        if (CommonConstant.ONE.equals(pointCurveReq.getPageType())) {
            //先找到最大size
            int length = 0;
            for (PointCurveResp pointCurveResp : pointCurve) {
                int size = pointCurveResp.getStaticCurveList().size();
                if (size > length) {
                    length = size;
                }
            }
            int titleLen = titleList.size() / CommonConstant.TWO;
            for (int j = 0; j < length; j++) {
                Row r = sheet.createRow(j + 1);
                for (int i = 0; i < titleLen; i++) {
                    List<StatisticsCurve> staticCurveList = pointCurve.get(i).getStaticCurveList();
                    for (StatisticsCurve statisticsCurve : staticCurveList) {
                        if (statisticsCurve.getDigital() == null) {
                            statisticsCurve.setDigital(new Double(0));
                        }
                    }
                    if (j < staticCurveList.size()) {
                        Cell cell = r.createCell(i * CommonConstant.TWO);
                        cell.setCellValue(staticCurveList.get(j).getDate());
                        Cell cell2 = r.createCell(i * CommonConstant.TWO + CommonConstant.ONE);
                        cell2.setCellValue(staticCurveList.get(j).getDigital().toString());
                    }
                }
            }
        } else {
            List<Map<String, HisPointValueRespVo>> timeDataMap = new ArrayList<>();
            int length = 0;
            Map<Integer, List<HisPointValueRespVo>> map = new HashMap<>();
            for (PointCurveResp pointCurveResp : pointCurve) {
                List<StatisticsCurve> staticCurveList = pointCurveResp.getStaticCurveList();
                List<HisPointValueRespVo> hisPointValueRespVoList = new ArrayList<>();
                for (StatisticsCurve statisticsRespVO : staticCurveList) {
                    HisPointValueRespVo hisPointValueRespVo = new HisPointValueRespVo();
                    hisPointValueRespVo.setDate(statisticsRespVO.getDate());
                    if (statisticsRespVO.getDigital() != null) {
                        hisPointValueRespVo.setDigital(statisticsRespVO.getDigital().toString());
                    } else {
                        hisPointValueRespVo.setDigital("");
                    }
                    hisPointValueRespVoList.add(hisPointValueRespVo);
                }
                Map<String, HisPointValueRespVo> m = new HashMap<>();
                for (int i = 0; i < hisPointValueRespVoList.size(); i++) {
                    m.put(staticCurveList.get(i).getDate(), hisPointValueRespVoList.get(i));
                }
                timeDataMap.add(m);
                if (staticCurveList.size() > length) {
                    length = staticCurveList.size();
                }
            }

            List<String> timeList = new ArrayList<>();
            for (PointCurveResp pointCurveResp : pointCurve) {
                List<StatisticsCurve> staticCurveList = pointCurveResp.getStaticCurveList();
                if (length == staticCurveList.size()) {
                    for (StatisticsCurve statisticsRespVO : staticCurveList) {
                        String date = statisticsRespVO.getDate();
                        timeList.add(date);
                    }
                }
            }
            Map<String, HisPointValueRespVo> rep = null;
            for (int j = 0; j < length; j++) {
                Row r = sheet.createRow(j + 1);
                //获取 时间（第一个单元格）
                Cell cell = r.createCell(0);
                cell.setCellValue(timeList.get(j));
                for (int i = 1; i < titleList.size(); i++) {
                    //获取 数值
                    rep = timeDataMap.get(i - 1);
                    if (rep != null && rep.get(timeList.get(j)) != null) {
                        Cell cell2 = r.createCell(i);
                        cell2.setCellValue(rep.get(timeList.get(j)).getDigital());
                    }
                }
            }
        }
        try {
            //输出Excel文件
            OutputStream output = response.getOutputStream();
            response.reset();
            //设置响应头，
            response.setHeader("Content-disposition", "attachment; filename=aaa.xls");
            response.setContentType("application/msexcel");
            wb.write(output);
            output.close();

        } catch (Exception e) {
            //异常信息
            e.printStackTrace();
        }
    }

    private XSSFWorkbook getXSSFWorkbook() {
        XSSFWorkbook wb = new XSSFWorkbook();
        //将SXSSFWorkbook工作簿添加到表
        Sheet sheet = wb.createSheet();
        //创建行，  0：代表第一个单元格
        Row row = sheet.createRow(0);
        //给单元格设置样式，添加到工作簿的样式表中
        CellStyle cellStyle = wb.createCellStyle();
        //创建一个新字体，并添加到工作簿的字体表中
        Font font = wb.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 12);
        //设置字体加粗
        font.setBold(true);
        //给字体设置样式
        cellStyle.setFont(font);
        //设置单元格背景颜色
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        //设置单元格填充样式（使用纯色背景颜色填充）
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return wb;
    }

    private List<PointCurveResp> getPointDataShowList(PointCurveReq pointCurveReq) {
        //根据电站id查询电站信息
        Station station = stationService.selectById(pointCurveReq.getStationId());
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        //获取设备和点表字段的集合
        List<PointCurveSrcCol> deviceIdList = pointCurveReq.getDeviceIdList();
        //查询所要的时序数据的表名
        Map<Integer, String> map = new HashMap<>();
        //存储srcId以及config名字
        Map<Integer, String> srcIdAndNameMap = new HashMap<>();
        Map<Integer, String> srcIdAndDeviceTypeMap = new HashMap<>();

        Map<String, String> colNameMap = new HashMap<>();
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            Device device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId(),pointCurveReq.getLang());
            DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
            if (device != null && device.getDeviceType() != null) {
                //若是虚拟设备，则取来自的真实设备
                if (device.getSrcId() < 0) {
                    device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), device.getFromId(),pointCurveReq.getLang());
                    pointCurveSrcCol.setSrcId(device.getSrcId());
                }
                pointCurveSrcCol.setDeviceName(device.getDeviceName());
                deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
            }
            if (deviceTypeConfig != null) {
                map.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getModelName());
                srcIdAndNameMap.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getName());
                srcIdAndDeviceTypeMap.put(pointCurveSrcCol.getSrcId(), device.getDeviceType());
                pointCurveSrcCol.setDeviceType(device.getDeviceType());
            }
            List<DeviceTypeCol> deviceTypeCols = deviceTypeColService.selectDeviceTypeColList(pointCurveSrcCol.getDeviceType(), pointCurveSrcCol.getCols(),pointCurveReq.getLang());
            Map<String, String> nameMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getColName));
            colNameMap.putAll(nameMap);
        }
        //根据map做判断分别调用不同的mapper查询
        TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
        tdBaseTimeQuery.setBeginTime(pointCurveReq.getBeginTime());
        tdBaseTimeQuery.setEndTime(pointCurveReq.getEndTime());
        tdBaseTimeQuery.setStationId(pointCurveReq.getStationId());
        tdBaseTimeQuery.setGroupId(station.getGroupId());
        tdBaseTimeQuery.setMap(map);
        tdBaseTimeQuery.setGroupId(station.getGroupId());

        List<PointCurveResp> list = new ArrayList<>();
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            tdBaseTimeQuery.setSrcId(pointCurveSrcCol.getSrcId());
            List<String> cols = pointCurveSrcCol.getCols();
            for (String col : cols) {
                tdBaseTimeQuery.setCol(col);
                DataResult<List<PointData>> pointDataShow = feignClient.getPointDataShow(tdBaseTimeQuery);
                //每次拿到后判断是否成功
                List<PointData> data = pointDataShow.getData();
                if (!pointDataShow.isSuccess() || data == null) {
                    log.error("pointDataShow is Error");
                } else {
                    PointCurveResp pointCurveResp = new PointCurveResp();
                    List<StatisticsCurve> staticCurveList = new ArrayList<>();
                    for (PointData datum : data) {
                        StatisticsCurve statisticsCurve = new StatisticsCurve();
                        statisticsCurve.setDate(datum.getDate());
                        statisticsCurve.setDigital(datum.getDigital());
                        staticCurveList.add(statisticsCurve);
                    }
                    pointCurveResp.setCol(col);
                    pointCurveResp.setSrcId(pointCurveSrcCol.getSrcId());
                    pointCurveResp.setDeviceName(pointCurveSrcCol.getDeviceName());
                    pointCurveResp.setColName(colNameMap.get(pointCurveSrcCol.getDeviceType() + "_" + col));
                    // dataMap.put(DeviceTypeConstant.POINT_DATA.ROW_NAME_DIGITAL + CommonConstant.ZERO, pointCurveSrcCol.getDeviceName() + "_" + colNameMap.get(pointCurveSrcCol.getDeviceType() + "_" + col));
                    pointCurveResp.setStaticCurveList(staticCurveList);
                    list.add(pointCurveResp);
                }
            }
        }
        return list;
    }


    @Override
    public PageResult<Map<Object, Object>> getPointAllData(TdBase tdBase) {
        PageResult pageResult = feignClient.queryAllValue(tdBase);
        return pageResult;
    }

    @Override
    public PointCurveResp getPlanCurve(Integer stationId) {
        //创建返回值
        PointCurveResp pointCurveResp = new PointCurveResp();
        PlanningIssueDevice issueDevice = new PlanningIssueDevice();
        issueDevice.setStationId(stationId);
        PlanningIssueDevice planningIssueDevice = issueService.queryIssueStatus(issueDevice);
        if (planningIssueDevice != null && planningIssueDevice.getId() != null) {
            PlanningCurveTemplate template = new PlanningTemplateVo();
            template.setTemId(planningIssueDevice.getPlanTemId());
            List<PlanningCurveTemplate> planningCurveTemplates = null;
            if (planningIssueDevice.getPlanTemId() != null) {
                planningCurveTemplates = planningService.planningCurveTemplateChartData(template);
            }
            if (CollectionUtils.isNotEmpty(planningCurveTemplates)) {
                PlanningCurveTemplate planningCurveTemplate = planningCurveTemplates.get(0);
                List<PlanningCurve> planningCurves = planningCurveTemplate.getPlanningCurves();
                List<StatisticsCurve> statisticsCurves = new ArrayList<>();
                for (PlanningCurve planningCurve : planningCurves) {
                    StatisticsCurve statisticsCurve = new StatisticsCurve();
                    statisticsCurve.setDigital(planningCurve.getP());
                    String date = DateUtil.formatDate(new Date());
                    statisticsCurve.setDate(date + " " + planningCurve.getStartTime());
                    statisticsCurves.add(statisticsCurve);
                }
                pointCurveResp.setDeviceName("计划曲线");
                pointCurveResp.setColName("计划曲线");
                pointCurveResp.setUnit("kW");
                pointCurveResp.setStaticCurveList(statisticsCurves);
                return pointCurveResp;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public Map<String,Object> getColCurve(CommonQuery vo) {
        Integer stationId = vo.getStationId();
        ConfigureQuery paramsobj = vo.getParamsobj();
        Integer dataType = paramsobj.getDataType();
        List<ConfigureKeyQuery> list = paramsobj.getRecordList();
        String redisKey = String.valueOf(stationId);
        Map<Object, Object> hgetall = redisService.hgetall(redisKey);
        List<PointCurveResp> dataList = new ArrayList<>();
        String myBeginTime = null;
        String myEndTime = null;
        Integer mySamlRate = null;
        boolean isSameTime = false;
        for (ConfigureKeyQuery c: list) {
            String beginTime = c.getStartTime()!=null ?c.getStartTime():DateUtil.format(DateUtil.beginOfDay(new Date()),CommonConstant.DATE) ;
            String endTime = c.getEndTime()!=null ?c.getEndTime():DateUtil.format(new Date(),CommonConstant.DATE) ;
            DateTime parseEndTime = DateUtil.parse(endTime, CommonConstant.DATE);
            Date now = new Date();
            if(now.getTime()-parseEndTime.getTime()<0){
                endTime = DateUtil.format(now, CommonConstant.DATE);
            }
            if(myBeginTime==null){
                myBeginTime = beginTime;
            }
            if(myEndTime==null){
                myEndTime = endTime;
            }
            List<String> fieldNameList = c.getFieldNameList();
            List<ColumnKey> keyList = c.getKeyList();
            List<String> legendList = c.getLegend();
            int len = fieldNameList.size();
            for (int i = 0; i < len; i++) {
                String s = fieldNameList.get(i);
                for (ColumnKey column:keyList) {
                    if(TableConstant.VAL.equals(s)){
                        DeviceColTransfer deviceTransfer = (DeviceColTransfer)hgetall.get(column.getKeyValue());
                        if(deviceTransfer != null){
                            String tdNameStr = deviceTransfer.getTdNameStr();
                            Integer sensType = deviceTransfer.getSensType();
                            PointCurveSrcCol p = new PointCurveSrcCol();
                            p.setLegend(deviceTransfer.getColName());
                            p.setTableName(tdNameStr);
                            p.setCol(deviceTransfer.getCol());
                            //计算(采样率)出开始时间与结束时间的差 （大于1440 采样率是 时间/60）
                            Integer samlRate = CustomTimeUtils.getSamlRate(beginTime, endTime, DateField.SECOND);
                            if(mySamlRate == null){
                                mySamlRate = samlRate;
                            }else{
                                //间隔相同，可以使用同一个X轴
                                if(samlRate.equals(mySamlRate)){
                                    if((myBeginTime.equals(beginTime) && myEndTime.equals(endTime))){
                                        isSameTime = true;
                                    }else{
                                        isSameTime = false;
                                    }
                                }else{
                                    throw new BusinessException(BaseResponseCode.DATA_ERROR);
                                }
                            }
                            TdBaseTimeQuery tdBaseTimeQuery = new TdBaseTimeQuery();
                            tdBaseTimeQuery.setTime(samlRate + "s");
                            tdBaseTimeQuery.setBeginTime(beginTime);
                            tdBaseTimeQuery.setEndTime(endTime);
                            tdBaseTimeQuery.setTimeInterval(samlRate);
                            tdBaseTimeQuery.setStationId(vo.getStationId());
                            List<PointCurveSrcCol> colList = new ArrayList<>();
                            colList.add(p);
                            tdBaseTimeQuery.setDeviceIdList(colList);
                            if(CommonConstant.TWO.equals(sensType) && !CommonConstant.ONE.equals(dataType)){
                                DataResult<List<PointCurveResp>> ycResult = feignClient.queryMeasure(tdBaseTimeQuery);
                                dataList.addAll(ycResult.getData());
                            }else{
                                DataResult<List<PointCurveResp>> yxResult = feignClient.querySignal(tdBaseTimeQuery);
                                List<PointCurveResp> data = yxResult.getData();
                                getSignalValue(data,beginTime,endTime,CommonConstant.ZERO);
                                dataList.addAll(data);
                            }
                        }
                    }
                }
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("isSameTime",isSameTime);
        resultMap.put("beginTime",myBeginTime);
        resultMap.put("endTime",myEndTime);
        resultMap.put("dataList",dataList);
        return resultMap;
    }

    @Override
    public int modifyHistoryData(PointCurveReq pointCurveReq) {
        Station station = stationService.selectById(pointCurveReq.getStationId());
        if (station == null) {
            throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
        }
        List<PointCurveSrcCol> deviceIdList = pointCurveReq.getDeviceIdList();
        //查询所要的时序数据的表名
        Map<Integer, String> map = new HashMap<>();
        Map<Integer, String> srcIdAndNameMap = new HashMap<>();
        Map<Integer, String> srcIdAndDeviceTypeMap = new HashMap<>();

        Map<String, String> colNameMap = new HashMap<>();
        for (PointCurveSrcCol pointCurveSrcCol : deviceIdList) {
            Device device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), pointCurveSrcCol.getSrcId(),pointCurveReq.getLang());
            DeviceTypeConfig deviceTypeConfig = new DeviceTypeConfig();
            if (device != null && device.getDeviceType() != null) {
                //若是虚拟设备，则取来自的真实设备
                if (device.getSrcId() < 0) {
                    device = deviceService.selectByStationIdAndSrcIdAndLng(pointCurveReq.getStationId(), device.getFromId(),pointCurveReq.getLang());
                    pointCurveSrcCol.setSrcId(device.getSrcId());
                }
                pointCurveSrcCol.setDeviceName(device.getDeviceName());
                deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
            }
            if (deviceTypeConfig != null) {
                map.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getModelName());
                srcIdAndNameMap.put(pointCurveSrcCol.getSrcId(), deviceTypeConfig.getName());
                srcIdAndDeviceTypeMap.put(pointCurveSrcCol.getSrcId(), device.getDeviceType());
                pointCurveSrcCol.setDeviceType(device.getDeviceType());
            }
            List<DeviceTypeCol> deviceTypeCols = deviceTypeColService.selectDeviceTypeColList(pointCurveSrcCol.getDeviceType(), pointCurveSrcCol.getCols(),pointCurveReq.getLang());
            Map<String, String> nameMap = deviceTypeCols.stream().collect(Collectors.toMap(s -> s.getDeviceType() + "_" + s.getCol(), DeviceTypeCol::getColName));
            colNameMap.putAll(nameMap);
        }
        return 0;
    }
}
