package com.njcn;

import cn.hutool.core.date.DatePattern;
import com.njcn.csdevice.CsDeviceBootApplication;
import com.njcn.csdevice.pojo.dto.PqsCommunicateDto;
import com.njcn.csdevice.service.DeviceFtpService;
import com.njcn.csdevice.service.ICsCommunicateService;
import com.njcn.csdevice.service.IRStatIntegrityDService;
import com.njcn.csdevice.service.IRStatOnlineRateDService;
import com.njcn.influx.utils.InfluxDbUtils;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertTrue;

/**
 * Unit test for simple App.
 */
@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = CsDeviceBootApplication.class)
@Slf4j
@NoArgsConstructor
public class AppTest{

    @Autowired
    private DeviceFtpService deviceFtpService;

    @Autowired
    private ICsCommunicateService csCommunicateService;

    @Autowired
    private IRStatIntegrityDService statIntegrityDService;

    @Autowired
    private IRStatOnlineRateDService statOnlineRateDService;

    public static void main(String[] args) {
        String eventValue = "122.5493";
        String persistTime = "0.2410";
        String data = determineDropZone(eventValue, persistTime);
        System.out.println("data==:" + data);
    }


    public static String determineDropZone(String eventValue, String persistTime) {
        if (eventValue != null && !eventValue.trim().isEmpty() && persistTime != null && !persistTime.trim().isEmpty()) {
            BigDecimal vvm;
            BigDecimal vvtm;
            try {
                vvm = (new BigDecimal(eventValue.trim())).divide(new BigDecimal("100"), 6, RoundingMode.HALF_UP);
                vvtm = new BigDecimal(persistTime.trim());
            } catch (Exception var6) {
                Exception e = var6;
                log.error("判定压降落点区域入参解析失败，eventValue={}, persistTime={}", new Object[]{eventValue, persistTime, e});
                return null;
            }

            if (vvtm.compareTo(new BigDecimal("0.001")) >= 0 && vvm.compareTo(BigDecimal.ZERO) != 0) {
                if (inRange(vvm, "0.9", "1") && inRange(vvtm, "0.001", "60")) {
                    return "A区";
                } else if (inRange(vvm, "0", "0.9") && inRange(vvtm, "0.001", "0.05")) {
                    return "A区";
                } else if (inRange(vvm, "0.5", "0.7") && inRange(vvtm, "0.05", "0.2")) {
                    return "B区";
                } else if (inRange(vvm, "0.7", "0.8") && inRange(vvtm, "0.05", "0.5")) {
                    return "B区";
                } else if (inRange(vvm, "0.8", "0.9") && inRange(vvtm, "0.05", "60")) {
                    return "B区";
                } else if (inRange(vvm, "0", "0.5") && inRange(vvtm, "0.05", "1")) {
                    return "C区";
                } else if (inRange(vvm, "0.5", "0.7") && inRange(vvtm, "0.2", "1")) {
                    return "C区";
                } else if (inRange(vvm, "0.7", "0.8") && inRange(vvtm, "0.5", "1")) {
                    return "C区";
                } else if (inRange(vvm, "0", "0.8") && inRange(vvtm, "1", "60")) {
                    return "D区";
                } else {
                    log.warn("压降落点区域未匹配任何规则，eventValue={}, persistTime={}", eventValue, persistTime);
                    return null;
                }
            } else {
                return "A区";
            }
        } else {
            log.warn("判定压降落点区域入参为空，eventValue={}, persistTime={}", eventValue, persistTime);
            return null;
        }
    }

    private static boolean inRange(BigDecimal value, String lowerInclusive, String upperExclusive) {
        return value.compareTo(new BigDecimal(lowerInclusive)) >= 0
                && value.compareTo(new BigDecimal(upperExclusive)) < 0;
    }

    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        assertTrue( true );
    }

    /**
     * 测试下载文件
     */
    @SneakyThrows
    @Test
    public void downloadFileTest() {
        String nDid = "00B78D016AB5";
        String name = "/etc/pqs_arm.bin";
        Integer size = 5123552;
        String fileCheck = "859E36E8";
        for (int i = 0; i < 10; i++) {
            log.info("开始第{}次", i);
            deviceFtpService.downloadFile(nDid,name,size,fileCheck);
            Thread.sleep(1000 * 60 * 4);
            log.info("这是第{}次询问装置,结果为:{}", i, null);
        }
    }

    @SneakyThrows
    @Test
    public void test1() {
    }

    @SneakyThrows
    @Test
    public void writeData() {
        PqsCommunicateDto pqsCommunicateDto = new PqsCommunicateDto();
        pqsCommunicateDto.setTime("2025-08-04 18:00:00");
        pqsCommunicateDto.setDevId("da7aa071bf89864bedea8833133676b7");
        pqsCommunicateDto.setType(0);
        pqsCommunicateDto.setDescription("通讯中断");
        csCommunicateService.insertion(pqsCommunicateDto);
    }




    public static void test2() {
        InfluxDbUtils influxDbUtils = new InfluxDbUtils("admin", "123456", "http://192.168.1.103:18086", "pqsbase", "");
        Map<String, String> tags = new HashMap<>();
        tags.put("dev_id","0eb0262f706445ac9c69931a60357561");
        Map<String,Object> fields = new HashMap<>();
//        fields.put("type",1);
//        fields.put("description","通讯正常");
        fields.put("type",0);
        fields.put("description","通讯中断");
        long time = LocalDateTime.parse("2024-01-06 06:00:00",  DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        Point point = influxDbUtils.pointBuilder("pqs_communicate", time, TimeUnit.MILLISECONDS, tags, fields);
        BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
        batchPoints.point(point);
        influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, Collections.singletonList(batchPoints.lineProtocol()));

    }

    public static void test22() {
        InfluxDbUtils influxDbUtils = new InfluxDbUtils("admin", "123456", "http://192.168.1.103:18086", "pqsbase", "");
        Map<String, String> tags = new HashMap<>();
        tags.put("dev_id","0eb0262f706445ac9c69931a60357561");
        Map<String,Object> fields = new HashMap<>();
        fields.put("type",1);
        fields.put("description","通讯正常");
//        fields.put("type",0);
//        fields.put("description","通讯中断");
        long time = LocalDateTime.parse("2024-01-06 12:00:00",  DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        Point point = influxDbUtils.pointBuilder("pqs_communicate", time, TimeUnit.MILLISECONDS, tags, fields);
        BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
        batchPoints.point(point);
        influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, Collections.singletonList(batchPoints.lineProtocol()));

    }



    public static void test3() {
        InfluxDbUtils influxDbUtils = new InfluxDbUtils("admin", "123456", "http://192.168.1.103:18086", "pqsbase", "");
        Map<String, String> tags = new HashMap<>();
        tags.put("dev_id","0eb0262f706445ac9c69931a60357561");
        Map<String,Object> fields = new HashMap<>();
        fields.put("type",0);
        fields.put("description","通讯中断");
//        fields.put("type",1);
//        fields.put("description","通讯正常");
        long time = LocalDateTime.parse("2024-01-06 18:00:00",  DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        Point point = influxDbUtils.pointBuilder("pqs_communicate", time, TimeUnit.MILLISECONDS, tags, fields);
        BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
        batchPoints.point(point);
        influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, Collections.singletonList(batchPoints.lineProtocol()));

    }

    public static void test33() {
        InfluxDbUtils influxDbUtils = new InfluxDbUtils("admin", "123456", "http://192.168.1.103:18086", "pqsbase", "");
        Map<String, String> tags = new HashMap<>();
        tags.put("dev_id","0eb0262f706445ac9c69931a60357561");
        Map<String,Object> fields = new HashMap<>();
//        fields.put("type",0);
//        fields.put("description","通讯中断");
        fields.put("type",1);
        fields.put("description","通讯正常");
        long time = LocalDateTime.parse("2024-01-06 22:00:00",  DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        Point point = influxDbUtils.pointBuilder("pqs_communicate", time, TimeUnit.MILLISECONDS, tags, fields);
        BatchPoints batchPoints = BatchPoints.database(influxDbUtils.getDbName()).retentionPolicy("").consistency(InfluxDB.ConsistencyLevel.ALL).build();
        batchPoints.point(point);
        influxDbUtils.batchInsert(influxDbUtils.getDbName(), "", InfluxDB.ConsistencyLevel.ALL, TimeUnit.MILLISECONDS, Collections.singletonList(batchPoints.lineProtocol()));

    }

}
