package com.ho.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ho.business.constant.DeviceTypeConstant;
import com.ho.business.entity.*;
import com.ho.business.mapper.DeviceMapper;
import com.ho.business.mapper.DeviceTypeMapper;
import com.ho.business.mapper.VirtualDeviceColMapper;
import com.ho.business.service.*;
import com.ho.business.vo.DeviceTransfer;
import com.ho.business.vo.req.DeviceReqVO;
import com.ho.business.vo.req.EventColReq;
import com.ho.business.vo.req.OperatingStatistic;
import com.ho.business.vo.req.StationReq;
import com.ho.business.vo.req.device.*;
import com.ho.business.vo.req.deviceModel.SynchronousReqVo;
import com.ho.business.vo.req.export.ExportReq;
import com.ho.business.vo.req.point.HisPointReqVo;
import com.ho.business.vo.req.point.PointCurveReq;
import com.ho.business.vo.resp.DeviceRespVO;
import com.ho.business.vo.resp.VirtualDeviceColResp;
import com.ho.business.vo.resp.cabin.TemperatureVoltage;
import com.ho.business.vo.resp.cabin.TemperatureVoltageResp;
import com.ho.business.vo.resp.chargepile.ChargePileRespVO;
import com.ho.business.vo.resp.importVo.DeviceExport;
import com.ho.business.vo.resp.importVo.DeviceTypeConfigExport;
import com.ho.business.vo.resp.importVo.StationExport;
import com.ho.business.vo.resp.point.BeforeSendOrderResp;
import com.ho.business.vo.resp.point.DevicePointResp;
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.entity.HisPointCurveReqVo;
import com.ho.common.tools.entity.PointCurveSrcCol;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.*;
import com.ho.datacollect.api.constant.DataCollectConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yule
 * @description 针对表【device】的数据库操作Service实现
 * @createDate 2022-08-25 16:11:14
 */
@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    DeviceMapper deviceMapper;

    @Autowired
    StationService stationService;

    @Autowired
    DeviceTypeMapper deviceTypeMapper;

    @Autowired
    DeviceTypeConfigService deviceTypeConfigService;

    @Autowired
    VirtualDeviceColService virtualDeviceColService;

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @Autowired
    RedisService redisService;

    @Autowired
    VirtualDeviceColMapper virtualDeviceColMapper;

    @Autowired
    ModelDeviceService modelDeviceService;

    @Autowired
    HisCurveRelateService hisCurveRelateService;

    @Autowired
    TabSortWebService tabSortWebService;

    @Autowired
    Snowflake snowflake;

    @Autowired
    DynamicConfigService dynamicConfigService;


    @Override
    public PageResult<DeviceRespVO> getPageListByInfo(DeviceReqVO deviceReqVO) {
        //是否是多个电站
        Map<Integer, String> stationMap = new HashMap<>();
        if (deviceReqVO.getStationIds() != null && !deviceReqVO.getStationIds().isEmpty()) {
            for (Integer stationId : deviceReqVO.getStationIds()) {
                Station station = stationService.selectById(stationId);

                stationMap.put(stationId, station.getName());
            }
        }
        //原来的
        /*Station station = stationService.selectById(deviceReqVO.getStationId());
        if (station == null) {
            return PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }*/

        if (deviceReqVO.getStationId() == null && ArrayUtil.isEmpty(deviceReqVO.getStationIds())) {
            return PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }

        //如果入参的电站id不为空
        if (deviceReqVO.getStationId() != null) {
            Station station = stationService.selectById(deviceReqVO.getStationId());
            if (station == null) {
                throw new BusinessException(BaseResponseCode.STATION_YC_NOT_EXISTS);
            }
            stationMap.put(deviceReqVO.getStationId(), station.getName());
        }
        //只查询deviceTypeConfig中定义的设备类型数据
        DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
        deviceTypeQuery.setGroupId(deviceReqVO.getGroupId());
        List<DeviceTypeConfig> deviceTypeConfigs = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
        //按deviceType为key转为map
        Map<String, String> deviceTypeMap = deviceTypeConfigs.stream().collect(Collectors.toMap(DeviceTypeConfig::getDeviceType, DeviceTypeConfig::getName, (k1, k2) -> k2));
        List<String> deviceTypeList = new ArrayList<>();
        for (DeviceTypeConfig deviceTypeConfig : deviceTypeConfigs) {
            deviceTypeList.add(deviceTypeConfig.getDeviceType());
        }
        //构造查询条件
        Device deviceQuery = new Device();
        //只查要显示的设备
        BeanUtil.copyProperties(deviceReqVO, deviceQuery);
        //deviceQuery.setHide(0);
        deviceQuery.setNeedFilter(CommonConstant.ONE);
        //因为有多个stationId了,所以不需要groupId和deptId了
        //deviceQuery.setGroupId(station.getGroupId());
        //deviceQuery.setDeptId(station.getDeptId());
        PageHelper.startPage(deviceReqVO.getPageNum(), deviceReqVO.getPageSize());
        //deviceTypeList 不限制值
        //List<DeviceRespVO> deviceList = deviceMapper.selectByInfo(deviceTypeList, deviceQuery, deviceReqVO.getStationIds());
        List<DeviceRespVO> deviceList = deviceMapper.selectByInfo(null, deviceQuery, deviceReqVO.getStationIds());
//        deviceList = getDevice(deviceList);
        Map<Integer, Boolean> deviceIsOnline = new HashMap<>();
        boolean isOnlie = false;
        if (!deviceList.isEmpty()) {
            Map<Integer, List<DeviceRespVO>> dataMap = deviceList.stream().collect(Collectors.groupingBy(DeviceRespVO::getSrcId));
            DeviceRespVO checkDevice = null;
            for (DeviceRespVO device : deviceList) {
                //根据缓存中设备上送数据更新时间判断设备是否在线
//                String deviceKey = device.getDeviceType() + ":" + device.getStationId() + ":" + device.getSrcId();
//                if (redisService.hasKey(deviceKey)) {
//                    Map<Object, Object> hgetall = redisService.hgetall(deviceKey);
//                    Date updateTime = (Date) hgetall.get(CommonConstant.UPDATE_TIME);
//                    Date date = new Date();
//                    long between = DateUtil.between(updateTime, date, DateUnit.MINUTE);
//                    if (between >= 5) {
//                        device.setStatus(CommonConstant.TWO);
//                    }
//                } else {
//                    device.setStatus(CommonConstant.TWO);
//                }
                //若是虚拟设备
                checkDevice = device;
                if (CommonConstant.ONE.equals(device.getVirtual())) {
                    List<DeviceRespVO> deviceRespVOList = dataMap.get(device.getFromId());
                    if (null != deviceRespVOList && deviceRespVOList.size() > 0) {
                        checkDevice = deviceRespVOList.get(0);
                    }
                }
                Boolean online = deviceIsOnline.get(checkDevice.getSrcId());
                if (null == online) {
                    isOnlie = isOnLine(checkDevice);
                    if (!isOnlie) {
                        device.setStatus(CommonConstant.TWO);
                    }
                    deviceIsOnline.put(device.getSrcId(), isOnlie);
                } else {
                    if (!online) {
                        device.setStatus(CommonConstant.TWO);
                    }
                }

                //device.setStationName(station.getName());
                device.setStationName(stationMap.get(device.getStationId()));
                //查询设备类型 ,改为直接从device表中拿到
                //String deviceType = topologyService.findDeviceType(device.getStationId(), device.getSrcId());
                String deviceType = device.getDeviceType();
                if (deviceType != null) {
//                    String deviceTypeName = DeviceTypeConstant.getDeviceName(deviceType);
                    String deviceTypeName = deviceTypeMap.get(deviceType);
                    device.setDeviceType(deviceType);
                    device.setDeviceTypeName(deviceTypeName);
                    device.setStationName(stationMap.get(device.getStationId()));
                    String pileName = DeviceTypeConstant.judgeChargePile(deviceType);
                    //所有设备都可以编辑
                    //device.setEditable(1);
                    /*if (pileName.equals(DeviceTypeConstant.CHARGE_PILE)) {
                        device.setEditable(1);
                    } else {
                        device.setEditable(0);
                    }*/
                }
                device.setHide(device.getHide());
            }
        }
        return PageUtils.getPageResult(new PageInfo<>(deviceList));
    }

    @Override
    public List<DeviceRespVO> getListByDeviceType(DeviceReqVO deviceReqVO) {
        List<DeviceRespVO> deviceList = getList(deviceReqVO);
        return deviceList;
    }

    /**
     * 根据device去获取deviceType中的数字，并形成deviceType为key,name为value的map
     *
     * @param deviceList
     * @return
     */
    private Map<String, String> getDeviceTypeNameMap(List<DeviceRespVO> deviceList) {
        Map<String, String> deviceTypeNameMap = new HashMap<>();
        if (deviceList.isEmpty()) {
            return deviceTypeNameMap;
        }
        List<String> dtList = new ArrayList<>();
        for (DeviceRespVO de : deviceList) {
            dtList.add(de.getDeviceType());
        }
        List<DeviceType> deviceTypes = deviceTypeMapper.selectName(dtList);
        deviceTypeNameMap = deviceTypes.stream().collect(Collectors.toMap(DeviceType::getDeviceType, DeviceType::getName));
        return deviceTypeNameMap;
    }

    @Override
    public List<DeviceRespVO> getListByInfo(List<String> deviceTypeList, DeviceReqVO deviceReqVO) {
        //是否是多个电站
        Map<Integer, String> stationMap = new HashMap<>();
        if (deviceReqVO.getStationIds() != null && !deviceReqVO.getStationIds().isEmpty()) {
            for (Integer stationId : deviceReqVO.getStationIds()) {
                Station station = stationService.selectById(stationId);
                stationMap.put(stationId, station.getName());
            }
        }
        //原来的
        /*Station station = stationService.selectById(deviceReqVO.getStationId());
        if (station == null) {
            return PageUtils.getPageResult(new PageInfo<>(new ArrayList<>()));
        }*/

        if (deviceReqVO.getStationId() == null && ArrayUtil.isEmpty(deviceReqVO.getStationIds())) {
            return new ArrayList<>();
        }
        //构造查询条件
        Device deviceQuery = new Device();
        BeanUtil.copyProperties(deviceReqVO, deviceQuery);
        //因为有多个stationId了,所以不需要groupId和deptId了
        //deviceQuery.setGroupId(station.getGroupId());
        //deviceQuery.setDeptId(station.getDeptId());
        List<DeviceRespVO> deviceList = deviceMapper.selectByInfo(new ArrayList<>(), deviceQuery, deviceReqVO.getStationIds());
        deviceList = getDeviceRespVOS(deviceList);
        Map<String, String> deviceTypeNameMap = getDeviceTypeNameMap(deviceList);
        if (!deviceList.isEmpty()) {
            for (DeviceRespVO device : deviceList) {
                //device.setStationName(station.getName());
                device.setStationName(stationMap.get(device.getStationId()));
                //查询设备类型 ,改为直接从device表中拿到
                //String deviceType = topologyService.findDeviceType(device.getStationId(), device.getSrcId());
                String deviceType = device.getDeviceType();
                if (deviceType != null) {
//                    String deviceTypeName = DeviceTypeConstant.getDeviceName(deviceType);
                    String deviceTypeName = deviceTypeNameMap.get(deviceType);
                    device.setDeviceType(deviceType);
                    device.setDeviceTypeName(deviceTypeName);
                    device.setStationName(stationMap.get(device.getStationId()));
                    String pileName = DeviceTypeConstant.judgeChargePile(deviceType);
                    if (pileName.equals(DeviceTypeConstant.CHARGE_PILE)) {
                        device.setEditable(1);
                    } else {
                        device.setEditable(0);
                    }
                }

            }
        }
        return deviceList;
    }

    @Override
    public List<DeviceRespVO> getList(DeviceReqVO deviceReqVO) {
        List<DeviceRespVO> deviceList = deviceMapper.selectByCondition(deviceReqVO);
        return deviceList;
    }

    @Override
    public List<DeviceRespVO> getListByDeviceType(Integer stationId, String deviceType) {
        List<String> deviceTypes = new ArrayList<>();
        deviceTypes.add(deviceType);
        deviceTypes.add(deviceType + "_" + stationId);
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setNeedFilter(CommonConstant.ONE);
        deviceReqVO.setDeviceTypeList(deviceTypes);
        List<DeviceRespVO> pcsDeviceList = getList(deviceReqVO);
        return pcsDeviceList;
    }

    @Override
    public List<DeviceRespVO> getListByIdsAndDeviceType(List<Integer> stationIds, String deviceType) {
        List<String> deviceTypes = new ArrayList<>();
        List<DeviceRespVO> list = new ArrayList<>();
        for (Integer stationId : stationIds) {
            deviceTypes.add(deviceType);
            deviceTypes.add(deviceType + "_" + stationId);
            DeviceReqVO deviceReqVO = new DeviceReqVO();
            deviceReqVO.setStationId(stationId);
            deviceReqVO.setNeedFilter(CommonConstant.ONE);
            deviceReqVO.setDeviceTypeList(deviceTypes);
            list = getList(deviceReqVO);
        }

        List<DeviceRespVO> pcsDeviceList = new ArrayList<>();
        pcsDeviceList.addAll(list);
        return pcsDeviceList;
    }

    @Override
    public List<DeviceRespVO> getListByFuzzyDeviceType(Integer stationId, String deviceType) {
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setNeedFilter(CommonConstant.ONE);
        deviceReqVO.setFuzzyDeviceType("#" + deviceType);
        List<DeviceRespVO> pcsDeviceList = getList(deviceReqVO);
        return pcsDeviceList;
    }

    @Override
    public List<DeviceRespVO> getListByDeviceTypeAndPid(Integer stationId, Integer pid, String deviceType) {
        List<String> deviceTypes = new ArrayList<>();
        deviceTypes.add(deviceType);
        deviceTypes.add(deviceType + "_" + stationId);
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        //父设备
        deviceReqVO.setPId(pid);
        deviceReqVO.setNeedFilter(CommonConstant.ONE);
        deviceReqVO.setDeviceTypeList(deviceTypes);
        List<DeviceRespVO> pcsDeviceList = getList(deviceReqVO);
        return pcsDeviceList;
    }


    @Override
    public int insertSelective(Device device) {
        int i = deviceMapper.insertSelective(device);
        return i;
    }

    @Override
    public int insertBatch(DeviceAddReq adddevice) {
        Integer newSrcId;
        List<Integer> newSrcIdList = new ArrayList<>();
        List<Device> deviceList = new ArrayList<>();
        if (adddevice.getSrcId() >= CommonConstant.ZERO) {
            //请输入正确的起始设备Id
            throw new BusinessException(BaseResponseCode.PLEASE_ENTER_CORRECT_STARTING_DEVICE_ID);
        }
        if (adddevice.getNum() > CommonConstant.ZERO) {
            for (Integer i = 0; i < adddevice.getNum(); i++) {
                Device device = new Device();
                newSrcId = adddevice.getSrcId() - i;
                String dName = adddevice.getDeviceName() + (i + 1);
                newSrcIdList.add(newSrcId);
                device.setDeviceName(dName);
                TranslateName translate = dynamicConfigService.getNameLanguage(dName);
                device.setDeviceNameEn(translate.getNameEn());
                device.setDeviceNameDe(translate.getNameDe());
                device.setDeviceNamePl(translate.getNamePl());
                device.setDeviceNameAra(translate.getNameAra());
                device.setDeviceNameFra(translate.getNameFra());
                device.setDeviceNameSpa(translate.getNameSpa());
                device.setSrcId(newSrcId);
                device.setDeptId(adddevice.getDeptId());
                device.setDeviceType(adddevice.getDeviceType());
                device.setFromId(adddevice.getFromId());
                device.setGroupId(adddevice.getGroupId());
                device.setHide(adddevice.getHide());
                device.setPid(adddevice.getPid());
                device.setSerialNo(adddevice.getSerialNo());
                device.setVirtual(adddevice.getVirtual());
                device.setStationId(adddevice.getStationId());
                device.setCreateTime(new Date());
                device.setCategory(CommonConstant.THREE);
                device.setStatus(CommonConstant.THREE);
                deviceList.add(device);
            }
        } else {
            //请输入虚拟设备个数
            throw new BusinessException(BaseResponseCode.PLEASE_ENTER_NUMBER_OF_VIRTUAL_DEVICES);
        }
        //入库之前先判断 srcId是否存在重复数据
        List<DeviceRespVO> devices = deviceMapper.selectByStationIdAndSrcIds(adddevice.getStationId(), newSrcIdList);
        if (!devices.isEmpty()) {
            //数据存在相同的设备id
            throw new BusinessException(BaseResponseCode.DATA_THE_SAME_DEVICE_ID);
        }
        int i = deviceMapper.insertBatch(deviceList);
        return i;
    }


    @Override
    public int updateDevice(Device device) {
     /*   @ApiModelProperty(value = "更新时间")
        private Date updateTime;*/
        int i = deviceMapper.updateByPrimaryKeySelective(device);
        return i;
    }

    @Override
    public int update(Device device) {
        device.setUpdateTime(new Date());
        int i = deviceMapper.updateByPrimaryKeySelective(device);
        if(CommonConstant.ZERO.equals(device.getVirtual())){
            String key = RedisKeyConstant.DEVICE_PUSH + device.getGroupId()+":"+device.getStationId();
            Map<Integer, DeviceRespVO> hgetall = (Map<Integer, DeviceRespVO>)redisService.get(key);
            if(hgetall==null){
                hgetall = new HashMap<>();
            }
            DeviceRespVO deviceRespVO = (DeviceRespVO)hgetall.get(device.getSrcId());
            if(deviceRespVO!=null){
                deviceRespVO.setDeviceType(device.getDeviceType());
            }else{
                deviceRespVO = new DeviceRespVO();
                BeanUtils.copyProperties(device,deviceRespVO);
            }
            hgetall.put(device.getSrcId(),deviceRespVO);
            redisService.set(key,hgetall);
            redisService.expire(key, RandomUtil.getRandomInt(), TimeUnit.MINUTES);
        }

        return i;
    }

    @Override
    public void deleteById(Integer id) {
        deviceMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateChargePile(Device device) {
        int i = deviceMapper.updateByPrimaryKeySelective(device);
        return i;
    }

    @Override
    public Device selectById(Integer id) {
        Device device = deviceMapper.selectByPrimaryKey(id);
        return device;
    }

    @Override
    public List<ChargePileRespVO> selectBySrcIds(Integer stationId, List<Integer> srcIds) {
        List<ChargePileRespVO> devices = deviceMapper.selectBySrcIds(stationId, srcIds);
        return devices;
    }

    @Override
    public DeviceRespVO getDeviceRespVO(Integer id) {
        Device device = deviceMapper.selectByPrimaryKey(id);

        DeviceRespVO deviceRespVO = new DeviceRespVO();
        Station station = stationService.selectById(device.getStationId());
        deviceRespVO.setStationName(station.getName());
        //查询设备类型
//        String deviceType = topologyService.findDeviceType(device.getStationId(), device.getSrcId());
        DeviceTypeConfig deviceTypeConfig = deviceTypeConfigService.selectByDeviceType(device.getDeviceType(), device.getGroupId());
        if (deviceTypeConfig != null) {
//            String deviceTypeName = DeviceTypeConstant.getDeviceName(deviceType);
            deviceRespVO.setDeviceType(deviceTypeConfig.getDeviceType());
            deviceRespVO.setDeviceTypeName(deviceTypeConfig.getName());
            String pileName = DeviceTypeConstant.judgeChargePile(device.getDeviceType());
            if (pileName.equals(DeviceTypeConstant.CHARGE_PILE)) {
                deviceRespVO.setEditable(1);
            } else {
                deviceRespVO.setEditable(0);
            }
        }

        return deviceRespVO;
    }

    //启用设备缓存
    @Override
//    @Cacheable(value = "device", sync = true)
    public Device selectByStationIdAndSrcId(Integer stationId, Integer srcId) {
        Device device = new Device();
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setSrcId(srcId);
        List<DeviceRespVO> deviceRespVOList = getList(deviceReqVO);
        if(deviceRespVOList!=null && !deviceRespVOList.isEmpty()){
            device = deviceRespVOList.get(0);
        }
        return device;
    }

    @Override
//    @Cacheable(value = "device", sync = true)
    public Device selectByStationIdAndSrcIdAndLng(Integer stationId, Integer srcId,String lang) {
        Device device = new Device();
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setSrcId(srcId);
        deviceReqVO.setLang(lang);
        List<DeviceRespVO> deviceRespVOList = getList(deviceReqVO);
        if(deviceRespVOList!=null && !deviceRespVOList.isEmpty()){
            device = deviceRespVOList.get(0);
        }
        return device;
    }

    @Override
    public List<DeviceRespVO> selectByGroup(Integer groupId) {
        Device device = new Device();
        device.setGroupId(groupId);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByInfo(null, device, null);
        return deviceRespVOS;
    }

    @Override
    public List<String> selectDistinctDeviceTypeByStationId(Integer stationId) {
        List<String> deviceTypeList = deviceMapper.selectDistinctDeviceTypeByStationId(stationId);
        return deviceTypeList;
    }

    @Override
    public List<DeviceRespVO> getDeviceByStationId(Integer stationId,String lang) {
        DeviceReqVO reqVO = new DeviceReqVO();
        reqVO.setStationId(stationId);
        reqVO.setLang(lang);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(reqVO);
        deviceRespVOS = getDeviceRespVOS(deviceRespVOS);
        return deviceRespVOS;
    }

    /**
     * 排除掉电站,间隔
     *
     * @param deviceRespVOS
     * @return
     */
    private List<DeviceRespVO> getDeviceRespVOS(List<DeviceRespVO> deviceRespVOS) {
        //排除掉电站,间隔
        deviceRespVOS = deviceRespVOS.stream().filter(s -> {
                    Integer category = s.getCategory();
                    if (category != null) {
                        return category > CommonConstant.TWO;
                    } else {
                        return false;
                    }
                }
        ).collect(Collectors.toList());
        return deviceRespVOS;
    }

    @Override
    public List<DeviceRespVO> getDeviceByStationIds(List<Integer> stationIds) {
        DeviceReqVO reqVO = new DeviceReqVO();
        reqVO.setStationIds(stationIds);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(reqVO);
        return deviceRespVOS;
    }

    @Override
    public List<DeviceRespVO> selectByIds(List<Integer> deviceIds) {
        DeviceReqVO reqVO = new DeviceReqVO();
        reqVO.setDeviceIds(deviceIds);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(reqVO);
        return deviceRespVOS;
    }

    @Override
    public List<DeviceRespVO> selectByStation(Integer stationId) {
        DeviceReqVO reqVO = new DeviceReqVO();
        reqVO.setStationId(stationId);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(reqVO);
        return deviceRespVOS;
    }

    /**
     * 根据电站id和设备的pid查询设备
     *
     * @param stationId 电站id
     * @param pId       设备的父id
     * @return
     */
    @Override
    public List<DeviceRespVO> selectByStationIdAndPId(Integer stationId, Integer pId) {
        DeviceReqVO reqVO = new DeviceReqVO();
        reqVO.setStationId(stationId);
        reqVO.setPId(pId);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(reqVO);
        return deviceRespVOS;
    }


    @Value("${station.timeDifference}")
    Integer minute;

    /**
     * 判断设备是否在线
     *
     * @param device 设备
     * @return
     */
    @Override
    public boolean isOnLine(Device device) {
//        boolean flag = false;
//        //拼接设备的缓存key
//        String deviceRedisKey = device.getDeviceType() + ":" + device.getStationId() + ":" + device.getSrcId();
//        //判断设备缓存是否存在
//        if (redisService.hasKey(deviceRedisKey)) {
//            Map<Object, Object> map = redisService.hgetall(deviceRedisKey);
//            Object comm = map.get(DataCollectConstant.COMMUNICATION_STATUS);
//            Integer communicationStatus = null;
//            if(comm instanceof Integer){
//                communicationStatus = (Integer) comm;
//            }else if(comm instanceof DeviceTransfer){
//                DeviceTransfer deviceTransfer = (DeviceTransfer)map.get(DataCollectConstant.COMMUNICATION_STATUS);
//                communicationStatus = deviceTransfer.getValue().intValue();
//            }
//
//            //如果/状态为1或者不存在这个字段,查接入点的状态
//            if (communicationStatus == null || CommonConstant.ONE.equals(communicationStatus)) {
//                //拼接接入点的缓存key
//                String accesspointRedisKey = RedisKeyConstant.HEARTBEAT + device.getSerialNo();
//                //判断接入点缓存是否存在
//                if (redisService.hasKey(accesspointRedisKey)) {
//                    //
//                    Map<Object, Object> accesspointMap = redisService.hgetall(accesspointRedisKey);
//                    Date updateTime = (Date) accesspointMap.get(DataCollectConstant.UPDATE_TIME);
//                    if (updateTime != null) {
//                        long between = DateUtil.between(updateTime, new Date(), DateUnit.MINUTE);
//                        //如果时间差值为5 ,则设备的离线个数+1
//                        if (between < minute) {
//                            flag = true;
//                        }
//                    }
//                }
//            }
//        }
//        return flag;

        /**
         * 先判断心跳，心跳不在  说明云平台和装置断了  所有设备都应该是离线
         * 心跳在，去判断设备的通讯状态，通讯状态故障则离线
         */
        boolean flag = false;
        String accesspointRedisKey = RedisKeyConstant.HEARTBEAT + device.getSerialNo();
        //判断接入点缓存是否存在
        if (redisService.hasKey(accesspointRedisKey)) {
            if (redisService.hasKey(accesspointRedisKey)) {
                Map<Object, Object> accesspointMap = redisService.hgetall(accesspointRedisKey);
                Date updateTime = (Date) accesspointMap.get(DataCollectConstant.UPDATE_TIME);
                if (updateTime != null) {
                    long between = DateUtil.between(updateTime, new Date(), DateUnit.MINUTE);
                    //如果时间差值为5 ,则设备的离线个数+1
                    if (between < minute) {
                        String deviceRedisKey = device.getDeviceType() + ":" + device.getStationId() + ":" + device.getSrcId();
                        if (redisService.hasKey(deviceRedisKey)) {
                            Map<Object, Object> map = redisService.hgetall(deviceRedisKey);
                            Object comm = map.get(DataCollectConstant.COMMUNICATION_STATUS);
                            Integer communicationStatus = null;
                            if (comm instanceof Integer) {
                                communicationStatus = (Integer) comm;
                            } else if (comm instanceof DeviceTransfer) {
                                DeviceTransfer deviceTransfer = (DeviceTransfer) map.get(DataCollectConstant.COMMUNICATION_STATUS);
                                communicationStatus = deviceTransfer.getValue().intValue();
                            }
                            //如果/状态为1或者不存在这个字段,查接入点的状态
                            if (communicationStatus == null || CommonConstant.ONE.equals(communicationStatus)) {
                                flag = true;
                            }
                        }
                    }
                }
            }
        }
        return flag;
    }

    @Override
    public List<DeviceRespVO> getIntervalDevice(DeviceIntervalReqVo vo) {
        DeviceReqVO reqVO = new DeviceReqVO();
        reqVO.setStationId(vo.getStationId());
        reqVO.setPId(vo.getSrcId());
        reqVO.setCategory(vo.getCategory());
        //只查设备
        reqVO.setHide(0);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(reqVO);
        //设备需要过滤设备类型为空的，间隔不需要过滤
        if (CommonConstant.TWO.equals(vo.getCategory())) {
            deviceRespVOS = deviceRespVOS.stream().filter(s -> s.getDeviceType() != null && s.getDeviceType().equals(DeviceTypeConstant.STORAGE)).collect(Collectors.toList());
        }
        return deviceRespVOS;
    }

    @Override
    public List<DeviceRespVO> selectByStationIdAndSrcIds(Map<Integer, List<Integer>> map) {
        List<DeviceRespVO> list = new ArrayList<>();
        //循环查询设备
        map.forEach((k, v) -> {
            List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByStationIdAndSrcIds(k, v);
            list.addAll(deviceRespVOS);
        });
        return list;
    }

    @Override
    public List<Device> selectByStationIdAndSrcIdsVirtual(DeviceListReq deviceListReq) {
        List<Device> list = new ArrayList<>();
        Integer stationId = deviceListReq.getStationId();
        List<Integer> srcIdList = deviceListReq.getSrcIdList();
        //
        List<Integer> srcIds = new ArrayList<>();
        //对设备id进行处理
        if (srcIdList != null && !srcIdList.isEmpty()) {
            Device device = null;
            for (Integer srcId : srcIdList) {
                if (srcId < 0) {
                    device = deviceMapper.selectByStationIdAndSrcId(stationId, srcId);
                    //这个设备的fromId才是真实设备
                    Integer fromId = device.getFromId();
                    device = deviceMapper.selectByStationIdAndSrcId(stationId, fromId);
                    if (device != null) {
                        device.setSrcId(srcId);
                        device.setFromId(fromId);
                        list.add(device);
                    }
                } else {
                    //真实设备
                    device = deviceMapper.selectByStationIdAndSrcId(stationId, srcId);
                    if (device != null) {
                        list.add(device);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<EventColReq> getQueryEventParam(DeviceListReq deviceListReq) {
        Integer stationId = deviceListReq.getStationId();
        List<Integer> srcIdList = deviceListReq.getSrcIdList();
        //真实设备id合集
        List<Integer> realSrcIdList = new ArrayList<>();
        Map<Integer, Integer> realMap = new HashMap();
        //虚拟设备
        List<Integer> virtualSrcIdList = new ArrayList<>();
        for (Integer srcId : srcIdList) {
            if (srcId >= 0) {
                realSrcIdList.add(srcId);
                realMap.put(srcId, srcId);
            } else {
                virtualSrcIdList.add(srcId);
            }
        }
        //存在虚拟设备，需要去查映射表
        Map<Integer, List<String>> map = new LinkedHashMap<>();
        if (virtualSrcIdList.size() > 0) {
            DeviceReqVO deviceReqVO = new DeviceReqVO();
            deviceReqVO.setStationId(stationId);
            deviceReqVO.setSrcIdList(virtualSrcIdList);
            deviceReqVO.setNoNeedFromId(CommonConstant.ONE);
            deviceReqVO.setFormIdList(realSrcIdList);
            List<DeviceRespVO> deviceRespVOList = deviceMapper.selectByCondition(deviceReqVO);
            //存在输入的虚拟设备不是选择的实体设备下面的设备
            if (null != deviceRespVOList && deviceRespVOList.size() > 0) {
                //最终需要查询的虚拟设备
                List<Integer> list = deviceRespVOList.stream().filter(i -> null != i.getFromId()).map(DeviceRespVO::getSrcId).collect(Collectors.toList());
                VirtualDeviceCol virtualDeviceCol = new VirtualDeviceCol();
                virtualDeviceCol.setStationId(stationId);
                virtualDeviceCol.setSrcIdList(list);
                List<VirtualDeviceColResp> virtualDeviceColResps = virtualDeviceColMapper.selectVirtualDeviceCol(virtualDeviceCol);
                Map<Integer, List<VirtualDeviceColResp>> srcIdVirtualMap = virtualDeviceColResps.stream().collect(Collectors.groupingBy(VirtualDeviceColResp::getSrcId));
                for (DeviceRespVO device : deviceRespVOList) {
                    List<String> str = map.get(device.getFromId());
                    if (str == null) {
                        str = new ArrayList<>();
                    }
                    List<String> colList = srcIdVirtualMap.get(device.getSrcId()).stream().map(VirtualDeviceColResp::getCol).collect(Collectors.toList());
                    str.addAll(colList);
                    map.put(device.getFromId(), str);
                }

            }
        }
        List<EventColReq> eventColReqList = new ArrayList<>();
        if (map.size() > 0) {
            eventColReqList = new ArrayList<>();
            EventColReq eventColReq = null;
            for (Map.Entry<Integer, List<String>> m : map.entrySet()) {
                eventColReq = new EventColReq();
                eventColReq.setSrcId(m.getKey());
                eventColReq.setColList(m.getValue());
                eventColReqList.add(eventColReq);
            }
            for (Integer srcId : realSrcIdList) {
                eventColReq = new EventColReq();
                eventColReq.setSrcId(srcId);
                eventColReq.setColList(null);
                eventColReqList.add(eventColReq);
            }
        }
        return eventColReqList;
    }

    @Override
    public List<DeviceRespVO> selectByIdAndSrcIdNotZero(Integer stationId,String lang) {
        List<DeviceRespVO> list = deviceMapper.selectByIdAndSrcIdNotZero(stationId, null, null,lang);
        return list;
    }

    @Override
    public List<DeviceRespVO> selectDeviceByStationId(Integer stationId,String lang) {
        List<DeviceRespVO> list = deviceMapper.selectByIdAndSrcIdNotZero(stationId, null, CommonConstant.ONE,lang);
        return list;
    }

    @Override
    public List<DeviceRespVO> selectAllDeviceAndSrcIdNotZero(Integer stationId,String lang) {
        List<DeviceRespVO> list = deviceMapper.selectByIdAndSrcIdNotZero(stationId, CommonConstant.ONE, null,lang);
        return list;
    }

    @Override
    public TemperatureVoltageResp getTemperatureVoltageData(DeviceTreeReq vo) {
        List<DeviceRespVO> deviceRespVOS = selectByIdAndSrcIdNotZero(vo.getStationId(),vo.getLang());
        List<DevicePointResp> treeDevices = new ArrayList<>();
        if (!deviceRespVOS.isEmpty()) {
            treeDevices = deviceTypeConfigService.getTreeDevices(deviceRespVOS, vo.getSrcId());
        }
        TemperatureVoltageResp temperatureVoltageResp = getTemperatureVoltageResp(vo, treeDevices);
        return temperatureVoltageResp;
    }

    @NotNull
    private TemperatureVoltageResp getTemperatureVoltageResp(DeviceTreeReq vo, List<DevicePointResp> treeDevices) {
        //查询当前设备下所以电池包的srcId合集
        Map<Integer, Integer> srcIds = new HashMap<>();
        getAllSrcId(srcIds, treeDevices);
        //关联关系表
        VirtualDeviceCol virtualDeviceCol = new VirtualDeviceCol();
        virtualDeviceCol.setStationId(vo.getStationId());
        List<VirtualDeviceColResp> virtualList = virtualDeviceColService.getList(virtualDeviceCol);
        //筛选关联关系中属于电池包的设备id
        List<VirtualDeviceColResp> packList = virtualList.stream().filter(i -> srcIds.get(i.getSrcId()) != null).collect(Collectors.toList());
        //Map<Integer, VirtualDeviceColResp> colIdMap = packList.stream().collect(Collectors.toMap(VirtualDeviceColResp::getDeviceColId, VirtualDeviceColResp -> VirtualDeviceColResp));

        TemperatureVoltageResp temperatureVoltageResp = new TemperatureVoltageResp();
        if (srcIds.size() > 0) {
            Map.Entry<Integer, Integer> entry = srcIds.entrySet().iterator().next();
            //获取真实设备srcId
            Integer srcId = entry.getValue();
            Device device = selectByStationIdAndSrcId(vo.getStationId(), srcId);
            //取设备类型
            String deviceType = device.getDeviceType();
            //取缓存
            String redisKey = deviceType + ":" + vo.getStationId() + ":" + srcId;
            //电压合集
            List<DeviceTransfer> vList = new ArrayList<>();
            //温度合集
            List<DeviceTransfer> tList = new ArrayList<>();
            if (redisService.hasKey(redisKey)) {
                Map<Object, Object> hgetall = redisService.hgetall(redisKey);
                for (VirtualDeviceColResp col : packList) {
                    DeviceTransfer deviceTransfer = (DeviceTransfer) hgetall.get(col.getCol());
                    if (null != deviceTransfer) {
                        if (col.getType().contains(DeviceTypeConstant.VOLTAGE)) {
                            vList.add(deviceTransfer);
                        } else if (col.getType().contains(DeviceTypeConstant.TEMPERATURE)) {
                            tList.add(deviceTransfer);
                        }
                    }
                }
                int vLen = vList.size();
                int tLen = tList.size();
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                DecimalFormat decimalFormatThree = new DecimalFormat("#.000");
                Map<BigDecimal, List<DeviceTransfer>> tMap = tList.stream().collect(Collectors.groupingBy(DeviceTransfer::getValue));
                List<TemperatureVoltage> temperatureList = new ArrayList<>();
                tMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> {
                    TemperatureVoltage temperatureVoltage = new TemperatureVoltage();
                    temperatureVoltage.setXValue(NumberUtil.round(x.getKey(),3));
                    temperatureVoltage.setYValue(x.getValue().size());
                    //temperatureVoltage.setPercentageValue(Math.round(x.getValue().size()*10000f/tLen)/100f);
                    temperatureVoltage.setPercentageValue(Float.valueOf(decimalFormat.format(x.getValue().size() * 100f / tLen)));
                    temperatureList.add(temperatureVoltage);
                });

                Map<BigDecimal, List<DeviceTransfer>> vMap = vList.stream().collect(Collectors.groupingBy(DeviceTransfer::getValue));
                List<TemperatureVoltage> voltageTempList = new ArrayList<>();
                vMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(x -> {
                    TemperatureVoltage temperatureVoltage = new TemperatureVoltage();
                    temperatureVoltage.setXValue(x.getKey());
                    temperatureVoltage.setYValue(x.getValue().size());
                    voltageTempList.add(temperatureVoltage);
                });
                //计算电压X轴值
                int len = voltageTempList.size();
                List<TemperatureVoltage> voltageList = new ArrayList<>();
                if (len > 10) {
                    TemperatureVoltage minV = voltageTempList.get(0);
                    TemperatureVoltage maxV = voltageTempList.get(len - 1);
                    BigDecimal diff = BigDecimal.valueOf((maxV.getXValue().doubleValue() - minV.getXValue().doubleValue()) / 9);
                    TemperatureVoltage temperatureVoltage = null;
                    for (int i = 0; i < 10; i++) {
                        temperatureVoltage = new TemperatureVoltage();
                        temperatureVoltage.setXValue(BigDecimal.valueOf(Double.parseDouble(decimalFormatThree.format(minV.getXValue().add(diff.multiply(new BigDecimal(i)))))));
                        if (i == 9) {
                            temperatureVoltage.setXValue(maxV.getXValue());
                        }
                        temperatureVoltage.setYValue(CommonConstant.ZERO);
                        voltageList.add(temperatureVoltage);
                    }
                    int num = 0;
                    BigDecimal minValue;
                    BigDecimal maxValue;
                    int volLen = voltageList.size();
                    for (int i = 0; i < volLen-1; i++) {
                        for (int j = num; j < len; j++) {
                            minValue = voltageList.get(i).getXValue();
                            maxValue = voltageList.get(i + 1).getXValue();
                            TemperatureVoltage temp = voltageTempList.get(j);
                            if (temp.getXValue().compareTo(minValue) >= 0 && temp.getXValue().compareTo(maxValue) < 0) {
                                voltageList.get(i).setYValue(voltageList.get(i).getYValue() + temp.getYValue());
                                if(j<=len-2 && voltageTempList.get(j+1).getXValue().compareTo(maxValue) >= 0){
                                    num++;
                                }
                            }else {
                                break;
                            }
                        }
                    }
                    voltageList.get(volLen-1).setYValue(voltageTempList.get(len-1).getYValue());
//                    for (TemperatureVoltage temp : voltageTempList) {
//                        minValue = voltageList.get(num).getXValue();
//                        maxValue = voltageList.get(num + 1).getXValue();
//                        if (!(temp.getXValue().compareTo(minValue) >= 0 && temp.getXValue().compareTo(maxValue) < 0)) {
//                            num++;
//                        }
//                        voltageList.get(num).setYValue(voltageList.get(num).getYValue() + temp.getYValue());
//                    }
                    //换算百分比
                    for (int i = 0; i < 10; i++) {
                        //voltageList.get(i).setPercentageValue(Math.round(voltageList.get(i).getYValue()*10000f/vLen)/100f);
                        voltageList.get(i).setPercentageValue(Float.valueOf(decimalFormat.format(voltageList.get(i).getYValue() * 100f / vLen)));
                    }
                } else {
                    voltageList = voltageTempList;
                    for (int i = 0; i < len; i++) {
                        //voltageList.get(i).setPercentageValue(Math.round(voltageList.get(i).getYValue()*10000f/vLen)/100f);
                        voltageList.get(i).setXValue(NumberUtil.round(voltageList.get(i).getXValue(), 3));
                        voltageList.get(i).setPercentageValue(Float.valueOf(decimalFormat.format(voltageList.get(i).getYValue() * 100f / vLen)));
                    }
                }
                temperatureVoltageResp.setTemperatureList(temperatureList);
                temperatureVoltageResp.setVoltageList(voltageList);
            } else {
                temperatureVoltageResp.setTemperatureList(new ArrayList<>());
                temperatureVoltageResp.setVoltageList(new ArrayList<>());
            }
        }
        return temperatureVoltageResp;
    }

    @Override
    public BeforeSendOrderResp beforeOrderSend(StationReq stationReq) {
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationReq.getStationId());
        deviceReqVO.setNeedFilter(CommonConstant.ONE);
        deviceReqVO.setHide(CommonConstant.ONE);
        List<DeviceRespVO> deviceRespVOList = getList(deviceReqVO);
        BeforeSendOrderResp beforeSendOrderResp = null;
        DeviceTypeCol deviceTypeCol = null;
        for (DeviceRespVO device : deviceRespVOList) {
            if (device.getDeviceType() != null) {
                deviceTypeCol = new DeviceTypeCol();
                deviceTypeCol.setDeviceType(device.getDeviceType());
                Integer count = deviceTypeColService.selectCountByDeviceType(deviceTypeCol);
                if (count > 0) {
                    beforeSendOrderResp = new BeforeSendOrderResp();
                    beforeSendOrderResp.setSrcId(device.getSrcId());
                    break;
                }
            }
        }
        return beforeSendOrderResp;
    }

    private Map<Integer, Integer> getAllSrcId(Map<Integer, Integer> srcIds, List<DevicePointResp> treeDevices) {
        if (treeDevices != null) {
            for (DevicePointResp resp : treeDevices) {
                if (resp.getDeviceType() != null && resp.getDeviceType().contains(DeviceTypeConstant.PACK)) {
                    srcIds.put(resp.getSrcId(), resp.getFromId());
                }
                getAllSrcId(srcIds, resp.getChildren());
            }
        }
        return srcIds;
    }

    @Override
    public List<Device> getRealDevice(Device device) {
        return deviceMapper.selectRealDevice(device);
    }

    @Override
    public void getSynchronousVD(SynchronousReqVo vo) {
        Device value = new Device();
        value.setStationId(vo.getModelStationId());
        value.setVirtual(CommonConstant.ONE);
        List<Device> devices = deviceMapper.selectRealDevice(value);
        List<Device> list = new ArrayList<>();
        if (!devices.isEmpty()) {
            for (Device device : devices) {
                Device deviceValue = new Device();
                deviceValue.setVirtual(device.getVirtual());
                deviceValue.setGroupId(device.getGroupId());
                deviceValue.setSrcId(device.getSrcId());
                deviceValue.setPid(device.getPid());
                deviceValue.setCategory(device.getCategory());
                deviceValue.setStationId(vo.getStationId());
                deviceValue.setDeviceName(device.getDeviceName());
                deviceValue.setDeviceNameEn(device.getDeviceNameEn());
                deviceValue.setDeviceNameFra(device.getDeviceNameFra());
                deviceValue.setDeviceNameSpa(device.getDeviceNameSpa());
                deviceValue.setDeviceNameDe(device.getDeviceNameDe());
                deviceValue.setDeviceNamePl(device.getDeviceNamePl());
                deviceValue.setDeviceNameAra(device.getDeviceNameAra());
                deviceValue.setStatus(device.getStatus());
                deviceValue.setCreateTime(new Date());
                deviceValue.setFromId(device.getFromId());
                deviceValue.setHide(device.getHide());
                if (device.getDeviceType() != null) {
                    String deviceType = device.getDeviceType();
                    int index = deviceType.indexOf("_");
                    deviceValue.setDeviceType(deviceType.substring(0, index + 1) + vo.getStationId());
                }

                list.add(deviceValue);
            }
            //先判断是否有重复数据，防止二次入库
            value.setStationId(vo.getStationId());
            value.setVirtual(CommonConstant.ONE);
            List<Device> devicesList = deviceMapper.selectRealDevice(value);
            if (!devicesList.isEmpty()) {
                //如果存在，全部删掉
                List<Integer> ids = devicesList.stream().map(Device::getId).collect(Collectors.toList());
                deviceMapper.deleteByList(ids);
            }
            deviceMapper.insertBatch(list);
        }
    }

    @Override
    public List<DeviceRespVO> selectGroup(List<DeviceRespVO> deviceRespVOS) {
        List<DeviceRespVO> list = new ArrayList<>();
        //过滤掉虚拟设备（virtual =1）
        //过滤不为空
        List<DeviceRespVO> deviceRespVOStream = deviceRespVOS.stream().filter(i -> CommonConstant.ZERO.equals(i.getVirtual()) && i.getDeviceType() != null).collect(Collectors.toList());
        Set<String> collect = deviceRespVOStream.stream().map(DeviceRespVO::getDeviceType).collect(Collectors.toSet());
        if (collect.isEmpty()) {
            return list;
        }
        List<String> deviceTypeList = deviceTypeColService.selectType(collect);
//        Map<String, List<DeviceRespVO>> map = deviceRespVOStream.stream().collect(Collectors.groupingBy(DeviceRespVO::getDeviceType));
//        for (String s : deviceTypeList) {
//            if (map.get(s) != null) {
//                List<DeviceRespVO> value = map.get(s);
//                list.addAll(value);
//            }
//        }
//        for (DeviceRespVO deviceRespVO : deviceRespVOS) {
//            if (CommonConstant.ONE.equals(deviceRespVO.getVirtual()) || !CommonConstant.THREE.equals(deviceRespVO.getCategory())) {
//                list.add(deviceRespVO);
//            }
//        }
        Map<String, String> typeMap = new HashMap<>();
        for (String s : deviceTypeList) {
            typeMap.put(s, s);
        }
        List<DeviceRespVO> needList = deviceRespVOS.stream().filter(deviceRespVO -> CommonConstant.ONE.equals(deviceRespVO.getVirtual()) || !CommonConstant.THREE.equals(deviceRespVO.getCategory()) || typeMap.get(deviceRespVO.getDeviceType()) != null).collect(Collectors.toList());
        Map<Integer, Integer> pidMap = needList.stream().collect(Collectors.toMap(DeviceRespVO::getPid, DeviceRespVO::getPid, (key1, key2) -> {
            return key2;
        }));
        list = needList.stream().filter(deviceRespVO -> !(!CommonConstant.THREE.equals(deviceRespVO.getCategory()) && pidMap.get(deviceRespVO.getSrcId()) == null)).collect(Collectors.toList());
        return list;
    }

    @Override
    public int updateByStationId(Station station) {
        int i = 0;
        if (!station.getSnList().isEmpty()) {
            String sn = station.getSnList().get(0);
            Device device = new Device();
            device.setSerialNo(sn);
            device.setStationId(station.getId());
            device.setUpdateTime(new Date());
            i = deviceMapper.updateByStationId(device);
        }
        return i;
    }

    @Override
    public List<Device> selectBySelect(Device deviceValue) {
        return deviceMapper.selectRealDevice(deviceValue);
    }

    @Override
    public TemperatureVoltageResp getCellVoltageAndTemperature(DeviceTreeReq vo) {
        //设置查询电池组属性
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(vo.getStationId());
        deviceReqVO.setDeviceTypePrefix(CommonConstant.PACK);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(deviceReqVO);
        List<Integer> srcIdList = deviceRespVOS.stream().map(s -> s.getSrcId()).collect(Collectors.toList());
        //查询对应的设备
        List<DeviceRespVO> deviceStation = selectByIdAndSrcIdNotZero(vo.getStationId(),vo.getLang());
        List<DevicePointResp> treeDevices = new ArrayList<>();
        if (!deviceRespVOS.isEmpty()) {
            for (Integer srcId : srcIdList) {
                List<DevicePointResp> devices = deviceTypeConfigService.getTreeDevices(deviceStation, srcId);
                treeDevices.addAll(devices);
            }
        }
        //
        TemperatureVoltageResp temperatureVoltageResp = getTemperatureVoltageResp(vo, treeDevices);
        return temperatureVoltageResp;
    }

    @Override
    public TemperatureVoltageResp getCellVoltageAndTemperatureNum(DeviceTreeReq vo) {
        //设置查询电池组属性
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(vo.getStationId());
        deviceReqVO.setDeviceTypePrefix(CommonConstant.PACK);
        List<DeviceRespVO> deviceRespVOS = deviceMapper.selectByCondition(deviceReqVO);
        List<Integer> srcIdList = deviceRespVOS.stream().map(s -> s.getSrcId()).collect(Collectors.toList());
        //查询对应的设备
        List<DeviceRespVO> deviceStation = selectByIdAndSrcIdNotZero(vo.getStationId(),vo.getLang());
        List<DevicePointResp> treeDevices = new ArrayList<>();
        if (!deviceRespVOS.isEmpty()) {
            for (Integer srcId : srcIdList) {
                List<DevicePointResp> devices = deviceTypeConfigService.getTreeDevices(deviceStation, srcId);
                treeDevices.addAll(devices);
            }
        }
        TemperatureVoltageResp temperatureVoltageResp = getTemperatureVoltageRespNum(vo, treeDevices);
        return temperatureVoltageResp;
    }

    private TemperatureVoltageResp getTemperatureVoltageRespNum(DeviceTreeReq vo, List<DevicePointResp> treeDevices) {
        Map<Integer, Integer> srcIds = new HashMap<>();
        getAllSrcId(srcIds, treeDevices);
        //关联关系表
        VirtualDeviceCol virtualDeviceCol = new VirtualDeviceCol();
        virtualDeviceCol.setStationId(vo.getStationId());
        List<VirtualDeviceColResp> virtualList = virtualDeviceColService.getList(virtualDeviceCol);
        //筛选关联关系中属于电池包的设备id
        List<VirtualDeviceColResp> packList = virtualList.stream().filter(i -> srcIds.get(i.getSrcId()) != null).collect(Collectors.toList());
        //Map<Integer, VirtualDeviceColResp> colIdMap = packList.stream().collect(Collectors.toMap(VirtualDeviceColResp::getDeviceColId, VirtualDeviceColResp -> VirtualDeviceColResp));

        TemperatureVoltageResp temperatureVoltageResp = new TemperatureVoltageResp();
        if (srcIds.size() > 0) {
            Map.Entry<Integer, Integer> entry = srcIds.entrySet().iterator().next();
            //获取真实设备srcId
            Integer srcId = entry.getValue();
            Device device = selectByStationIdAndSrcId(vo.getStationId(), srcId);
            //取设备类型
            String deviceType = device.getDeviceType();
            //取缓存
            String redisKey = deviceType + ":" + vo.getStationId() + ":" + srcId;
            //电压合集
            List<DeviceTransfer> vList = new ArrayList<>();
            //温度合集
            List<DeviceTransfer> tList = new ArrayList<>();
            if (redisService.hasKey(redisKey)) {
                Map<Object, Object> hgetall = redisService.hgetall(redisKey);
                Map<Integer, List<VirtualDeviceColResp>> colMap = packList.stream().collect(Collectors.groupingBy(VirtualDeviceColResp::getSrcId));
                colMap.forEach((k, v) -> {
                    System.out.println();
                    for (VirtualDeviceColResp col : v) {
                        DeviceTransfer deviceTransfer = (DeviceTransfer) hgetall.get(col.getCol());
                        if (null != deviceTransfer) {
                            if (col.getType().contains(DeviceTypeConstant.VOLTAGE)) {
                                vList.add(deviceTransfer);
                            } else if (col.getType().contains(DeviceTypeConstant.TEMPERATURE)) {
                                tList.add(deviceTransfer);
                            }
                        }
                    }
                    int vCount = vList.size();
                    int tCount = tList.size();
                    if (vCount > tCount) {
                        int count = vCount - tCount;
                        for (int i = 0; i < count; i++) {
                            DeviceTransfer deviceTransfer = new DeviceTransfer();
                            deviceTransfer.setValue(null);
                            tCount++;
                            tList.add(deviceTransfer);
                        }
                    } else {
                        int count = tCount - vCount;
                        for (int i = 0; i < count; i++) {
                            DeviceTransfer deviceTransfer = new DeviceTransfer();
                            deviceTransfer.setValue(null);
                            vCount++;
                            vList.add(deviceTransfer);
                        }
                    }
                });
                /*for (VirtualDeviceColResp col : packList) {
                    DeviceTransfer deviceTransfer = (DeviceTransfer) hgetall.get(col.getCol());
                    if (null != deviceTransfer) {
                        if (col.getType().contains(DeviceTypeConstant.VOLTAGE)) {
                            vList.add(deviceTransfer);
                        } else if (col.getType().contains(DeviceTypeConstant.TEMPERATURE)) {
                            tList.add(deviceTransfer);
                        }
                    }
                }*/
                int vNum = 0;
                int tNum = 0;
                List<TemperatureVoltage> voltageList = new ArrayList<>();
                List<TemperatureVoltage> temperatureList = new ArrayList<>();
                for (DeviceTransfer deviceTransfer : vList) {
                    TemperatureVoltage voltage = new TemperatureVoltage();
                    voltage.setXValue(deviceTransfer.getValue());
                    vNum++;
                    voltage.setYValue(vNum);
                    voltageList.add(voltage);
                }
                for (DeviceTransfer deviceTransfer : tList) {
                    TemperatureVoltage temperature = new TemperatureVoltage();
                    temperature.setXValue(deviceTransfer.getValue());
                    tNum++;
                    temperature.setYValue(tNum);
                    temperatureList.add(temperature);
                }

/*                //比较两个集合数量，并补充使其数量一致

                }*/
                temperatureVoltageResp.setTemperatureList(temperatureList);
                temperatureVoltageResp.setVoltageList(voltageList);
            } else {
                temperatureVoltageResp.setTemperatureList(new ArrayList<>());
                temperatureVoltageResp.setVoltageList(new ArrayList<>());
            }
        }
        return temperatureVoltageResp;

    }

    @Override
    public PointCurveReq getDefaultValue(Integer stationId, SimpleUser user) {
        PointCurveReq pointCurveReq = new PointCurveReq();
        pointCurveReq.setStationId(stationId);
        pointCurveReq.setIsOriginal(0);
        //开始时间与结束时间
        String beginTime = DateUtil.format(DateUtil.beginOfDay(new Date()), CommonConstant.DATE);
        String endTime = DateUtil.format(new Date(), CommonConstant.DATE);
        pointCurveReq.setBeginTime(beginTime);
        pointCurveReq.setEndTime(endTime);

        //查询设备点集合
        List<PointCurveSrcCol> deviceIdList = new ArrayList<>();
        List<ModelDeviceColComp> modelDeviceColCompList = new ArrayList<>();
        List<DeviceRespVO> pcsDeviceList = getListByDeviceType(stationId, DeviceTypeConstant.PCS);
        if (pcsDeviceList.isEmpty()) {
            pcsDeviceList = getListByFuzzyDeviceType(stationId, DeviceTypeConstant.PCS);
        }
        for (DeviceRespVO device : pcsDeviceList) {
            List<ModelDeviceColComp> colCompList = modelDeviceService.getCompListByType("device", device.getDeviceType(), "outputPower");
            List<ModelDeviceColComp> colCopyCompList = new ArrayList<>();
            List<PointCurveSrcCol> colList = new ArrayList<>();
            for (ModelDeviceColComp modelDeviceColComp : colCompList) {
                ModelDeviceColComp copy = new ModelDeviceColComp();
                BeanUtil.copyProperties(modelDeviceColComp, copy);
                copy.setSrcId(device.getSrcId());
                colCopyCompList.add(copy);
                PointCurveSrcCol pointCurveSrcCol = new PointCurveSrcCol();
                pointCurveSrcCol.setSrcId(device.getSrcId());
                List<String> cols = new ArrayList<>();
                cols.add(modelDeviceColComp.getDeviceCol());
                pointCurveSrcCol.setCols(cols);
                colList.add(pointCurveSrcCol);
            }
            modelDeviceColCompList.addAll(colCopyCompList);
            deviceIdList.addAll(colList);
        }

        List<DeviceRespVO> bmsDeviceList = getListByDeviceType(stationId, DeviceTypeConstant.BMS);
        if (bmsDeviceList.isEmpty()) {
            bmsDeviceList = getListByFuzzyDeviceType(stationId, DeviceTypeConstant.BMS);
        }
        for (DeviceRespVO device : bmsDeviceList) {
            List<ModelDeviceColComp> colCompList = modelDeviceService.getCompListByType("device", device.getDeviceType(), "soc");
            List<ModelDeviceColComp> colCopyCompList = new ArrayList<>();
            List<PointCurveSrcCol> colList = new ArrayList<>();
            for (ModelDeviceColComp modelDeviceColComp : colCompList) {
                ModelDeviceColComp copy = new ModelDeviceColComp();
                BeanUtil.copyProperties(modelDeviceColComp, copy);
                copy.setSrcId(device.getSrcId());
                colCopyCompList.add(copy);
                PointCurveSrcCol pointCurveSrcCol = new PointCurveSrcCol();
                pointCurveSrcCol.setSrcId(device.getSrcId());
                List<String> cols = new ArrayList<>();
                cols.add(modelDeviceColComp.getDeviceCol());
                pointCurveSrcCol.setCols(cols);
                colList.add(pointCurveSrcCol);
            }
            modelDeviceColCompList.addAll(colCopyCompList);
            deviceIdList.addAll(colList);
        }
        //光伏逆变器
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.INVERTER);
        List<DeviceRespVO> inverterDeviceList = getList(deviceReqVO);
        for (DeviceRespVO device : inverterDeviceList) {
            List<ModelDeviceColComp> colCompList = modelDeviceService.getCompListByType("device", device.getDeviceType(), "acActivePower");
            List<ModelDeviceColComp> colCopyCompList = new ArrayList<>();
            List<PointCurveSrcCol> colList = new ArrayList<>();
            for (ModelDeviceColComp modelDeviceColComp : colCompList) {
                ModelDeviceColComp copy = new ModelDeviceColComp();
                BeanUtil.copyProperties(modelDeviceColComp, copy);
                copy.setSrcId(device.getSrcId());
                colCopyCompList.add(copy);
                PointCurveSrcCol pointCurveSrcCol = new PointCurveSrcCol();
                pointCurveSrcCol.setSrcId(device.getSrcId());
                List<String> cols = new ArrayList<>();
                cols.add(modelDeviceColComp.getDeviceCol());
                pointCurveSrcCol.setCols(cols);
                colList.add(pointCurveSrcCol);
            }
            modelDeviceColCompList.addAll(colCopyCompList);
            deviceIdList.addAll(colList);
        }
        //防逆流
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.AMMETER_FNL);
        List<DeviceRespVO> fnlDeviceList = getList(deviceReqVO);
        for (DeviceRespVO device : fnlDeviceList) {
            List<ModelDeviceColComp> colCompList = modelDeviceService.getCompListByType("device", device.getDeviceType(), "activePower");
            List<ModelDeviceColComp> colCopyCompList = new ArrayList<>();
            List<PointCurveSrcCol> colList = new ArrayList<>();
            for (ModelDeviceColComp modelDeviceColComp : colCompList) {
                ModelDeviceColComp copy = new ModelDeviceColComp();
                BeanUtil.copyProperties(modelDeviceColComp, copy);
                copy.setSrcId(device.getSrcId());
                colCopyCompList.add(copy);
                PointCurveSrcCol pointCurveSrcCol = new PointCurveSrcCol();
                pointCurveSrcCol.setSrcId(device.getSrcId());
                List<String> cols = new ArrayList<>();
                cols.add(modelDeviceColComp.getDeviceCol());
                pointCurveSrcCol.setCols(cols);
                colList.add(pointCurveSrcCol);
            }
            modelDeviceColCompList.addAll(colCopyCompList);
            deviceIdList.addAll(colList);
        }
        pointCurveReq.setDeviceIdList(deviceIdList);
        //判断是否有策略曲线模版,如果没有就添加
        if (!hisCurveRelateService.hasModelName(CommonConstant.STRATEGY_MODEL, stationId, user.getUserId())) {
            //创建模版集合
            List<HisPointCurveReqVo> list = new ArrayList<>();
            for (ModelDeviceColComp modelDeviceColComp : modelDeviceColCompList) {
                HisPointCurveReqVo hisCurveRelate = new HisPointCurveReqVo();
                hisCurveRelate.setCol(modelDeviceColComp.getDeviceCol());
                hisCurveRelate.setDeviceType(modelDeviceColComp.getDeviceType());
                hisCurveRelate.setColName(modelDeviceColComp.getModelColName());
                hisCurveRelate.setStationId(stationId);
                hisCurveRelate.setSrcId(modelDeviceColComp.getSrcId());
                list.add(hisCurveRelate);
            }
            if (CollectionUtils.isNotEmpty(list)) {
                HisPointReqVo hisPointReqVo = new HisPointReqVo();
                hisPointReqVo.setModelName(CommonConstant.STRATEGY_MODEL);
                hisPointReqVo.setList(list);
                hisCurveRelateService.add(hisPointReqVo, user);
            }
        }
        pointCurveReq.setIsStrategy(CommonConstant.ONE);
        return pointCurveReq;
    }

    @Override
    public List<OperatingStatistic> getOperatingStatistic(Integer stationId) {
        List<OperatingStatistic> list = new ArrayList<>();
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.PLAN_CURVE.PALN_CONTROL_DEVICE_TYPE);
        List<DeviceRespVO> deviceList = getList(deviceReqVO);
        if (CollectionUtils.isEmpty(deviceList)) {
            return list;
        }
        DeviceRespVO deviceRespVO = deviceList.get(0);
        String redisKey = new StringBuilder().append(DeviceTypeConstant.PLAN_CURVE.PALN_CONTROL_DEVICE_TYPE)
                .append(stationId).append(":").append(stationId).append(":").append(deviceRespVO.getSrcId()).toString();
        Map<Object, Object> map = redisService.hgetall(redisKey);
        if (map != null) {
            //上月
            Object objTotalCharge = map.get(CommonConstant.Demand.LAST_MONTH_MAX_DEMAND);
            if (objTotalCharge instanceof DeviceTransfer) {
                DeviceTransfer lastMonthMaxDemand = (DeviceTransfer) map.get(CommonConstant.Demand.LAST_MONTH_MAX_DEMAND);
                if (lastMonthMaxDemand != null) {
                    OperatingStatistic operatingStatistic = new OperatingStatistic();
                    operatingStatistic.setName("上月最大需量 ");
                    operatingStatistic.setValue(lastMonthMaxDemand.getValue() + "kW");
                    operatingStatistic.setTime(DateUtil.format(lastMonthMaxDemand.getUpdateTime(), CommonConstant.DATE));
                    list.add(operatingStatistic);
                }
            }
            Object objLastMonthMaxPower = map.get(CommonConstant.Demand.LAST_MONTH_MAX_POWER);
            if (objLastMonthMaxPower instanceof DeviceTransfer) {
                DeviceTransfer lastMonthMaxPower = (DeviceTransfer) map.get(CommonConstant.Demand.LAST_MONTH_MAX_POWER);
                if (lastMonthMaxPower != null) {
                    OperatingStatistic operatingStatistic = new OperatingStatistic();
                    operatingStatistic.setName("上月最大功率 ");
                    operatingStatistic.setValue(lastMonthMaxPower.getValue() + "kW");
                    operatingStatistic.setTime(DateUtil.format(lastMonthMaxPower.getUpdateTime(), CommonConstant.DATE));
                    list.add(operatingStatistic);
                }
            }
            Object objLastMonthMinPower = map.get(CommonConstant.Demand.LAST_MONTH_MIN_POWER);
            if (objLastMonthMinPower instanceof DeviceTransfer) {
                DeviceTransfer lastMonthMinPower = (DeviceTransfer) map.get(CommonConstant.Demand.LAST_MONTH_MIN_POWER);
                if (lastMonthMinPower != null) {
                    OperatingStatistic operatingStatistic = new OperatingStatistic();
                    operatingStatistic.setName("上月最小功率 ");
                    operatingStatistic.setValue(lastMonthMinPower.getValue() + "kW");
                    operatingStatistic.setTime(DateUtil.format(lastMonthMinPower.getUpdateTime(), CommonConstant.DATE));
                    list.add(operatingStatistic);
                }
            }

            //上月
            Object objTheMonthMaxDemand = map.get(CommonConstant.Demand.THE_MONTH_MAX_DEMAND);
            if (objTheMonthMaxDemand instanceof DeviceTransfer) {
                DeviceTransfer TheMonthMaxDemand = (DeviceTransfer) map.get(CommonConstant.Demand.THE_MONTH_MAX_DEMAND);
                if (TheMonthMaxDemand != null) {
                    OperatingStatistic operatingStatistic = new OperatingStatistic();
                    operatingStatistic.setName("当月最大需量 ");
                    operatingStatistic.setValue(TheMonthMaxDemand.getValue() + "kW");
                    operatingStatistic.setTime(DateUtil.format(TheMonthMaxDemand.getUpdateTime(), CommonConstant.DATE));
                    list.add(operatingStatistic);

                }
            }
            Object objTheMonthMaxPower = map.get(CommonConstant.Demand.THE_MONTH_MAX_POWER);
            if (objTheMonthMaxPower instanceof DeviceTransfer) {
                DeviceTransfer TheMonthMaxPower = (DeviceTransfer) map.get(CommonConstant.Demand.THE_MONTH_MAX_POWER);
                if (TheMonthMaxPower != null) {
                    OperatingStatistic operatingStatistic = new OperatingStatistic();
                    operatingStatistic.setName("当月最大功率 ");
                    operatingStatistic.setValue(TheMonthMaxPower.getValue() + "kW");
                    operatingStatistic.setTime(DateUtil.format(TheMonthMaxPower.getUpdateTime(), CommonConstant.DATE));
                    list.add(operatingStatistic);
                }
            }
            Object objTheMonthMinPower = map.get(CommonConstant.Demand.THE_MONTH_MIN_POWER);
            if (objTheMonthMinPower instanceof DeviceTransfer) {
                DeviceTransfer TheMonthMinPower = (DeviceTransfer) map.get(CommonConstant.Demand.THE_MONTH_MIN_POWER);
                if (TheMonthMinPower != null) {
                    OperatingStatistic operatingStatistic = new OperatingStatistic();
                    operatingStatistic.setName("当月最小功率 ");
                    operatingStatistic.setValue(TheMonthMinPower.getValue() + "kW");
                    operatingStatistic.setTime(DateUtil.format(TheMonthMinPower.getUpdateTime(), CommonConstant.DATE));
                    list.add(operatingStatistic);
                }
            }
        }
        return list;
    }

    @Override
    public List<OperatingStatistic> getOperatingStatistic2(Integer stationId) {
        List<OperatingStatistic> list = new ArrayList<>();
        DeviceReqVO deviceReqVO = new DeviceReqVO();
        deviceReqVO.setStationId(stationId);
        //查询BMS
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.BMS);
        List<DeviceRespVO> deviceList = getList(deviceReqVO);
        if (CollectionUtils.isNotEmpty(deviceList)) {
            OperatingStatistic socOperating = new OperatingStatistic();
            OperatingStatistic sohOperating = new OperatingStatistic();
            socOperating.setName(DeviceTypeConstant.SOC2);
            sohOperating.setName(DeviceTypeConstant.SOH2);
            BigDecimal socValue = BigDecimal.ZERO;
            BigDecimal sohValue = BigDecimal.ZERO;

            BigDecimal socCount = BigDecimal.ZERO;
            BigDecimal sohCount = BigDecimal.ZERO;
            for (DeviceRespVO deviceRespVO : deviceList) {
                String redisKey = new StringBuilder().append(deviceRespVO.getDeviceType())
                        .append(":").append(stationId).append(":").append(deviceRespVO.getSrcId()).toString();
                Map<Object, Object> map = redisService.hgetall(redisKey);
                //soc
                Object socObject = map.get(DeviceTypeConstant.SOC);
                if (socObject instanceof DeviceTransfer) {
                    DeviceTransfer soc = (DeviceTransfer) socObject;
                    if (soc != null && soc.getValue() != null) {
                        socValue = socValue.add(soc.getValue());
                        socCount = socCount.add(BigDecimal.ONE);
                        socOperating.setTime(DateUtil.format(soc.getUpdateTime(), CommonConstant.DATE));
                    }
                }
                //soh
                Object sohObject = map.get(DeviceTypeConstant.SOH);
                if (sohObject instanceof DeviceTransfer) {
                    DeviceTransfer soh = (DeviceTransfer) sohObject;
                    if (soh != null && soh.getValue() != null) {
                        sohValue = sohValue.add(soh.getValue());
                        sohCount = sohCount.add(BigDecimal.ONE);
                        sohOperating.setTime(DateUtil.format(soh.getUpdateTime(), CommonConstant.DATE));
                    }
                }
            }
            if (socCount.intValue() != 0) {
                socOperating.setValue(socValue.divide(socCount, BigDecimal.ROUND_HALF_UP, 2).toString() + "%");
            } else {
                socOperating.setValue(socValue.toString() + "%");
            }
            list.add(socOperating);
            if (sohCount.intValue() != 0) {
                sohOperating.setValue(sohValue.divide(sohCount, BigDecimal.ROUND_HALF_UP, 2).toString() + "%");
            } else {
                sohOperating.setValue(sohValue.toString() + "%");
            }
            list.add(sohOperating);
        }
        //查询PCS
        deviceReqVO.setDeviceTypePrefix(DeviceTypeConstant.PCS);
        List<DeviceRespVO> pcsDeviceList = getList(deviceReqVO);
        if (CollectionUtils.isNotEmpty(pcsDeviceList)) {
            OperatingStatistic powerOperating = new OperatingStatistic();
            powerOperating.setName(DefineConstant.TOTAL_ACTIVE_POWER);
            BigDecimal powerValue = BigDecimal.ZERO;
            for (DeviceRespVO deviceRespVO : pcsDeviceList) {
                String redisKey = new StringBuilder().append(deviceRespVO.getDeviceType())
                        .append(":").append(stationId).append(":").append(deviceRespVO.getSrcId()).toString();
                Map<Object, Object> map = redisService.hgetall(redisKey);
                Object powerObject = map.get(DeviceTypeConstant.OUTPUT_POWER);
                if (powerObject instanceof DeviceTransfer) {
                    DeviceTransfer power = (DeviceTransfer) powerObject;
                    if (power != null && power.getValue() != null) {
                        powerValue = powerValue.add(power.getValue());
                        powerOperating.setTime(DateUtil.format(power.getUpdateTime(), CommonConstant.DATE));
                    }
                }
            }
            powerOperating.setValue(powerValue.toString() + "kW");
            list.add(powerOperating);
        }
        //电站状态
        OperatingStatistic statusOperating = new OperatingStatistic();
        statusOperating.setName(DefineConstant.STATION_STATUS);
        statusOperating.setValue(DefineConstant.SHUT_DOWN);
        JSONObject stationStatus = tabSortWebService.getStationStatus(stationId);
        if (stationStatus != null && stationStatus.get("stationStatus") != null) {
            Integer status = (Integer) stationStatus.get("stationStatus");
            if (status == 1) {
                statusOperating.setValue(DefineConstant.RUN);
            }
        }
        statusOperating.setTime(DateUtil.format(new Date(), CommonConstant.DATE));
        list.add(statusOperating);
        return list;
    }

    @Override
    public DeviceRespVO selectBySrcIdAndStationId(Integer stationId, Integer srcId) {
        Device device = deviceMapper.selectByStationIdAndSrcId(stationId, srcId);
        DeviceRespVO deviceRespVO = new DeviceRespVO();
        if (null != device) {
            BeanUtils.copyProperties(device, deviceRespVO);
        }
        return deviceRespVO;
    }

    @Override
    public void exportExcel(ExportReq vo, HttpServletResponse response) {
        if(vo.getType()==null || CommonConstant.ONE.equals(vo.getType())){
            //导出设备数据
            DeviceReqVO deviceReqVO = new DeviceReqVO();
            deviceReqVO.setStationIds(vo.getStationIds());
            List<DeviceRespVO> list = getList(deviceReqVO);
            String fileName = "device";
            String sheetName = "data";
            try {
                List<DeviceExport> exportList = new ArrayList<>();
                DeviceExport deviceExport = null;
                for (DeviceRespVO typeCol : list) {
                    deviceExport = new DeviceExport();
                    BeanUtils.copyProperties(typeCol, deviceExport);
                    exportList.add(deviceExport);
                }
                EasyExcelUtil.writeExcel(response, exportList, fileName, sheetName, DeviceExport.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(CommonConstant.TWO.equals(vo.getType())){
            //导出设备类型数据
            DeviceTypeQuery deviceTypeQuery = new DeviceTypeQuery();
            deviceTypeQuery.setStationIds(vo.getStationIds());
            List<DeviceTypeConfig> list = deviceTypeConfigService.queryListByCondition(deviceTypeQuery);
            String fileName = "deviceTypeConfig";
            String sheetName = "data";
            try {
                List<DeviceTypeConfigExport> exportList = new ArrayList<>();
                DeviceTypeConfigExport exp = null;
                for (DeviceTypeConfig s : list) {
                    exp = new DeviceTypeConfigExport();
                    BeanUtils.copyProperties(s, exp);
                    exportList.add(exp);
                }
                EasyExcelUtil.writeExcel(response, exportList, fileName, sheetName, DeviceTypeConfigExport.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(CommonConstant.THREE.equals(vo.getType())){
            //导出电站数据
            List<Station> list = stationService.selectStationsByIds(vo.getStationIds(),null);
            String fileName = "station";
            String sheetName = "data";
            try {
                List<StationExport> exportList = new ArrayList<>();
                StationExport exp = null;
                for (Station s : list) {
                    exp = new StationExport();
                    BeanUtils.copyProperties(s, exp);
                    exportList.add(exp);
                }
                EasyExcelUtil.writeExcel(response, exportList, fileName, sheetName, StationExport.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void importExcel(MultipartFile file, Integer type) {
        if(type==null || CommonConstant.ONE.equals(type)){
            try {
                List<DeviceExport> list = EasyExcel.read(file.getInputStream()).head(DeviceExport.class).sheet().doReadSync();
                Map<Integer, List<Device>> updateMap = new HashMap<>();
                List<Device> updateList = new ArrayList<>();
                Device s = null;
                Integer updateNum = CommonConstant.ONE;
                for (DeviceExport e:list) {
                    s = new Device();
                    BeanUtil.copyProperties(e,s);
                    updateList.add(s);
                    if(updateList.size() % CommonConstant.NINE_HUNDRED_AND_NINETY_NINE == 998){
                        updateList = new ArrayList<>();
                        updateNum++;
                    }
                    updateMap.put(updateNum, updateList);
                }
                for (Map.Entry<Integer,List<Device>> m : updateMap.entrySet()) {
                    deviceMapper.updateDeviceList(m.getValue());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(CommonConstant.TWO.equals(type)){
            try {
                List<DeviceTypeConfigExport> list = EasyExcel.read(file.getInputStream()).head(DeviceTypeConfigExport.class).sheet().doReadSync();
                Map<Integer, List<DeviceTypeConfig>> updateMap = new HashMap<>();
                List<DeviceTypeConfig> updateList = new ArrayList<>();
                DeviceTypeConfig s = null;
                Integer updateNum = CommonConstant.ONE;
                for (DeviceTypeConfigExport e:list) {
                    s = new DeviceTypeConfig();
                    BeanUtil.copyProperties(e,s);
                    updateList.add(s);
                    if(updateList.size() % CommonConstant.NINE_HUNDRED_AND_NINETY_NINE == 998){
                        updateList = new ArrayList<>();
                        updateNum++;
                    }
                    updateMap.put(updateNum, updateList);
                }
                for (Map.Entry<Integer,List<DeviceTypeConfig>> m : updateMap.entrySet()) {
                    deviceTypeConfigService.updateDeviceTypeConfigList(m.getValue());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(CommonConstant.THREE.equals(type)){
            try {
                List<StationExport> list = EasyExcel.read(file.getInputStream()).head(StationExport.class).sheet().doReadSync();
                Map<Integer, List<Station>> updateMap = new HashMap<>();
                List<Station> updateList = new ArrayList<>();
                Station s = null;
                Integer updateNum = CommonConstant.ONE;
                for (StationExport e:list) {
                    s = new Station();
                    BeanUtil.copyProperties(e,s);
                    updateList.add(s);
                    if(updateList.size() % CommonConstant.NINE_HUNDRED_AND_NINETY_NINE == 998){
                        updateList = new ArrayList<>();
                        updateNum++;
                    }
                    updateMap.put(updateNum, updateList);
                }
                for (Map.Entry<Integer,List<Station>> m : updateMap.entrySet()) {
                    stationService.updateStationList(m.getValue());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}