package com.gyee.generation.util.realtimesource;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.gyee.generation.model.auto.ProBasicEquipmentPoint;
import com.gyee.generation.model.auto.ProBasicPowerstationPoint;
import com.gyee.generation.model.vo.RealTimeParameterVo;
import com.gyee.generation.util.realtimesource.timeseries.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 */
@Component
public class EdosUtil implements IEdosUtil {

    private RestTemplate restTemplate =new RestTemplate();
    @Value("${db.url1}")
    private String baseURL;

    @Value("${db.url2}")
    private String baseURL2;

    @Value("${initialcode}")
    private String initialcode;
    @Override
    public PointData getRealData(ProBasicPowerstationPoint point) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            try {
                Optional<String> keys = Optional.ofNullable(point.getNemCode());
                Optional<String> thingType = Optional.ofNullable("station");
                Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
                Optional<String> uniformCodes = Optional.ofNullable(point.getUniformCode());

                String url = baseURL + "/latest?null=0";
                if (point.getNemCode().startsWith("GF-")){
                    url =  baseURL2 + "/latest?null=0";
                }
                if (keys.isPresent())
                    url = url + "&keys=" + keys.get();
                if (thingType.isPresent())
                    url = url + "&thingType=" + thingType.get();
                if (thingId.isPresent())
                    url = url + "&thingId=" + thingId.get();
                if (uniformCodes.isPresent())
                    url = url + "&uniformCodes=" + uniformCodes.get();

                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonArray = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonArray)){
                    List<PointData> list = JsonObjectHelper.phrasePointData(jsonArray);
                    if (list.size() > 0)
                    {
                        PointData po=list.get(0);
                        po.setPointValueInDouble(NumberUtil.round(po.getPointValueInDouble(),4).doubleValue());
                        return po;
                    }
                    else
                    {
                        return ErrorRequest.RequestError(point.getNemCode());
                    }

                } else {
                    return ErrorRequest.RequestError(point.getNemCode());
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            return po;
        }

    }

    @Override
    public PointData getSectionData(String point, Long date) throws Exception {


        if (ObjectUtil.isNotEmpty(point)) {


            Optional<String> tagName = Optional.ofNullable(point);

            String url = baseURL + "/history/section?tagNames=" + tagName.get() + "&ts=" + date;
            if (point.startsWith("GF-")) {
                url = baseURL2 + "/history/section?tagNames=" + tagName.get() + "&ts=" + date;
            }
            try {
                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonObject = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonObject) && !jsonObject.isEmpty()) {

                    return JsonObjectHelper.phrasePointData(jsonObject, point);
                } else {

                    return new PointData();
                }
            } catch (Exception e) {

                return new PointData();
            }
        } else {

            PointData data = new PointData();
            data.setEdnaId(point);
            data.setPointTime(date);
            data.setPointValue("0");
            data.setPointName("1");
            data.setPointValueInDouble(0.0);
            return data;
        }
    }

    @Override
    public PointData getSectionData(ProBasicPowerstationPoint point, Long date) throws Exception {

        if (ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode())) {


            Optional<String> tagName = Optional.ofNullable(point.getNemCode());

            String url = baseURL + "/history/section?tagNames=" + tagName.get() + "&ts=" + date;
            if (point.getNemCode().startsWith("GF-")) {
                url = baseURL2 + "/history/section?tagNames=" + tagName.get() + "&ts=" + date;
            }
            try {
                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonObject = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonObject) && !jsonObject.isEmpty()) {

                    return JsonObjectHelper.phrasePointData(jsonObject, point.getNemCode());
                } else {

                    return new PointData();
                }
            } catch (Exception e) {

                return new PointData();
            }
        } else {

            PointData data = new PointData();
            data.setEdnaId(point.getNemCode());
            data.setPointTime(date);
            data.setPointValue("0");
            data.setPointName("1");
            data.setPointValueInDouble(0.0);
            return data;
        }

    }

    @Override
    public PointData getSectionData(ProBasicEquipmentPoint point, Long date) throws Exception {


        if (ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode())) {


            Optional<String> tagName = Optional.ofNullable(point.getNemCode());

            String url = baseURL + "/history/section?tagNames=" + tagName.get() + "&ts=" + date;
            if (point.getNemCode().startsWith("GF-")) {
                url = baseURL2 + "/history/section?tagNames=" + tagName.get() + "&ts=" + date;
            }
            try {
                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonObject = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonObject) && !jsonObject.isEmpty()) {

                    return JsonObjectHelper.phrasePointData(jsonObject, point.getNemCode());
                } else {

                    return new PointData();
                }
            } catch (Exception e) {

                return new PointData();
            }
        } else {

            PointData data = new PointData();
            data.setEdnaId(point.getNemCode());
            data.setPointTime(date);
            data.setPointValue("0");
            data.setPointName("1");
            data.setPointValueInDouble(0.0);
            return data;
        }

    }


    @Override
    public List<PointData> getHistoryDatasSnap(ProBasicPowerstationPoint point, Long beginDate, Long endDate, Long count, Long pried) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> tagName = Optional.ofNullable(point.getNemCode());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> uniformCode = Optional.ofNullable(point.getUniformCode());
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);
            //通过时间区间和时间间隔获取点数
            Long finalInterval;
            if (pried != null)
                finalInterval = pried;
            else if (count != null)
                finalInterval = (endDate - beginDate) / count;
            else
                return ErrorRequest.RequestListError(point.getNemCode());
            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));

            try {
                String url = baseURL + "/history/snap?null=0";
                if (point.getNemCode().startsWith("GF-")){
                    url =  baseURL2 + "/history/snap?null=0";
                }

                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCode.isPresent())
                        url = url + "&uniformCodes=" + uniformCode.get();
                }
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null) {
                    List<PointData> snapList = JsonObjectHelper.phrasePointData(jsonArray, point.getNemCode());
                    List<PointData> resultList = new ArrayList<>();

                    if(snapList.isEmpty())
                    {
//                        for (PointData snapItem : resultList) {
//                            snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                        }
                        getHistsnapSameTiem(point.getNemCode(), beginDate, pried, resultList);
                    }else
                    {

                        resultList=snapList;
//                        for (PointData snapItem : snapList) {
//
//                            long subTime = snapItem.getPointTime() - pried;
//                            //查询时间区间的截面值(截面值为传入时间节点的上一个最近值，返回时间为值的真实时间)，
//                            // 再进行比较，若截面值的时间戳在以快照时间节点前推一个单位的时间区间中，
//                            // 则代表该时间节点快照有效，否则为0
//                            String rawUrl = baseURL + "/history/section?null=0&tagNames=" + point.getNemCode() + "&ts=" + snapItem.getPointTime() ;
//                            if (point.getNemCode().startsWith("GF-")){
//                                rawUrl = baseURL2 + "/history/section?null=0&tagNames=" + point.getNemCode() + "&ts=" + snapItem.getPointTime() ;
//                            }
//                            ResponseEntity<JSONObject> sectionResp = restTemplate.getForEntity(rawUrl, JSONObject.class);
//                            JSONObject jsonObjectSection = sectionResp.getBody();
//
//                            if (jsonObjectSection != null) {
//                                List<PointData> sectionlist = JsonObjectHelper.phrasePointData(jsonObjectSection);
//                                if (sectionlist.size() > 0) {
//                                    if(sectionlist.get(0).getPointTime()<=snapItem.getPointTime()){
//                                        snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                                        resultList.add(snapItem);
//                                    }
//                                    else{
//                                        PointData data = new PointData();
//                                        data.setEdnaId(point.getNemCode());
//                                        data.setPointTime(snapItem.getPointTime());
//                                        data.setPointValue("0");
//                                        data.setPointName("1");
//                                        data.setPointValueInDouble(0.0);
//                                        resultList.add(data);
//                                    }
//                                } else {
//                                    PointData data = new PointData();
//                                    data.setEdnaId(point.getNemCode());
//                                    data.setPointTime(0l);
//                                    data.setPointValue("0");
//                                    data.setPointName("1");
//                                    data.setPointValueInDouble(0.0);
//                                    resultList.add(data);
//                                }
//                            } else {
//                                PointData data = new PointData();
//                                data.setEdnaId(point.getNemCode());
//                                data.setPointTime(0l);
//                                data.setPointValue("0");
//                                data.setPointName("1");
//                                data.setPointValueInDouble(0.0);
//                                resultList.add(data);
//                            }
//                        }
                    }


                    return resultList;


                } else {
                    return ErrorRequest.RequestListError(point.getNemCode());
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }


    }


    private void getHistsnapSameTiem(String pointid, Long beginDate, Long pried,
                                     List<PointData> resultList) {


        long subTime =beginDate - pried;
        String rawUrl = baseURL + "/history/section?null=0&tagNames=" + pointid + "&ts=" + beginDate ;
        if (pointid.startsWith("GF-")){
            rawUrl = baseURL2 + "/history/section?null=0&tagNames=" + pointid + "&ts=" + beginDate ;
        }

        ResponseEntity<JSONObject> sectionResp = restTemplate.getForEntity(rawUrl, JSONObject.class);
        JSONObject jsonObjectSection = sectionResp.getBody();
        if (jsonObjectSection != null) {
            List<PointData> sectionlist = JsonObjectHelper.phrasePointData(jsonObjectSection);
            if (sectionlist.size() > 0) {
                if(sectionlist.get(0).getPointTime()<=beginDate){
                    resultList.add(sectionlist.get(0));
                }
                else{
                    PointData data = new PointData();
                    data.setEdnaId(pointid);
                    data.setPointTime(sectionlist.get(0).getPointTime());
                    data.setPointValue("0");
                    data.setPointName("1");
                    data.setPointValueInDouble(0.0);
                    resultList.add(data);
                }
            } else {
                PointData data = new PointData();
                data.setEdnaId(pointid);
                data.setPointTime(0l);
                data.setPointValue("0");
                data.setPointName("1");
                data.setPointValueInDouble(0.0);
                resultList.add(data);
            }
        } else {
            PointData data = new PointData();
            data.setEdnaId(pointid);
            data.setPointTime(beginDate);
            data.setPointValue("0");
            data.setPointName("1");
            data.setPointValueInDouble(0.0);
            resultList.add(data);
        }
    }


    @Override
    public List<PointData> getHistoryDatasRaw(ProBasicPowerstationPoint point, Long beginDate, Long endDate) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> tagName = Optional.ofNullable(point.getNemCode());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> uniformCode = Optional.ofNullable(point.getUniformCode());
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);

            try {
                String url = baseURL + "/history/snap?null=0";
                if (point.getNemCode().startsWith("GF-")){
                    url = baseURL2 + "/history/snap?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCode.isPresent())
                        url = url + "&uniformCodes=" + uniformCode.get();
                }

                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null)
                    return JsonObjectHelper.phrasePointData(jsonArray, point.getNemCode());
                else {
                    return ErrorRequest.RequestListError(point.getNemCode());
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }

    @Override
    public PointData getRealData(ProBasicEquipmentPoint point) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> keys = Optional.ofNullable(point.getNemCode());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> uniformCodes = Optional.ofNullable(point.getUniformCode());

            try {
                String url = "";
                if (point.getNemCode().startsWith("GF-")){
                    url = baseURL2 + "/latest?null=0";
                }else {
                    url = baseURL + "/latest?null=0";
                }

                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (keys.isPresent())
                    url = url + "&keys=" + keys.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCodes.isPresent())
                        url = url + "&uniformCodes=" + uniformCodes.get();
                }
                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonArray = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonArray)){
                    List<PointData> list = JsonObjectHelper.phrasePointData(jsonArray);
                    if (list.size() > 0)
                    {
                        PointData po=list.get(0);
                        po.setPointValueInDouble(NumberUtil.round(po.getPointValueInDouble(),4).doubleValue());
                        return po;
                    }
                    else
                    {
                        return ErrorRequest.RequestError(point.getNemCode());
                    }
                } else {
                    return ErrorRequest.RequestError(point.getNemCode());
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            return po;
        }

    }

    @Override
    public List<PointData> getHistoryDatasSnap(ProBasicEquipmentPoint point, Long beginDate, Long endDate, Long count, Long pried) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> tagName = Optional.ofNullable(point.getNemCode());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> uniformCode = Optional.ofNullable(point.getUniformCode());
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);
            //通过时间区间和时间间隔获取点数
            Long finalInterval;
            if (pried != null)
                finalInterval = pried;
            else if (count != null)
                finalInterval = (endDate - beginDate) / count;
            else
                return ErrorRequest.RequestListError(point.getNemCode());
            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));

            try {
                String url ="";
                if (point.getNemCode().startsWith("GF-")){
                    url = baseURL2 + "/history/snap?null=0";
                }else {
                    url = baseURL + "/history/snap?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCode.isPresent())
                        url = url + "&uniformCodes=" + uniformCode.get();
                }
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null) {
                    List<PointData> snapList = JsonObjectHelper.phrasePointData(jsonArray, point.getNemCode());
                    List<PointData> resultList = new ArrayList<>();

                    if(snapList.isEmpty())
                    {
//                        for (PointData snapItem : resultList) {
//                            snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                        }
                        getHistsnapSameTiem(point.getNemCode(), beginDate, pried, resultList);
                    }
                    else
                    {
                        resultList=snapList;

//
//
//                        for (PointData snapItem : snapList) {
//                            long subTime = snapItem.getPointTime() - pried;
//                            //查询时间区间的截面值(截面值为传入时间节点的上一个最近值，返回时间为值的真实时间)，
//                            // 再进行比较，若截面值的时间戳在以快照时间节点前推一个单位的时间区间中，
//                            // 则代表该时间节点快照有效，否则为0
//
//                            String rawUrl = baseURL + "/history/section?null=0&tagNames=" + point.getNemCode() + "&ts=" + snapItem.getPointTime() ;
//                             if (point.getNemCode().startsWith("GF-")){
//                                rawUrl = baseURL2 + "/history/section?null=0&tagNames=" + point.getNemCode() + "&ts=" + snapItem.getPointTime() ;
//                            }
//
//                            ResponseEntity<JSONObject> sectionResp = restTemplate.getForEntity(rawUrl, JSONObject.class);
//                            JSONObject jsonObjectSection = sectionResp.getBody();
//
//                            if (jsonObjectSection != null) {
//                                List<PointData> sectionlist = JsonObjectHelper.phrasePointData(jsonObjectSection);
//                                if (sectionlist.size() > 0) {
//                                    if(sectionlist.get(0).getPointTime()<=snapItem.getPointTime()){
//                                        snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                                        resultList.add(snapItem);
//                                    }
//                                    else{
//                                        PointData data = new PointData();
//                                        data.setEdnaId(point.getNemCode());
//                                        data.setPointTime(snapItem.getPointTime());
//                                        data.setPointValue("0");
//                                        data.setPointName("1");
//                                        data.setPointValueInDouble(0.0);
//                                        resultList.add(data);
//                                    }
//                                } else {
//                                    PointData data = new PointData();
//                                    data.setEdnaId(point.getNemCode());
//                                    data.setPointTime(0l);
//                                    data.setPointValue("0");
//                                    data.setPointName("1");
//                                    data.setPointValueInDouble(0.0);
//                                    resultList.add(data);
//                                }
//                            } else {
//                                PointData data = new PointData();
//                                data.setEdnaId(point.getNemCode());
//                                data.setPointTime(0l);
//                                data.setPointValue("0");
//                                data.setPointName("1");
//                                data.setPointValueInDouble(0.0);
//                                resultList.add(data);
//                            }
//                        }
                    }


                    return resultList;
                } else {
                    return ErrorRequest.RequestListError(point.getNemCode());
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }





    @Override
    public List<PointData> getHistoryDatasRaw(ProBasicEquipmentPoint point, Long beginDate, Long endDate) throws Exception {
        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> tagName = Optional.ofNullable(point.getNemCode());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> uniformCode = Optional.ofNullable(point.getUniformCode());
            Optional<Long> startTs = Optional.ofNullable(beginDate);
            Optional<Long> endTs = Optional.ofNullable(endDate);
            try {
                String url = "";
                if (point.getNemCode().startsWith("GF-")){
                    url = baseURL2 + "/history/snap?null=0";
                }else {
                    url = baseURL + "/history/snap?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCode.isPresent())
                        url = url + "&uniformCodes=" + uniformCode.get();
                }

                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null)
                    return JsonObjectHelper.phrasePointData(jsonArray, point.getNemCode());
                else {
                    return ErrorRequest.RequestListError(point.getNemCode());
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }

    @Override
    public PointData getRealData(String pointid) throws Exception {

        if(ObjectUtil.isNotEmpty(pointid) &&  !initialcode.equals(pointid))
        {
            Optional<String> keys = Optional.ofNullable(pointid);
            String url = baseURL + "/latest?null=0";
            if (pointid.startsWith("GF-")){
                url = baseURL2 + "/latest?null=0";
            }

            try {
                if (keys.isPresent())
                    url = url + "&keys=" + keys.get();
                else
                    return null;

                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonArray = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonArray)){
                    List<PointData> list = JsonObjectHelper.phrasePointData(jsonArray);
                    if (list.size() > 0)
                    {
                        PointData po=list.get(0);
                        po.setPointValueInDouble(NumberUtil.round(po.getPointValueInDouble(),4).doubleValue());
                        return po;
                    }
                    else
                    {
                        return ErrorRequest.RequestError(pointid);
                    }
                } else {
                    return ErrorRequest.RequestError(pointid);
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestError(pointid);
                } else {
                    return ErrorRequest.RequestError(pointid);
                }
            }
        }else
        {
            PointData po=new PointData();
            po.setEdnaId(pointid);
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            return po;
        }

    }

    @Override
    public List<PointData> getRealData(String... pointids) throws Exception {


        String pointIdString = StringUtil.join(pointids, ",");
        Optional<String> keys = Optional.ofNullable(pointIdString);
        String url = baseURL + "/latest?null=0";
        if (pointIdString.startsWith("GF-")){
            url = baseURL2 + "/latest?null=0";
        }
        try {
            if (keys.isPresent())
                url = url + "&keys=" + keys.get();
            else {
                return ErrorRequest.RequestListError(pointids);
            }
            ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
            JSONObject jsonObject = resp.getBody();
            if (jsonObject != null) {
                //对结果进行有序返回
                int len = pointids.length;
                List<PointData> result = new ArrayList<>();
                HashMap<String, PointData> pointDataHashMap = new HashMap<>();
                for (int i = 0; i < len; i++) {

                    if (pointDataHashMap.containsKey(pointids[i]) == false){
                        PointData pd = new PointData();
                        pd.setPointName(pointids[i]);
                        pd.setEdnaId(pointids[i]);
                        result.add(pd);

                        pointDataHashMap.put(pd.getPointName(), pd);
                    }
                    else{
                        result.add(pointDataHashMap.get(pointids[i]));
                    }

                }
                Iterator<String> sIterator = jsonObject.keySet().iterator();
                while (sIterator.hasNext()) {
                    // 获得key
                    String key = sIterator.next();
                    PointData pointData = pointDataHashMap.get(key);
                    if (pointData == null)
                        continue;
                    // 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
                    JSONObject jsonData = jsonObject.getJSONObject(key);
                    Long ts = jsonData.getLong("ts");
                    String pointValue = null;
                    if (jsonData.containsKey("doubleValue")) {
                        pointValue = jsonData.getString("doubleValue");
                    } else if (jsonData.containsKey("booleanValue")) {
                        pointValue = jsonData.getString("booleanValue");
                    } else if (jsonData.containsKey("longValue")) {
                        pointValue = jsonData.getString("longValue");
                    } else if (jsonData.containsKey("stringValue")) {
                        pointValue = jsonData.getString("stringValue");
                    }
//                    pointData.setPointValue(pointValue);
//                    pointData.setPointValueInDouble(Double.parseDouble(pointValue));

                    if(pointValue.equals("true"))
                    {
                        pointData.setPointValueInDouble(1.0);
                    }else if(pointValue.equals("false"))
                    {
                        pointData.setPointValueInDouble(0.0);
                    }else
                    {
                        double value=Double.parseDouble(pointValue);
                        pointData.setPointValueInDouble(NumberUtil.round(value,4).doubleValue());
                    }


                    pointData.setPointValue(pointValue);
                    // //System.out.println("key= " + key + ", ts = " + ts + ", value = " + pointValue);
                }
                return result;

            } else {
                return ErrorRequest.RequestListError(pointids);
            }

        } catch (HttpClientErrorException exception) {
            if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                //System.out.println("404请求错误");
                return ErrorRequest.RequestListError(pointids);
            } else {
                throw exception;
            }
        }


    }



    @Override
    public List<PointData> getRealData(List<String> pointids) throws Exception {


        String pointIdString = StringUtil.join(pointids.toArray(), ",");
        Optional<String> keys = Optional.ofNullable(pointIdString);
        String url = baseURL + "/latest?null=0";
        if (pointIdString.startsWith("GF-")){
            url = baseURL2 + "/latest?null=0";
        }
        try {
            if (keys.isPresent())
                url = url + "&keys=" + keys.get();
            else {
                String[] arr = new String[pointids.size()];
                return ErrorRequest.RequestListError(pointids.toArray(arr));
            }

            ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
            JSONObject jsonObject = resp.getBody();
            if (jsonObject != null) {


                //对结果进行有序返回
                int len = pointids.size();
                List<PointData> result = new ArrayList<>();
                HashMap<String, PointData> pointDataHashMap = new HashMap<>();
                for (int i = 0; i < len; i++) {
                    if (pointDataHashMap.containsKey(pointids.get(i)) == false){
                        PointData pd = new PointData();
                        pd.setPointName(pointids.get(i));
                        pd.setEdnaId(pointids.get(i));
                        result.add(pd);

                        pointDataHashMap.put(pd.getPointName(), pd);
                    }
                    else{
                        result.add(pointDataHashMap.get(pointids.get(i)));
                    }
                }
                Iterator<String> sIterator = jsonObject.keySet().iterator();
                while (sIterator.hasNext()) {
                    // 获得key
                    String key = sIterator.next();
                    PointData pointData = pointDataHashMap.get(key);
                    if (pointData == null)
                        continue;
                    // 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
                    JSONObject jsonData = jsonObject.getJSONObject(key);
                    Long ts = jsonData.getLong("ts");
                    String pointValue = null;
                    if (jsonData.containsKey("doubleValue")) {
                        pointValue = jsonData.getString("doubleValue");
                    } else if (jsonData.containsKey("booleanValue")) {
                        pointValue = jsonData.getString("booleanValue");
                    } else if (jsonData.containsKey("longValue")) {
                        pointValue = jsonData.getString("longValue");
                    } else if (jsonData.containsKey("stringValue")) {
                        pointValue = jsonData.getString("stringValue");
                    }
                    if(pointValue.equals("true"))
                    {
                        pointData.setPointValueInDouble(1.0);
                    }else if(pointValue.equals("false"))
                    {
                        pointData.setPointValueInDouble(0.0);
                    }else
                    {
                        double value=Double.parseDouble(pointValue);
                        pointData.setPointValueInDouble(NumberUtil.round(value,4).doubleValue());
                    }
                    pointData.setPointValue(pointValue);
                    pointData.setPointTime(ts);
                    //  //System.out.println("key= " + key + ", ts = " + ts + ", value = " + pointValue);
                }
                return result;

            } else {
                String[] arr = new String[pointids.size()];
                return ErrorRequest.RequestListError(pointids.toArray(arr));
            }

        } catch (HttpClientErrorException exception) {
            if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                //System.out.println("404请求错误");
                String[] arr = new String[pointids.size()];
                return ErrorRequest.RequestListError(pointids.toArray(arr));
            } else {
                throw exception;
            }
        }

    }

    @Override
    public Map<String, Double> getRealDataMap(String... pointids) throws Exception {


        if(ObjectUtil.isNotEmpty(pointids) )
        {
            List<String> idls=new ArrayList<>();
            for(String str:pointids)
            {
                if(ObjectUtil.isNotEmpty(str) && !initialcode.equals(str))
                {
                    idls.add(str);
                }
            }
            if(!idls.isEmpty()  )
            {
                String pointIdString = StringUtil.join(pointids, ",");
                Optional<String> keys = Optional.ofNullable(pointIdString);
                String url = baseURL + "/latest?null=0";
                if (pointIdString.startsWith("GF-")){
                    url = baseURL2 + "/latest?null=0";
                }
                try {
                    if (keys.isPresent())
                        url = url + "&keys=" + keys.get();
                    else
                        return null;
                    ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                    JSONObject jsonArray = resp.getBody();
                    if (ObjectUtil.isNotEmpty(jsonArray)){
                        Iterator<String> sIterator = jsonArray.keySet().iterator();
                        Map<String, Double> resultMap = new HashMap();
                        while (sIterator.hasNext()) {
                            // 获得key
                            String key = sIterator.next();
                            // 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
                            JSONObject jsonData = jsonArray.getJSONObject(key);
                            Long ts = jsonData.getLong("ts");
                            String pointValue = null;
                            if (jsonData.containsKey("doubleValue")) {
                                pointValue = jsonData.getString("doubleValue");
                            } else if (jsonData.containsKey("booleanValue")) {
                                pointValue = jsonData.getString("booleanValue");
                            } else if (jsonData.containsKey("longValue")) {
                                pointValue = jsonData.getString("longValue");
                            } else if (jsonData.containsKey("stringValue")) {
                                pointValue = jsonData.getString("stringValue");
                            }
                            resultMap.put(key, Double.parseDouble(pointValue));
                        }
                        return resultMap;

                    } else
                        return ErrorRequest.RequestMapError();
                } catch (HttpClientErrorException exception) {
                    if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                        //System.out.println("404请求错误");
                        return ErrorRequest.RequestMapError();
                    } else {
                        throw exception;
                    }
                }
            }else
            {
                Map<String, Double> map=new HashMap<>();
                for(String str:pointids)
                {

                    map.put(str, 0.0);

                }
                return map;
            }
        }else
        {

            Map<String, Double> map=new HashMap<>();

            for(String str:pointids)
            {

                map.put(str, 0.0);

            }
            return map;
        }

    }


    @Override
    public List<PointData> getHistoryDatasSnap(String pointid, Long beginDate, Long endDate, Long count, Long pried) throws Exception {

        if(ObjectUtil.isNotEmpty(pointid) &&  !initialcode.equals(pointid))
        {
            Optional<String> tagName = Optional.ofNullable(pointid);
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);

            //通过时间区间和时间间隔获取点数
            Long finalInterval;
            if (pried != null)
                finalInterval = pried;
            else if (count != null)
                finalInterval = (endDate - beginDate) / count;
            else
                return ErrorRequest.RequestListError(pointid);
            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));

            try {
                String url = baseURL + "/history/snap?null=0";
                if (pointid.startsWith("GF-")){
                    url = baseURL2 + "/history/snap?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();

                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null) {
                    List<PointData> list = JsonObjectHelper.phrasePointData(jsonArray,tagName.get());
                    List<PointData> resultList = new ArrayList<>();

                    if(list.isEmpty())
                    {
//                        for (PointData snapItem : resultList) {
//                            snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                        }
                        getHistsnapSameTiem(pointid, beginDate, pried, resultList);
                    }
                    else
                    {
                        resultList=list;

//
//
//                        for (PointData snapItem : snapList) {
//                            long subTime = snapItem.getPointTime() - pried;
//                            //查询时间区间的截面值(截面值为传入时间节点的上一个最近值，返回时间为值的真实时间)，
//                            // 再进行比较，若截面值的时间戳在以快照时间节点前推一个单位的时间区间中，
//                            // 则代表该时间节点快照有效，否则为0
//
//                            String rawUrl = baseURL + "/history/section?null=0&tagNames=" + point.getNemCode() + "&ts=" + snapItem.getPointTime() ;
//                             if (point.getNemCode().startsWith("GF-")){
//                                rawUrl = baseURL2 + "/history/section?null=0&tagNames=" + point.getNemCode() + "&ts=" + snapItem.getPointTime() ;
//                            }
//
//                            ResponseEntity<JSONObject> sectionResp = restTemplate.getForEntity(rawUrl, JSONObject.class);
//                            JSONObject jsonObjectSection = sectionResp.getBody();
//
//                            if (jsonObjectSection != null) {
//                                List<PointData> sectionlist = JsonObjectHelper.phrasePointData(jsonObjectSection);
//                                if (sectionlist.size() > 0) {
//                                    if(sectionlist.get(0).getPointTime()<=snapItem.getPointTime()){
//                                        snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                                        resultList.add(snapItem);
//                                    }
//                                    else{
//                                        PointData data = new PointData();
//                                        data.setEdnaId(point.getNemCode());
//                                        data.setPointTime(snapItem.getPointTime());
//                                        data.setPointValue("0");
//                                        data.setPointName("1");
//                                        data.setPointValueInDouble(0.0);
//                                        resultList.add(data);
//                                    }
//                                } else {
//                                    PointData data = new PointData();
//                                    data.setEdnaId(point.getNemCode());
//                                    data.setPointTime(0l);
//                                    data.setPointValue("0");
//                                    data.setPointName("1");
//                                    data.setPointValueInDouble(0.0);
//                                    resultList.add(data);
//                                }
//                            } else {
//                                PointData data = new PointData();
//                                data.setEdnaId(point.getNemCode());
//                                data.setPointTime(0l);
//                                data.setPointValue("0");
//                                data.setPointName("1");
//                                data.setPointValueInDouble(0.0);
//                                resultList.add(data);
//                            }
//                        }
                    }


                    return resultList;
                } else {
                    return ErrorRequest.RequestListError(pointid);
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(pointid);
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(pointid);
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }


    }


    @Override
    public List<PointData> getHistoryDatasRaw(String pointid, Long beginDate, Long endDate) throws Exception {


        if(ObjectUtil.isNotEmpty(pointid) &&  !initialcode.equals(pointid))
        {
            Optional<String> tagName = Optional.ofNullable(pointid);
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);

            try {

                String url = baseURL + "/history/raw?null=0";
                if (pointid.startsWith("GF-")){
                    url = baseURL2 + "/history/raw?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);

                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null)
                    return JsonObjectHelper.phrasePointData(jsonArray, pointid);
                else {
                    return ErrorRequest.RequestListError(pointid);
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(pointid);
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(pointid);
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }

    @Override
    public List<PointData> getHistStat(ProBasicEquipmentPoint point, Long beginDate, Long endDate, Long count, Long pried, int type) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> tagName = Optional.ofNullable(point.getNemCode());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> uniformCode = Optional.ofNullable(point.getUniformCode());
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);

//        Calendar cal = Calendar.getInstance();
//        cal.setTime(new Date(startTs.get()));
//        cal.add(Calendar.SECOND, -pried.intValue());
//        startTs= Optional.ofNullable(cal.getTime().getTime());
//        count++;

            //通过时间区间和时间间隔获取点数
            Long finalInterval;
            if (pried != null)
                finalInterval = pried;
            else if (count != null)
                finalInterval = (endDate - beginDate) / count;
            else
                return ErrorRequest.RequestListError(point.getNemCode());
            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));

            try {
                String url = "";
                 if (point.getNemCode().startsWith("GF-")){
                    url = baseURL2 + "/history/stat?null=0";
                }else {
                    url = baseURL + "/history/stat?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCode.isPresent())
                        url = url + "&uniformCodes=" + uniformCode.get();
                }
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null)
                    return JsonObjectHelper.GeneralTsDataToPointDataByStat(jsonArray, point.getNemCode(), type);
                else {
                    return ErrorRequest.RequestListError(point.getNemCode());
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }

    @Override
    public List<PointData> getHistStat(ProBasicPowerstationPoint point, Long beginDate, Long endDate, Long count, Long pried, int type) throws Exception {

        if(ObjectUtil.isNotEmpty(point) && ObjectUtil.isNotEmpty(point.getNemCode()) && !initialcode.equals(point.getNemCode()))
        {
            Optional<String> tagName = Optional.ofNullable(point.getNemCode());
            Optional<String> thingId = Optional.ofNullable(point.getWindpowerstationId());
            Optional<String> thingType = Optional.ofNullable(point.getModelId());
            Optional<String> uniformCode = Optional.ofNullable(point.getUniformCode());
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);
            //通过时间区间和时间间隔获取点数
            Long finalInterval;
            if (pried != null)
                finalInterval = pried;
            else if (count != null)
                finalInterval = (endDate - beginDate) / count;
            else
                return ErrorRequest.RequestListError(point.getNemCode());
            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));

            try {
                String url = baseURL + "/history/stat?null=0";
                if (point.getNemCode().startsWith("GF-")){
                    url = baseURL2 + "/history/stat?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                else {
                    if (thingType.isPresent())
                        url = url + "&thingType=" + thingType.get();
                    if (thingId.isPresent())
                        url = url + "&thingId=" + thingId.get();
                    if (uniformCode.isPresent())
                        url = url + "&uniformCodes=" + uniformCode.get();
                }
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null)
                    return JsonObjectHelper.GeneralTsDataToPointDataByStat(jsonArray, point.getNemCode(), type);
                else {
                    return ErrorRequest.RequestListError(point.getNemCode());
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(point.getNemCode());
                } else {
                    throw exception;
                }
            }
        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(point.getNemCode());
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }

    @Override
    public List<PointData> getHistStat(String pointid, Long beginDate, Long endDate, Long count, Long pried, int type) throws Exception {


        if(ObjectUtil.isNotEmpty(pointid) &&  !initialcode.equals(pointid))
        {
            Optional<String> tagName = Optional.ofNullable(pointid);
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);
            //通过时间区间和时间间隔获取点数
            Long finalInterval;
            if (count != null)
                finalInterval = (endDate - beginDate) / count;
            else if (pried != null)
                finalInterval = pried;
            else
                return null;
            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));
            try {
                String url = baseURL + "/history/stat?null=0";
                if (pointid.startsWith("GF-")){
                    url = baseURL2 + "/history/stat?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null)
                    return JsonObjectHelper.GeneralTsDataToPointDataByStat(jsonArray, pointid, type);
                else {
                    return ErrorRequest.RequestListError(pointid);
                }
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(pointid);
                } else {
                    throw exception;
                }
            }

        }else
        {
            List<PointData> pols=new ArrayList<>();
            PointData po=new PointData();
            po.setEdnaId(pointid);
            po.setPointValueInDouble(0.0);
            po.setPointTime(0l);
            pols.add(po);
            return pols;
        }

    }

    @Override
    public DNAStatVal[] getHistStat(String point, Long beginDate, Long endDate, Integer pried) throws Exception {


        if(ObjectUtil.isNotEmpty(point) &&  !initialcode.equals(point))
        {
            Optional<String> tagName = Optional.ofNullable(point);
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);
            //通过时间区间和时间间隔获取点数
            Optional<Integer> interval = Optional.ofNullable(pried);

            try {
                String url = baseURL + "/history/stat?null=0";
                if (point.startsWith("GF-")){
                    url = baseURL2 + "/history/stat?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();
                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=" + interval.get();

                ////System.out.println(restTemplate.getForEntity(url, JSONArray.class));
                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                if (resp != null) {
                    JSONArray jsonArray = resp.getBody();
                    if (jsonArray == null || jsonArray.size() <= 0) {
                        DNAStatVal[] dnaVal = new DNAStatVal[1];
                        DNAVal errorData = new DNAVal();
                        errorData.Status = 0;

                        DNAStatVal val = new DNAStatVal();
                        val.avg = errorData;
                        val.max = errorData;
                        val.min = errorData;
                        dnaVal[0] = val;
                        return dnaVal;
                    } else {
                        return JsonObjectHelper.phraseDNAVal(jsonArray);
                    }
                } else {
                    return null;
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    //System.out.println("404请求错误");
                    DNAStatVal val = new DNAStatVal();
                    DNAStatVal[] dnaVal = new DNAStatVal[1];
                    DNAVal errorData = new DNAVal();
                    errorData.Status = 0;
                    val.avg = errorData;
                    val.max = errorData;
                    val.min = errorData;
                    dnaVal[0] = val;
                    return dnaVal;

                } else {
                    DNAStatVal val = new DNAStatVal();
                    DNAStatVal[] dnaVal = new DNAStatVal[1];
                    DNAVal errorData = new DNAVal();
                    errorData.Status = 0;
                    val.avg = errorData;
                    val.max = errorData;
                    val.min = errorData;
                    dnaVal[0] = val;
                    return dnaVal;
                }
            }
        }else
        {
            DNAStatVal val = new DNAStatVal();
            DNAStatVal[] dnaVal = new DNAStatVal[1];
            DNAVal errorData = new DNAVal();
            errorData.Status = 0;
            val.avg = errorData;
            val.max = errorData;
            val.min = errorData;
            dnaVal[0] = val;
            return dnaVal;
        }


    }

    private JSONObject convertPointData(PointData pd) {
        JSONObject jo = new JSONObject();
        jo.put("tagName", pd.getEdnaId());
        JSONObject joo = new JSONObject();
        joo.put("ts", pd.getPointTime());
        joo.put("status", 0);
        joo.put("doubleValue", pd.getPointValueInDouble());
        jo.put("tsData", joo);
        return jo;
    }

    @Override
    public void updatePoint(PointData point) throws Exception {
        String url = baseURL + "/history";
        if (point.getEdnaId().startsWith("GF-")){
            url = baseURL2 + "/history";
        }
        try {
            String result = restTemplate.postForObject(url, convertPointData(point), String.class);
        } catch (HttpClientErrorException exception) {
            if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                return;
            } else {
                throw exception;
            }
        }
    }

    @Override
    public DNAVal[] getRealtimeTagValues(String... tagNames) throws Exception {


        if (ObjectUtil.isNotEmpty(tagNames) && tagNames.length > 0) {


            DNAVal[] result = new DNAVal[tagNames.length];
            for (int i = 0; i < tagNames.length; i++) {
                if (ObjectUtil.isNotEmpty(tagNames[i]) && !initialcode.equals(tagNames[i])) {
                    PointData po = getRealData(tagNames[i]);
                    DNAVal val = new DNAVal();
                    val.DValue = po.getPointValueInDouble();
                    if(ObjectUtil.isNotEmpty(po.getPointTime()))
                    {
                        val.Time = Integer.valueOf(String.valueOf(po.getPointTime()));
                    }else
                    {
                        val.Time = 0;
                    }

                    val.Status = 1;
                    result[i] = val;
                } else {
                    DNAVal val = new DNAVal();
                    val.Status = 0;
                    result[i] = val;
                }

            }
            return result;
        } else {
            DNAVal[] result = new DNAVal[tagNames.length];
            for (int i = 0; i < tagNames.length; i++) {
                DNAVal val = new DNAVal();
                val.Status = 0;
                result[i] = val;

            }
            return result;
        }

    }

    @Override
    public void updatePoint(List<PointData> pointls) throws Exception {
        String url = baseURL + "/history/batch";
        if (!pointls.isEmpty() ) {

            if (pointls.get(0).getEdnaId().startsWith("GF-")) {
                url = baseURL2 + "/history/batch";
            }
        }

        List<JSONObject> writeList = new ArrayList<>();

        int batchSize = 500; // 设置每次传输的批次大小

        int totalSize = pointls.size();
        int batchCount = totalSize % batchSize == 0 ? totalSize / batchSize : totalSize / batchSize + 1;

        for (int i = 0; i < batchCount; i++) {
            int startIndex = i * batchSize;
            int endIndex = Math.min((i + 1) * batchSize, totalSize);
            List<PointData> batch = pointls.subList(startIndex, endIndex);

            List<JSONObject> batchWriteList = new ArrayList<>();
            for (PointData entity : batch) {
                batchWriteList.add(convertPointData(entity));
            }

            try {
                String result = restTemplate.postForObject(url, batchWriteList, String.class);
                // 处理返回的结果
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    throw new Exception("404请求错误");
                } else {
                    throw exception;
                }
            }
        }
    }

    @Override
    public void sendSinglePoint(PointData point) throws Exception {
        String url = baseURL + "/latest";

        if (point.getEdnaId().startsWith("GF-")){
            url = baseURL2 + "/latest";
        }
        try {
            String result = restTemplate.postForObject(url, convertPointData(point), String.class);
        } catch (HttpClientErrorException exception) {
            if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                return;
            } else {
                throw exception;
            }
        }
    }

    @Override
    public void sendMultiPoint(List<PointData> pointls) throws Exception {

        String url = baseURL + "/latest/batch";

        if (!pointls.isEmpty() ){

            if (pointls.get(0).getEdnaId().startsWith("GF-")){
                url = baseURL2 + "/latest/batch";
            }

            List<JSONObject> writeList = new ArrayList<>();

            int batchSize = 500; // 设置每次传输的批次大小

            int totalSize = pointls.size();
            int batchCount = totalSize % batchSize == 0 ? totalSize / batchSize : totalSize / batchSize + 1;

            for (int i = 0; i < batchCount; i++) {
                int startIndex = i * batchSize;
                int endIndex = Math.min((i + 1) * batchSize, totalSize);
                List<PointData> batch = pointls.subList(startIndex, endIndex);

                List<JSONObject> batchWriteList = new ArrayList<>();
                for (PointData entity : batch) {
                    batchWriteList.add(convertPointData(entity));
                }

                try {
                    String result = restTemplate.postForObject(url, batchWriteList, String.class);
                    // 处理返回的结果
                } catch (HttpClientErrorException exception) {
                    if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                        throw new Exception("404请求错误");
                    } else {
                        throw exception;
                    }
                }
            }
        }

    }

    @Override
    public void sendMultiPoint(String[] realvalue, DNAVal[] pointls) throws Exception {
        String url = baseURL + "/latest/batch";

        List<JSONObject> writeDataList = new ArrayList<>();
        if (realvalue != null && pointls != null & realvalue.length == pointls.length) {
            for (int i = 0; i < realvalue.length; i++) {
                PointData writeData = new PointData();
                writeData.setEdnaId(realvalue[i]);
                writeData.setPointValueInDouble(pointls[i].DValue);
                writeData.setPointTime((long)pointls[i].Time);
                JSONObject jsonObject=convertPointData(writeData);
                writeDataList.add(jsonObject);
            }

            try {
                String result = restTemplate.postForObject(url, writeDataList, String.class);
            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    System.out.println("404请求错误");
                } else {
                    throw exception;
                }
            }
        } else
            return;
    }


    @Override
    public DNAVal[] getHistMatrix(String[] nameList, int tTime) throws Exception {
        if(ObjectUtil.isNotEmpty(nameList) )
        {
            List<String> idls=new ArrayList<>();
            for(String str:nameList)
            {
                if(ObjectUtil.isNotEmpty(str) && !initialcode.equals(str))
                {
                    idls.add(str);
                }
            }
            if(!idls.isEmpty()  && idls.size()==nameList.length)
            {
                String tagNameString = StringUtil.join(nameList, ",");
                Long time = Long.valueOf(tTime);
                Optional<String> tagName = Optional.ofNullable(tagNameString);
                Optional<Long> ts = Optional.ofNullable(time * 1000);
                String url = baseURL + "/history/section?tagNames=" + tagName.get() + "&ts=" + ts.get();
                try {
                    ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                    JSONObject jsonObject = resp.getBody();
                    if (ObjectUtil.isNotEmpty(jsonObject) && !jsonObject.isEmpty())
                    {
                        return JsonObjectHelper.phraseDNAVal(jsonObject,nameList);
                    }
                    else {
                        DNAVal[] errorResult = new DNAVal[nameList.length];
                        for(int i=0;i<nameList.length;i++)
                        {
                            DNAVal val = new DNAVal();
                            val.Status = 0;
                            errorResult[i] = val;
                        }
                        return errorResult;
                    }
                } catch (Exception e) {
                    DNAVal[] errorResult = new DNAVal[nameList.length];
                    for(int i=0;i<nameList.length;i++)
                    {
                        DNAVal val = new DNAVal();
                        val.Status = 0;
                        errorResult[i] = val;
                    }
                    return errorResult;
                }
            }else
            {

                DNAVal[] errorResult = new DNAVal[nameList.length];
                for(int i=0;i<nameList.length;i++)
                {
                    DNAVal val = new DNAVal();
                    val.Status = 0;
                    errorResult[i] = val;
                }
                return errorResult;
            }
        }else
        {

            DNAVal[] errorResult = new DNAVal[nameList.length];
            for(int i=0;i<nameList.length;i++)
            {
                DNAVal val = new DNAVal();
                val.Status = 0;
                errorResult[i] = val;
            }
            return errorResult;
        }


    }

    @Override
    public void sendMultiRealTimeParamete(List<RealTimeParameterVo> pointls) throws Exception {


        String url = baseURL + "/latest/batch";
        List<JSONObject> writeList = new ArrayList<>();

        for (RealTimeParameterVo entity : pointls) {
            writeList.add(convertRealTimeParamete(entity));
        }
        try {
            String result = restTemplate.postForObject(url, writeList, String.class);
        } catch (HttpClientErrorException exception) {
            if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                System.out.println("404请求错误");
            } else {
                throw exception;
            }
        }
    }

    private JSONObject convertRealTimeParamete(RealTimeParameterVo pd) {
        JSONObject jo = new JSONObject();
        jo.put("tagName", pd.getPoint());
        JSONObject joo = new JSONObject();
        joo.put("ts", pd.getTime().getTime());
        joo.put("status", 0);
        joo.put("doubleValue", pd.getInsertValue());
        jo.put("tsData", joo);
        return jo;
    }


    @Override
    public List<PointData> getHistoryDatasSnap(String pointid, Long beginDate, Long endDate) throws Exception {


        if (ObjectUtil.isNotEmpty(pointid) && !initialcode.equals(pointid)) {
            Optional<String> tagName = Optional.ofNullable(pointid);
            Optional<Long> startTs = Optional.ofNullable(beginDate * 1000);
            Optional<Long> endTs = Optional.ofNullable(endDate * 1000);

            //通过时间区间和时间间隔获取点数
            Long finalInterval=60l;

            Optional<Integer> interval = Optional.ofNullable(Integer.parseInt(finalInterval.toString()));

            try {
                String url = baseURL + "/history/snap?null=0";
                if (pointid.startsWith("GF-")){
                    url = baseURL2 + "/history/snap?null=0";
                }
                //tagName 或thingType，thingId，uniformCode可以确定一个标签点
                if (tagName.isPresent())
                    url = url + "&tagName=" + tagName.get();

                if (startTs.isPresent())
                    url = url + "&startTs=" + startTs.get();
                if (endTs.isPresent())
                    url = url + "&endTs=" + endTs.get();
                if (interval.isPresent())
                    url = url + "&interval=60" ;


                ResponseEntity<JSONArray> resp = restTemplate.getForEntity(url, JSONArray.class);
                JSONArray jsonArray = resp.getBody();
                if (jsonArray != null) {
                    List<PointData> resultList = JsonObjectHelper.phrasePointData(jsonArray,tagName.get());
//                    List<PointData> resultList = new ArrayList<>();

                    if(resultList.isEmpty())
                    {
//                        for (PointData snapItem : resultList) {
//                            snapItem.setPointValueInDouble(NumberUtil.round(snapItem.getPointValueInDouble(),4));
//                        }
                        getHistsnapSameTiem(pointid, beginDate, finalInterval, resultList);
                    }else
                    {
//                        for (PointData snapItem : list) {
//                            long subTime = snapItem.getPointTime() - finalInterval;
//                            //查询时间区间的截面值(截面值为传入时间节点的上一个最近值，返回时间为值的真实时间)，
//                            // 再进行比较，若截面值的时间戳在以快照时间节点前推一个单位的时间区间中，
//                            // 则代表该时间节点快照有效，否则为0
//                            String rawUrl = baseURL + "/history/section?null=0&tagNames=" +pointid+ "&ts=" + snapItem.getPointTime() ;
//                            ResponseEntity<JSONObject> sectionResp = restTemplate.getForEntity(rawUrl, JSONObject.class);
//                            JSONObject jsonObjectSection = sectionResp.getBody();
//
//                            if (jsonObjectSection != null) {
//                                List<PointData> sectionlist = JsonObjectHelper.phrasePointData(jsonObjectSection);
//                                if (sectionlist.size() > 0) {
//                                    if(sectionlist.get(0).getPointTime()<=snapItem.getPointTime()){
//                                        resultList.add(snapItem);
//                                    }
//                                    else{
//                                        PointData data = new PointData();
//                                        data.setEdnaId(pointid);
//                                        data.setPointTime(snapItem.getPointTime());
//                                        data.setPointValue("0");
//                                        data.setPointName("1");
//                                        data.setPointValueInDouble(0.0);
//                                        resultList.add(data);
//                                    }
//                                } else {
//                                    PointData data = new PointData();
//                                    data.setEdnaId(pointid);
//                                    data.setPointTime(snapItem.getPointTime());
//                                    data.setPointValue("0");
//                                    data.setPointName("1");
//                                    data.setPointValueInDouble(0.0);
//                                    resultList.add(data);
//                                }
//                            } else {
//                                PointData data = new PointData();
//                                data.setEdnaId(pointid);
//                                data.setPointTime(snapItem.getPointTime());
//                                data.setPointValue("0");
//                                data.setPointName("1");
//                                data.setPointValueInDouble(0.0);
//                                resultList.add(data);
//                            }
//                        }
                    }

                    return resultList;
                } else {
                    return ErrorRequest.RequestListError(pointid);
                }

            } catch (HttpClientErrorException exception) {
                if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
                    System.out.println("404请求错误");
                    return ErrorRequest.RequestListError(pointid);
                } else {
                    throw exception;
                }
            }
        } else
        {
            return  new ArrayList<>();
        }


    }



    //多点切面数据


    @Override
    public List<PointData> getHistMatrix(List<String> nameList, long tTime) throws Exception {
        String tagNameString = StringUtil.join(nameList, ",");
        Long time = Long.valueOf(tTime);
        Optional<String> tagName = Optional.ofNullable(tagNameString);
        Optional<Long> ts = Optional.ofNullable(time * 1000);
        String url = baseURL + "/history/section?tagNames=" + tagName.get() + "&ts=" + ts.get();
        if (tagNameString.startsWith("GF-")){
            url = baseURL2 + "/history/section?tagNames=" + tagName.get() + "&ts=" + ts.get();
        }
        try {
            ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
            JSONObject jsonObject = resp.getBody();
            if (ObjectUtil.isNotEmpty(jsonObject) && !jsonObject.isEmpty())
            {
                return JsonObjectHelper.phrasePointData(jsonObject,nameList);
            }
            else {

                return new ArrayList<>();
            }
        } catch (Exception e) {
            DNAVal[] errorResult = new DNAVal[nameList.size()];
            for(int i=0;i<nameList.size();i++)
            {
                DNAVal val = new DNAVal();
                val.Status = 0;
                errorResult[i] = val;
            }
            return new ArrayList<>();
        }
    }

    @Override
    public PointData getHistMatrix(String id, long tTime) throws Exception {

        if(ObjectUtil.isNotEmpty(id) && !id.equals(initialcode))
        {
            String tagNameString = id;
            Long time = Long.valueOf(tTime);
            Optional<String> tagName = Optional.ofNullable(tagNameString);
            Optional<Long> ts = Optional.ofNullable(time * 1000);
            String url = baseURL + "/history/section?tagNames=" + tagName.get() + "&ts=" + ts.get();
            if (id.startsWith("GF-")){
                url = baseURL2 + "/history/section?tagNames=" + tagName.get() + "&ts=" + ts.get();
            }
            try {
                ResponseEntity<JSONObject> resp = restTemplate.getForEntity(url, JSONObject.class);
                JSONObject jsonObject = resp.getBody();
                if (ObjectUtil.isNotEmpty(jsonObject) && !jsonObject.isEmpty())
                {

                    return JsonObjectHelper.phrasePointData(jsonObject,id);
                }
                else {

                    return new PointData();
                }
            } catch (Exception e) {

                return new PointData();
            }
        }
        else {

            PointData data = new PointData();
            data.setEdnaId(id);
            data.setPointTime(tTime);
            data.setPointValue("0");
            data.setPointName("1");
            data.setPointValueInDouble(0.0);
            return  data;
        }

    }


}
