package com.fastbee.data.service.gis.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fastbee.common.core.domain.CommonResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.model.vo.TreeItemVo;
import com.fastbee.common.model.vo.iot.GisDeviceListVo;
import com.fastbee.common.utils.*;
import com.fastbee.data.service.gis.IGisDeviceService;
import com.fastbee.iot.domain.Device;
import com.fastbee.iot.domain.DeviceLog;
import com.fastbee.iot.domain.Product;
import com.fastbee.iot.domain.ThingsModel;
import com.fastbee.iot.haiwei.service.HaiWeiService;
import com.fastbee.iot.mapper.DeviceMapper;
import com.fastbee.iot.mapper.ProductMapper;
import com.fastbee.iot.model.haiwei.HaiWeiDeviceInfoVo;
import com.fastbee.iot.model.haiwei.HaiWeiPropertyVo;
import com.fastbee.iot.service.*;
import com.fastbee.waterele.domain.MaWatereleRecord;
import com.fastbee.waterele.service.IMaWatereleRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GisDeviceServiceImpl implements IGisDeviceService {

    private final DeviceMapper deviceMapper;
    private final ProductMapper productMapper;

    @Autowired
    public IDeviceService iDeviceService;
    @Autowired
    public IProductService iProductService;
    @Autowired
    private IDeviceLogService logService;

    //    @Resource
//    DeviceInfoCacheService deviceInfoCacheService;
    @Autowired
    private IAlertService iAlertService;
    @Autowired
    private IThingsModelService thingsModelService;

    @Autowired
    private IMaWatereleRecordService watereleRecordService;

    @Resource
    HaiWeiService haiWeiService;

    public GisDeviceServiceImpl(@Qualifier("deviceMapper") DeviceMapper deviceMapper, @Qualifier("productMapper") ProductMapper productMapper) {
        this.deviceMapper = deviceMapper;
        this.productMapper = productMapper;
    }

    @Override
    public GisDeviceListVo totalAndList(Device device) {
        Product product = new Product();
        product.setProductId(136L);
        List<Product> productEntities = productMapper.selectProductList(product);
        Long userId = SecurityUtils.getUserId();
        List<TreeItemVo> productContainDeviceListVos = new ArrayList<>();
        int count = 0;
        int onLineCount = 0;
        GisDeviceListVo deviceListVo = new GisDeviceListVo();
        for (Product productEntity : productEntities) {
            TreeItemVo treeItemVo = new TreeItemVo();
            treeItemVo.setId(1000000 + productEntity.getProductId());
            treeItemVo.setName(productEntity.getProductName());
            List<Device> deviceEntities = new ArrayList<>();
            Device deviceEntity = new Device();
            deviceEntity.setProductId(productEntity.getProductId());
            deviceEntity.setStatus(device.getStatus());
            deviceEntity.setDeviceNameOrSerialNumber(device.getDeviceNameOrSerialNumber());
            if (userId.equals(1L)) {
                deviceEntities = deviceMapper.selectDeviceListNotUser(deviceEntity);
            } else {
                deviceEntities = deviceMapper.selectDeviceList(deviceEntity);
            }
            count += deviceEntities.size();
            List<TreeItemVo> treeItemVoList = new ArrayList<>();
            for (Device deviceEntity1 : deviceEntities) {
                TreeItemVo devItem = new TreeItemVo();
                devItem.setName(deviceEntity1.getDeviceName());
                devItem.setId(deviceEntity1.getDeviceId());
                devItem.setStatus(deviceEntity1.getStatus());
                devItem.setLatitude(deviceEntity1.getLatitude() != null ? deviceEntity1.getLatitude().floatValue() : null);
                devItem.setLongitude(deviceEntity1.getLongitude() != null ? deviceEntity1.getLongitude().floatValue() : null);
                treeItemVoList.add(devItem);
                if (deviceEntity1.getStatus() == 3) {
                    onLineCount++;
                }
            }
            treeItemVo.setChildren(treeItemVoList);
            productContainDeviceListVos.add(treeItemVo);
        }
        deviceListVo.setProductContainDeviceList(productContainDeviceListVos);
        deviceListVo.setCount(count);
        deviceListVo.setOnLineCount(onLineCount);
        return deviceListVo;
    }

    @Override
    public Object getRealTimeDataByDevicerId(Long deviceId) {
        HashMap<String, Object> rMap = new HashMap<String, Object>() {
        };
        if (deviceId == null) {
            throw new RuntimeException("请上传devicerId");
        }
        Device device = iDeviceService.selectDeviceByDeviceId(deviceId);
        if (device == null) {
            throw new RuntimeException("未查到该设备");
        }
        DateTime dateTime = DateUtil.date(new Date());
        Map<String, Object> devParams = getDevParams(device);
        //太阳能设备
        String taiyangnengIds = devParams.get("taiyangnIds").toString();
        ThingsModel thingsModel1 = new ThingsModel();
        thingsModel1.setProductId(138L);
        List<ThingsModel> taiyangnengModels = thingsModelService.selectThingsModelList(thingsModel1);
        taiyangnengModels.sort(Comparator.comparing(ThingsModel::getModelOrder));
        if (StringUtils.isNotEmpty(taiyangnengIds)) {
//            Device taiyangnengDevice = deviceMapper.selectDeviceByDeviceId(Long.parseLong(taiyangnengIds));
            CommonResult<HaiWeiDeviceInfoVo> cache = haiWeiService.getCache(Long.parseLong(taiyangnengIds));
            if(cache != null){
                HaiWeiDeviceInfoVo checkedData = cache.getCheckedData();
                if(checkedData != null){
                    List<HaiWeiPropertyVo> propertyList = checkedData.getPropertyList();
                    for (HaiWeiPropertyVo haiWeiPropertyVo : propertyList) {
//                        if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_kaixian")){
//                            continue;
//                        }
                        HashMap<Object, Object> hashMap = new HashMap<Object, Object>() {{
                            put("upType", 0);
                            put("identifier", haiWeiPropertyVo.getNameEn());
                            put("unit", haiWeiPropertyVo.getUnit());
                            put("value", StringUtils.isEmpty(haiWeiPropertyVo.getValue().toString())?
                                    "--":haiWeiPropertyVo.getValue().toString());
                            put("name", haiWeiPropertyVo.getNameCn());
                        }};
                        if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_MpptDown")){
                            hashMap.put("value", NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                    Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"正常":"异常"):"正常");
                        }else  if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_市电状态")){
                            hashMap.put("value", NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                    Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"市电":"太阳能"):"市电");
                        }
                        rMap.put(haiWeiPropertyVo.getNameEn(), hashMap);
                    }
                }
            }
//            List<DeviceLog> deviceLogs = logService.selectDeviceLogList(new DeviceLog() {{
//                setSerialNumber(taiyangnengDevice.getSerialNumber());
//                setBeginTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, -1)).toString());
//                setEndTime(DateUtil.endOfDay(dateTime).toString());
//            }});
//            Map<String, List<DeviceLog>> taiyangnengCollect = deviceLogs.stream().sorted(Comparator
//                    .comparing(DeviceLog::getCreateTime, Comparator
//                            .nullsFirst(Comparator.naturalOrder())).reversed()).collect(Collectors.groupingBy(t -> t.getIdentity()));
//            for (ThingsModel thingsModel : taiyangnengModels) {
//                if (thingsModel.getModelName().equals("市电状态")) {
//                    List<DeviceLog> deviceLogs1 = taiyangnengCollect.get(thingsModel.getIdentifier());
//                    HashMap<Object, Object> hashMap = new HashMap<Object, Object>() {{
//                        put("upType", 0);
//                        put("identifier", thingsModel.getIdentifier());
//                        put("unit", "");
//                        put("value", "市电");
//                        put("name", thingsModel.getModelName());
//                    }};
//                    if (deviceLogs1.size() > 0) {
//                        if (StringUtils.isNotEmpty(deviceLogs1.get(0).getLogValue())) {
//                            if (Float.parseFloat(deviceLogs1.get(0).getLogValue()) == 1f) {
//                                hashMap.put("value", "市电");
//                            } else {
//                                hashMap.put("value", "太阳能");
//                            }
//                        }
//                    }
//                    rMap.put(thingsModel.getIdentifier(), hashMap);
//                } else {
//                    HashMap<Object, Object> hashMap = new HashMap<Object, Object>() {{
//                        put("upType", 0);
//                        put("identifier", thingsModel.getIdentifier());
//                        put("unit", "");
//                        put("value", 0);
//                        put("name", thingsModel.getModelName());
//                    }};
//                    if (StringUtils.isNotEmpty(thingsModel.getSpecs())) {
//                        String specs = thingsModel.getSpecs();
//                        JSONObject parse = (JSONObject) JSON.parse(specs);
//                        if (parse.containsKey("unit")) {
//                            hashMap.put("unit", parse.get("unit"));
//                        }
//                    }
//                    if (hashMap.size() > 1) {
//                        List<DeviceLog> deviceLogs1 = taiyangnengCollect.get(thingsModel.getIdentifier());
//                        if (deviceLogs1 != null) {
//                            if (deviceLogs1.size() > 0) {
//                                if (StringUtils.isNotEmpty(deviceLogs1.get(0).getLogValue())) {
//                                    if (deviceLogs1.size() > 1) {
//                                        try{
//                                            if (Float.parseFloat(deviceLogs1.get(0).getLogValue()) == Float.parseFloat(deviceLogs1.get(1).getLogValue())) {
//                                                hashMap.put("upType", 1);
//                                            } else if (Float.parseFloat(deviceLogs1.get(0).getLogValue()) < Float.parseFloat(deviceLogs1.get(1).getLogValue())) {
//                                                hashMap.put("upType", -1);
//                                            }
//                                        }catch (Exception e){
//                                            hashMap.put("upType", 0);
//                                        }
//                                    } else {
//                                        hashMap.put("upType", 0);
//                                    }
//                                    hashMap.put("value", deviceLogs1.get(0).getLogValue());
//                                } else {
//                                    hashMap.put("value", "--");
//                                    hashMap.put("upType", 0);
//                                }
//
//                            } else {
//                                hashMap.put("value", "--");
//                                hashMap.put("upType", 0);
//                            }
//
//
//                        }
//                    } else if (hashMap.size() > 0) {
//                        List<DeviceLog> deviceLogs2 = taiyangnengCollect.get(thingsModel.getIdentifier());
//                        if (deviceLogs2 != null) {
//                            hashMap.put("value", deviceLogs2.get(0).getLogValue());
//                        }
//                    }
//                    rMap.put(thingsModel.getIdentifier(), hashMap);
//                }
//            }
        } else {
            for (ThingsModel thingsModel : taiyangnengModels) {
                HashMap<Object, Object> hashMap = new HashMap<Object, Object>() {{
                    put("upType", 0);
                    put("identifier", thingsModel.getIdentifier());
                    put("unit", "");
                    put("value", 0);
                    put("name", thingsModel.getModelName());
                }};
                rMap.put(thingsModel.getIdentifier(), hashMap);
            }
        }
        //箱门信息
        String guimenIds = devParams.get("guimenIds").toString();
        if (StringUtils.isNotEmpty(guimenIds)) {
            CommonResult<HaiWeiDeviceInfoVo> cache = haiWeiService.getCache(Long.valueOf(guimenIds));
            HaiWeiDeviceInfoVo checkedData = cache.getCheckedData();
            List<HaiWeiPropertyVo> propertyList = checkedData.getPropertyList();
            for (HaiWeiPropertyVo haiWeiPropertyVo : propertyList) {
                if (haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_open")) {
                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
                        put("upType", 0);
                        put("identifier", "xiangmen");
                        put("unit", "");
                        put("value", StringUtils.isEmpty(haiWeiPropertyVo.getValue().toString())?
                                "--":haiWeiPropertyVo.getValue().toString());
                        put("name", haiWeiPropertyVo.getNameCn());
                    }};
                    rMap.put("xiangmen", hashMap1);
                } else if (haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_lock1Con")) {
                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
                        put("upType", 0);
                        put("identifier", "三菱FX2N_1_lock1Con");
                        put("unit", "");
                        put("value", NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"正常":"异常"):"正常");
                        put("name", "内门上锁");
                    }};
                    rMap.put("内门上锁", hashMap1);
                } else if (haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_lock2Con")) {
                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
                        put("upType", 0);
                        put("identifier", "三菱FX2N_1_lock2Con");
                        put("unit", "");
                        put("value", NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"正常":"异常"):"正常");
                        put("name", "内门下锁");
                    }};
                    rMap.put("内门下锁", hashMap1);
                }
            }
        } else {
            for (ThingsModel thingsModel : taiyangnengModels) {
                HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
                    put("upType", 0);
                    put("identifier", thingsModel.getIdentifier().equals("三菱FX2N_1_open") ? "xiangmen" : thingsModel.getIdentifier());
                    put("unit", "");
                    put("value", 0);
                    put("name", thingsModel.getModelName());
                }};
                rMap.put(thingsModel.getIdentifier().equals("三菱FX2N_1_open") ? "xiangmen" : thingsModel.getIdentifier(), hashMap1);
            }
        }
        String liuliangIds = devParams.get("liuliangIds").toString();
        ThingsModel thingsModel2 = new ThingsModel();
        thingsModel2.setProductId(139L);
        List<ThingsModel> liuliangModels = thingsModelService.selectThingsModelList(thingsModel2);
        if (StringUtils.isNotEmpty(liuliangModels)) {
            CommonResult<HaiWeiDeviceInfoVo> cache = haiWeiService.getCache(Long.parseLong(liuliangIds));
            if(cache != null){
                HaiWeiDeviceInfoVo checkedData = cache.getCheckedData();
                if(checkedData != null){
                    List<HaiWeiPropertyVo> propertyList = checkedData.getPropertyList();
                    for (HaiWeiPropertyVo haiWeiPropertyVo : propertyList) {
//                        if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_kaixian")){
//                            continue;
//                        }
                        HashMap<Object, Object> hashMap = new HashMap<Object, Object>() {{
                            put("upType", 0);
                            put("identifier", haiWeiPropertyVo.getNameEn());
                            put("unit", haiWeiPropertyVo.getUnit());
                            put("value", StringUtils.isEmpty(haiWeiPropertyVo.getValue().toString())?
                                    "--":haiWeiPropertyVo.getValue().toString());
                            put("name", haiWeiPropertyVo.getNameCn());
                        }};
                        if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_guanxian")){
                            hashMap.put("value",  NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                    Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"关闭":"开启"):"关闭");
                            rMap.put("阀门状态", hashMap);
                        }else if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_FlowDown")){
                            hashMap.put("value",  NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                    Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"正常":"异常"):"正常");
                            rMap.put("水表状态", hashMap);
                        }else if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_mCon")){
                            hashMap.put("value", NumberUtils.isNumeric(haiWeiPropertyVo.getValue().toString())?(
                                    Float.parseFloat(haiWeiPropertyVo.getValue().toString()) == 1f?"正常":"异常"):"正常");
                            rMap.put("水泵状态", hashMap);
                        }else if(haiWeiPropertyVo.getNameEn().equals("三菱FX2N_1_sumFlow")){
                            hashMap.put("value",  haiWeiPropertyVo.getValue().toString());
                            rMap.put("sumFlow", hashMap);
                        }else {
                            rMap.put(haiWeiPropertyVo.getNameEn(), hashMap);
                        }
                    }
                }
            }
//            Device liuliangDevice = deviceMapper.selectDeviceByDeviceId(Long.parseLong(liuliangIds));
//            List<DeviceLog> deviceLogs = logService.selectDeviceLogList(new DeviceLog() {{
//                setSerialNumber(liuliangDevice.getSerialNumber());
//                setBeginTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, -1)).toString());
//                setEndTime(DateUtil.endOfDay(dateTime).toString());
//            }});
//            Map<String, List<DeviceLog>> liuliangCollect = deviceLogs.stream().sorted(Comparator
//                    .comparing(DeviceLog::getCreateTime, Comparator
//                            .nullsFirst(Comparator.naturalOrder())).reversed()).collect(Collectors.groupingBy(t -> t.getIdentity()));
//            for (ThingsModel thingsModel : liuliangModels) {
//                if(thingsModel.getIdentifier().equals("三菱FX2N_1_mCon")){
//                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
//                        put("upType", 0);
//                        put("identifier", "三菱FX2N_1_mCon");
//                        put("unit", "");
//                        put("value", "停止");
//                        put("name", thingsModel.getModelName());
//                    }};
//                    List<DeviceLog> deviceLogs1 = liuliangCollect.get(thingsModel.getIdentifier());
//                    if(deviceLogs1.size() > 0){
//                        if(NumberUtils.isNumeric(deviceLogs1.get(0).getLogValue())){
//                            if(Float.parseFloat(deviceLogs1.get(0).getLogValue()) == 1f){
//                                hashMap1.put("value", "启动");
//                            }else{
//                                hashMap1.put("value", "停止");
//                            }
//                        }
//                    }
//                    rMap.put("水泵状态", hashMap1);
//                }else if(thingsModel.getIdentifier().equals("三菱FX2N_1_guanxian")){
//                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
//                        put("upType", 0);
//                        put("identifier", "三菱FX2N_1_guanxian");
//                        put("unit", "");
//                        put("value", "关闭");
//                        put("name", thingsModel.getModelName());
//                    }};
//                    List<DeviceLog> deviceLogs1 = liuliangCollect.get(thingsModel.getIdentifier());
//                    if(deviceLogs1.size() > 0){
//                        if(NumberUtils.isNumeric(deviceLogs1.get(0).getLogValue())){
//                            if(Float.parseFloat(deviceLogs1.get(0).getLogValue()) == 1f){
//                                hashMap1.put("value", "关闭");
//                            }else{
//                                hashMap1.put("value", "开启");
//                            }
//                        }else{
//                            hashMap1.put("value", "关闭");
//                        }
//
//                    }
//                    rMap.put("阀门状态", hashMap1);
//                }else if(thingsModel.getIdentifier().equals("三菱FX2N_1_FlowDown")){
//                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
//                        put("upType", 0);
//                        put("identifier", "三菱FX2N_1_FlowDown");
//                        put("unit", "");
//                        put("value", "正常");
//                        put("name", thingsModel.getModelName());
//                    }};
//                    List<DeviceLog> deviceLogs1 = liuliangCollect.get(thingsModel.getIdentifier());
//                    if(deviceLogs1.size() > 0){
//                        if(NumberUtils.isNumeric(deviceLogs1.get(0).getLogValue())){
//                            if(Float.parseFloat(deviceLogs1.get(0).getLogValue()) == 1f){
//                                hashMap1.put("value", "断线");
//                            }else{
//                                hashMap1.put("value", "正常");
//                            }
//                        }else{
//                            hashMap1.put("value", "正常");
//                        }
//
//                    }
//                    rMap.put("水表状态", hashMap1);
//                }else{
//                    HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
//                        put("upType", 0);
//                        put("identifier", thingsModel.getIdentifier().equals("三菱FX2N_1_sumFlow") ? "sumFlow" : thingsModel.getIdentifier());
//                        put("unit", "");
//                        put("value", 0);
//                        put("name", thingsModel.getModelName());
//                    }};
//                    if (StringUtils.isNotEmpty(thingsModel.getSpecs())) {
//                        String specs = thingsModel.getSpecs();
//                        JSONObject parse = (JSONObject) JSON.parse(specs);
//                        if (parse.containsKey("unit")) {
//                            hashMap1.put("unit", parse.get("unit"));
//                        }
//                    }
//
//                    if (hashMap1.size() > 1) {
//                        List<DeviceLog> deviceLogs1 = liuliangCollect.get(thingsModel.getIdentifier());
//                        if (deviceLogs1 != null) {
//                            if (deviceLogs1.size() > 0) {
//                                if (StringUtils.isNotEmpty(deviceLogs1.get(0).getLogValue())) {
//                                    if (deviceLogs1.size() > 1) {
//                                        if (Float.parseFloat(deviceLogs1.get(0).getLogValue()) == Float.parseFloat(deviceLogs1.get(1).getLogValue())) {
//                                            hashMap1.put("upType", 1);
//                                        } else if (Float.parseFloat(deviceLogs1.get(0).getLogValue()) < Float.parseFloat(deviceLogs1.get(1).getLogValue())) {
//                                            hashMap1.put("upType", -1);
//                                        }
//                                    } else {
//                                        hashMap1.put("upType", 0);
//                                    }
//                                    hashMap1.put("value", deviceLogs1.get(0).getLogValue());
//                                } else {
//                                    hashMap1.put("value", "--");
//                                    hashMap1.put("upType", 0);
//                                }
//
//                            } else {
//                                hashMap1.put("value", "--");
//                                hashMap1.put("upType", 0);
//                            }
//
//
//                        }
//                    } else if (hashMap1.size() > 0) {
//                        List<DeviceLog> deviceLogs2 = liuliangCollect.get(thingsModel.getIdentifier());
//                        if (deviceLogs2 != null) {
//                            hashMap1.put("value", deviceLogs2.get(0).getLogValue());
//                        }
//                    }
//                    rMap.put(thingsModel.getIdentifier().equals("三菱FX2N_1_sumFlow") ? "sumFlow" : thingsModel.getIdentifier(), hashMap1);
//                }
//             }
        } else {
            for (ThingsModel thingsModel : taiyangnengModels) {
                HashMap<Object, Object> hashMap1 = new HashMap<Object, Object>() {{
                    put("upType", 0);
                    put("identifier", thingsModel.getIdentifier().equals("三菱FX2N_1_sumFlow") ? "sumFlow" : thingsModel.getIdentifier());
                    put("unit", "");
                    put("value", 0);
                    put("name", thingsModel.getModelName());
                }};
                rMap.put(thingsModel.getIdentifier().equals("三菱FX2N_1_sumFlow") ? "sumFlow" : thingsModel.getIdentifier(), hashMap1);
            }
        }
        MaWatereleRecord maWatereleRecord = new MaWatereleRecord();
        maWatereleRecord.setDevSn(device.getSerialNumber());
        TableDataInfo tableDataInfo = watereleRecordService.selectMaWatereleRecordList(maWatereleRecord);
        List<MaWatereleRecord> deviceLogs = (List<MaWatereleRecord>) tableDataInfo.getRows();
        String sumEle = "0";
        if (deviceLogs.size() > 0) {
            sumEle = NumberUtil.isNumber(deviceLogs.get(0).getSumele()) ? deviceLogs.get(0).getSumele() :
                    "0";
        }
        String finalSumEle = sumEle;
        HashMap<Object, Object> hashMap2 = new HashMap<Object, Object>() {{
            put("upType", 0);
            put("identifier", "sumEle");
            put("unit", "kwh");
            put("value", finalSumEle);
            put("name", "累计用电量");
        }};
        rMap.put("sumEle", hashMap2);
        return rMap;
    }

    @Override
    public Object getDeviceLogCurves(Long deviceId) {
        if (deviceId == null) {
            throw new RuntimeException("请上传deviceId");
        }

        Device device = iDeviceService.selectDeviceByDeviceId(deviceId);
        if (device == null) {
            throw new RuntimeException("未查到该设备");
        }
        //获取累计水量和累计电量的前20条数据记录
        MaWatereleRecord watereleRecord = new MaWatereleRecord();
        watereleRecord.setDevSn(device.getSerialNumber());
        List<MaWatereleRecord> maWatereleRecords =
                (List<MaWatereleRecord>) watereleRecordService.selectMaWatereleRecordList(watereleRecord).getRows();
        if (maWatereleRecords.size() > 20) {
            maWatereleRecords = maWatereleRecords.subList(0, 20);
        }
        maWatereleRecords.sort(Comparator.comparing(MaWatereleRecord::getCreateTime));
        ArrayList<Object> sumFlow = new ArrayList<>();
        ArrayList<Object> sumFlowTime = new ArrayList<>();
        ArrayList<Object> sumEle = new ArrayList<>();
        ArrayList<Object> time = new ArrayList<>();
        for (MaWatereleRecord record : maWatereleRecords) {
            time.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, record.getCreateTime()));
//            sumFlow.add(record.getSumflow());
            sumEle.add(record.getSumele());
        }
        DateTime dateTime = DateUtil.date(new Date());
        Map<String, Object> devParams = DevParamsUtils.getDevParams(device.getDevParams());
        if (devParams.containsKey("liuliangIds")) {
            Device liuliangDevice = iDeviceService.selectDeviceByDeviceId(Long.parseLong(devParams.get("liuliangIds").toString()));
            if (liuliangDevice != null) {
                List<DeviceLog> deviceLogs = logService.selectDeviceLogList(new DeviceLog() {{
                    setSerialNumber(liuliangDevice.getSerialNumber());
                    setBeginTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, 0)).toString());
                    setEndTime(DateUtil.endOfDay(dateTime).toString());
                }});
                Map<String, List<DeviceLog>> liuliangCollect = deviceLogs.stream().sorted(Comparator
                        .comparing(DeviceLog::getCreateTime, Comparator
                                .nullsFirst(Comparator.naturalOrder()))).collect(Collectors.groupingBy(t -> t.getIdentity()));
                List<DeviceLog> deviceLogList = liuliangCollect.get("三菱FX2N_1_sumFlow");
                if (deviceLogList != null && deviceLogList.size() > 0) {
                    for (DeviceLog deviceLog : deviceLogList) {
                        sumFlow.add(deviceLog.getLogValue());
                        sumFlowTime.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, deviceLog.getCreateTime()));
                    }
                }
            }
        }

        Map<String, Object> rMap = new HashMap<>();
        rMap.put("time", time);
        rMap.put("sumFlow", sumFlow);
        rMap.put("sumFlowTime", sumFlowTime);
        rMap.put("sumEle", sumEle);
        return rMap;
    }


    private HashMap<String, Object> getDataList(Device device, String identity) {
        HashMap<String, Object> dataListMap = new HashMap<>();
        HashMap<String, Object> kvHashMap = new HashMap<>();
        kvHashMap.put("identity", identity);
        kvHashMap.put("serialNumber", device.getSerialNumber());
        Date endTime = new Date();
        kvHashMap.put("endTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR, -23);
        kvHashMap.put("beginTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH, calendar.getTime()) + ":00:00");
        List<HashMap<String, Object>> reMap = logService.selectDayData(kvHashMap);
        Map<String, Map<String, Object>> create_time = new HashMap<>();
        if (reMap != null) {
            create_time = reMap.stream().collect(Collectors.toMap(t -> {
                return DateUtil.date((LocalDateTime) t.get("create_time")).toString("HH");
            }, t -> t, (t, t1) -> t1));
        }
        DateTime date = DateUtil.date();
        ArrayList<Object> jiangyvliang = new ArrayList<>();
        ArrayList<Object> time = new ArrayList<>();
        dataListMap.put("time", time);
        dataListMap.put("data", jiangyvliang);
        for (int i = 0; i < 24; i++) {
            String s = DateUtil.offsetHour(DateUtil.offsetHour(date, -23), i).toString("HH");
            time.add(s);
            Map<String, Object> map = create_time.get(s);
            if (map != null) {
                if (identity.equals("dataSumFlow")) {
                    jiangyvliang.add(Float.parseFloat(create_time.get(s).get("maxLogValue").toString())
                            - Float.parseFloat(create_time.get(s).get("minLogValue").toString()));
                } else {
                    jiangyvliang.add(create_time.get(s).get("avgLogValue"));
                }
            } else {
                jiangyvliang.add(0);
            }
        }
        return dataListMap;

    }

    public Map<String, Object> getDevParams(Device device) {
        Map<String, Object> devData = new HashMap<>();
        try {
            Object devParams = com.alibaba.fastjson.JSON.parse(device.getDevParams());    //先转换成Object
            List<Map<String, Object>> Params = (List<Map<String, Object>>) devParams;
            if (Params != null) {
                for (Map<String, Object> param : Params) {
                    devData.put(param.get("key").toString(), param.get("value").toString());
                }
            }
        } catch (Exception exception) {
        }

        return devData;
    }

}
