package com.gyee.generation.util.dataadapter;

import com.alibaba.fastjson.JSON;
import com.gyee.generation.init.MqttCache;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


@Service
public class AdapterServiceImpl implements IAdapterService {

    @Resource
    private MyWebClient myWebClient;


    /**
     * 请求历史数据
     *
     * @param start      开始时间
     * @param end        结束时间
     * @param sampleType 采样类型。0瞬时值，1原始值，2最大值，3最小值，4平均值。
     * @param sampleRate 采样频率，单位秒。
     * @param paths      要查询的变量（数据、测点）名。
     * @param pageIndex  真分页页码，可不填，不填表示不分页。
     * @param pageSize   真分页页长，可不填，不填表示不分页。
     * @param isDesc     是否倒序，bool。
     * @return 历史数据
     */
    @Override
    public TotalPointData getTotalData(String start, String end, int sampleType, int sampleRate, String paths,
                                       String pageIndex, String pageSize, boolean isDesc) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateStart = parseDateTime(start);
        LocalDateTime localDateEnd = parseDateTime(end);

        OffsetDateTime utcStart = OffsetDateTime.of(localDateStart, ZoneOffset.ofHours(8))
                .withOffsetSameInstant(ZoneOffset.UTC);
        OffsetDateTime utcEnd = OffsetDateTime.of(localDateEnd, ZoneOffset.ofHours(8))
                .withOffsetSameInstant(ZoneOffset.UTC);
        String uStart = utcStart.format(formatter);
        String uEnd = utcEnd.format(formatter);

        String uri2 = "/scadarest/api/SA/HistoryQuerySdb?start=" + uStart + "&end=" + uEnd
                + "&sampleType=" + sampleType + "&sampleRate=" + sampleRate + "&paths=" + paths
                + "&pageIndex=" + pageIndex + "&pageSize=" + pageSize + "&isDesc=" + isDesc;

        Mono<String> mono2 = myWebClient.webClient.get().uri(uri2)
                .header("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6WyJhZG1pbkBzY2FkYS5jb20iLCJhZG1pbkBzY2FkYS5jb20iXSwic3ViIjoiOGNiYjhlZTQtNjY5MS00M2ZlLTk0ZjktM2MxMDk1Mzg5Y2ZkIiwianRpIjoiOTFkYTRmMjQtODQyZC00OTJlLWIxYjUtYmY3OGM0ZWRhNmNlIiwiaWF0IjoxNzIzNjI2NzQxLCJ1c2VyX2lkIjoiOGNiYjhlZTQtNjY5MS00M2ZlLTk0ZjktM2MxMDk1Mzg5Y2ZkIiwiYmluZGluZ190eXBlIjoiTm9uZSIsInJvbGVfaWQiOiI1NTM0NWEwOC1lY2QwLTRlMWUtYjM1MC0yYTQzZjM3Y2NiNmMiLCJuYmYiOjE3MjM2MjY3NDEsImV4cCI6MjAzODk4Njc0MSwiaXNzIjoiU2NhZGFQb3J0YWwiLCJhdWQiOiJTY2FkYVBvcnRhbFdlYkFQSSJ9.x4nNd5TJrpZ3Bi8GBMkkQllmvcd1veq-_2EBmrqF_q0")
                .retrieve().bodyToMono(String.class);
        String block = mono2.block();
        return JSON.parseObject(block, TotalPointData.class);
    }


    /**
     * 处理日期为一位或者两位的问题
     */
    private static LocalDateTime parseDateTime(String datetimeString) {
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm:ss");
        LocalDateTime dateTime = null;

        try {
            dateTime = LocalDateTime.parse(datetimeString, formatter1);
        } catch (Exception e1) {
            try {
                DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-d HH:mm:ss");
                dateTime = LocalDateTime.parse(datetimeString, formatter2);
            } catch (Exception e2) {
                DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                dateTime = LocalDateTime.parse(datetimeString, formatter3);
            }
        }
        return dateTime;
    }


    /**
     * 请求实时数据
     *
     * @param paths 根据逗号隔开的测点
     * @return 测点的实时数据
     */
    @Override
    public Map<String, PointInfo> getLatestData(String paths) {
        Map<String, PointInfo> map = new HashMap<>();
        String uri = "/adapter/latest/list?paths=" + paths;
        Mono<? extends Map> mono = myWebClient.getLatest().get().uri(uri).retrieve().bodyToMono(map.getClass());

        if (null == paths || paths.isEmpty()) {
            return map;
        }
        String[] split = paths.split(",");
        for (String s : split) {
            PointInfo pintInfo = MqttCache.subData.get(s);
            map.put(s, pintInfo);
        }
        return map;
    }


}
