package com.yeejoin.equipmanage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.equipmanage.common.datasync.vo.RequestVo;
import com.yeejoin.equipmanage.common.utils.HttpContentTypeUtil;
import com.yeejoin.equipmanage.utils.DcsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class NrApiInvocationImpl {

    @Value("${dcs.x.hw.id}")
    private String xHwId;

    @Value("${dcs.x.hw.appKey}")
    private String xHwAppKey;

    @Autowired
    private DcsUtil dcsUtil;

    @Value("${dcs.url.realtime.key}")
    private String realtimeKey;

    @Value("${dcs.url.yxfs.key}")
    private String yxfsKey;

    @Value("${operation.date}")
    private String operationDate;

    @Value("${dcs.url.realtime.datatype}")
    private String datatype;
    @Value("${dcs.url.realtime}")
    private String realtimeUrl;

    private final Logger logger = LoggerFactory.getLogger(NrApiInvocationImpl.class);


    public JSONArray getNrRealTime() throws Exception {


        String authorization = dcsUtil.getDcsToken();
        JSONArray objects = new JSONArray();
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", authorization);
        headerMap.put("token", authorization.split(" ")[1]);
        headerMap.put("X-HW-ID", xHwId);
        headerMap.put("X-HW-APPKEY", xHwAppKey);
        if (StringUtils.isNotBlank(authorization)) {
            RequestVo requestVo = new RequestVo();
            requestVo.setId(1L);
            requestVo.setClientId("serv-x01");
            Map<String, Object> bodyMap = new HashMap<>();

            bodyMap.put("datatype",datatype);

            bodyMap.put("keys", Arrays.asList(realtimeKey.split(",")));

//                                bodyMap.put("datatype","state");
//                                bodyMap.put("keys", Arrays.asList("3940656019406849",
//                                        "3940656019472385",
//                                        "3940656019537921",
//                                        "3940656019144705",
//                                        "3940656019210241",
//                                        "3940656019275777",
//                                        "3940656019341313"));

            requestVo.setBody(bodyMap);
            logger.info("===============告警存入header:" + JSON.toJSONString(headerMap) + ";\n==================告警存入body: " + JSON.toJSONString(requestVo));
            String data = HttpContentTypeUtil.sendHttpPostJsonWithHeader(realtimeUrl, JSON.toJSONString(requestVo), headerMap);
            bodyMap.put("keys",Arrays.asList(yxfsKey.split(",")));
            requestVo.setBody(bodyMap);

            //String s = "{\"code\":\"2023\",\"id\":1,\"message\":\"获取实时信号值成功\",\"body\":{\"values\":[{\"time_stamp\":\"2025-12-04 15:55:56.000\",\"value\":4417.724609375,\"key\":\"0000YC000101004B14\",\"quality\":0},{\"time_stamp\":\"2025-12-04 15:55:56.000\",\"value\":0.67138671875,\"key\":\"0000YC000101004623\",\"quality\":0},{\"time_stamp\":\"2025-12-04 15:55:41.000\",\"value\":0.79345703125,\"key\":\"0000YC000101004624\",\"quality\":0}]}}";
            logger.info("===============告警推送联调返回数据：" + data);
            logger.info("===============告警推送联调返回数据结果：" + JSONObject.parseObject(data));


            JSONArray jsonArray = JSONObject.parseObject(data).getJSONObject("body").getJSONArray("values");
            String yxfs = HttpContentTypeUtil.sendHttpPostJsonWithHeader(realtimeUrl, JSON.toJSONString(requestVo), headerMap);
            logger.info("===============告警推送联调返回数据结果：" + yxfs);
            JSONArray yxfsArr = JSONObject.parseObject(yxfs).getJSONObject("body").getJSONArray("values");
            JSONArray filteredArr = new JSONArray(
                    yxfsArr.stream()
                            .filter(obj -> obj instanceof JSONObject)
                            .map(obj -> (JSONObject) obj)
                            .filter(obj -> {
                                Object v = obj.get("value");
                                if (v instanceof Number) {
                                    return ((Number) v).doubleValue() == 1.0;
                                }
                                return false;
                            }).collect(Collectors.toList())
            );




            jsonArray.addAll(filteredArr);

            JSONObject yxsj = new JSONObject();
            yxsj.put("key","tyrq");
            yxsj.put("value",operationDate);


            JSONObject safeDay = new JSONObject();
            safeDay.put("key","safeDay");
            LocalDate opDate = LocalDate.parse(operationDate);
            safeDay.put("value", ChronoUnit.DAYS.between(opDate, LocalDate.now()));
            jsonArray.add(yxsj);
            jsonArray.add(safeDay);
            objects.addAll(jsonArray);
            logger.info("===============告警推送联调返回数据结果1111111：" + jsonArray);

        }
        return objects;
    }

}
