package client;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;
import com.energy.manage.service.ManageAppApplication;
import com.energy.manage.service.client.skf.AuthClient;
import com.energy.manage.service.client.skf.DynamicMeasurementsClient;
import com.energy.manage.service.constant.client.skf.SkfClientConstants;
import com.energy.manage.service.domain.client.skf.AutoTokenVO;
import com.energy.manage.service.domain.client.skf.DynamicMeasurementsVo;
import com.energy.manage.service.domain.client.skf.HierarchyListVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
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 java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Slf4j
@SpringBootTest(classes = ManageAppApplication.class)
@RunWith(value = SpringRunner.class)
public class SkfClientWebTest {

    @Autowired
    private AuthClient authClient;

    @Autowired
    private DynamicMeasurementsClient dynamicMeasurementsClient;

    @Test
    public void authToken() {

        // 获取token
        AutoTokenVO autoTokenVO = authClient.getSkfToken(SkfClientConstants.SKF_TOKEN_GRANT_TYPE,
                SkfClientConstants.SKF_TOKEN_USERNAME, SkfClientConstants.SKF_TOKEN_PASSWORD);

        if (autoTokenVO == null) {
            return;
        }

        String token = "Bearer " + autoTokenVO.getAccess_token();
        System.out.println("Authorization ====>" + token);

        // 获取组织结构
        List<HierarchyListVo> values = dynamicMeasurementsClient.getSkfHierarchy(token);
        List<HierarchyListVo> hierarchyListVos = Lists.newArrayList();

        for (HierarchyListVo hierarchyListVo : values) {
            for (HierarchyListVo listVo : hierarchyListVo.getChildren()) {
                if (listVo.getTypeId() == 1) {
                    for (HierarchyListVo vo : listVo.getChildren()) {
                        hierarchyListVos.addAll(vo.getChildren());
                    }
                }
            }
        }

        Integer pointId = 86;

        List<String> xlist = Lists.newArrayList();
//        xlist.add("7");
//        xlist.add("8");
        xlist.add("11");

        for(String x : xlist){
            String fromDateUTC = "2024-0"+x+"-01";
            String toDateUTC = "2024-0"+x+"-30";
            Integer includeMeasurements = 1;
            Integer numReadings = 999;

            List<DynamicMeasurementsVo> lists = dynamicMeasurementsClient.getSkfDynamicMeasurements(token, pointId,fromDateUTC,toDateUTC);
            System.out.println("数据集 >>>>> " + lists.size());


            if (CollectionUtil.isEmpty(lists)) {
                return;
            }

            // 测点名字
            String name = null;
            for (HierarchyListVo vo : hierarchyListVos) {
                if (vo.getId().equals(pointId)) {
                    name = vo.getName();
                }
            }

            for (DynamicMeasurementsVo dynamicMeasurementsVo : lists) {
                if (!CollectionUtil.isEmpty(dynamicMeasurementsVo.getMeasurements())) {
                    List<DynamicMeasurementsVo.MeasurementsDTO> dynamicMeasurementsVoMeasurements = dynamicMeasurementsVo.getMeasurements();
                    List<Double> doubleList = Lists.newArrayList();
                    for (DynamicMeasurementsVo.MeasurementsDTO dto : dynamicMeasurementsVoMeasurements) {
                        CollectionUtil.addAll(doubleList, dto.getValues());
                    }
                    createCsvFile(doubleList, "/Users/shiyue/Downloads/sdk_data/"+x+"month","/Users/shiyue/Downloads/sdk_data/"+x+"month/"+"SKF_F004_4#风机_" + utctolocal(dynamicMeasurementsVo.getReadingTimeUTC()) + "_" + name + "_" + dynamicMeasurementsVo.getSpeed() + "_cms.csv");
                }
            }
        }
    }


    /**
     * 时间转换
     *
     * @param utcTime
     * @return
     */
    private String utctolocal(String utcTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        LocalDateTime dateTime = LocalDateTime.parse(utcTime, formatter);
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }


    /**
     * 导出csv格式工具类
     *
     * @param result   导出数据
     * @param fileName 文件名
     */
    public void createCsvFile(List result, String path,String fileName) {
        try {
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            File csvFile = new File(fileName);  //构造文件
            //导入HuTool中CSV工具包的CsvWriter类
            //设置导出字符类型, CHARSET_UTF_8
            CsvWriter writer = CsvUtil.getWriter(csvFile, CharsetUtil.CHARSET_UTF_8);
            writer.write(result);  //通过CsvWriter中的write方法写入数据
            writer.close();   //关闭CsvWriter
            //保存文件
//            FileInputStream fileInputStream = new FileInputStream(csvFile);
//            this.saveFile(fileInputStream, csvFile.getName());
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * 文件保存
     *
     * @param inputStream
     * @param fileName
     */
    private void saveFile(InputStream inputStream, String fileName) {
        OutputStream os = null;
        try {
            //保存文件路径
            String path = "/Users/shiyue/Downloads/sdk_data/8month";
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




}
