package com.jjt.rziot;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.jjt.JjtApplication;
import com.jjt.common.utils.StringUtils;
import com.jjt.utils.IotService;
import javafx.util.Pair;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 后整烫剪机
 */
@SpringBootTest(classes = JjtApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TangJianJiTest {
    @Resource
    private IotService iotService;

    /**
     * 印花设备数据
     */
    @Test
    void test() {
        iotService.setToken();
        String st = "2025-02-28";
        LocalDate localDate = LocalDate.parse(st);
        LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN).plusHours(19);
        LocalDateTime end = start.plusHours(11);
        List<Pair<String, String>> list = new ArrayList<>();
        Long startTime = start.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        Long endTime = end.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        String sql = "select SUM(DIFF(Capacity_data_2)) from root.tl.suxi.tangJianJiLine** where time>%s and time <=%s";
        sql = String.format(sql, startTime, endTime);
        iotService.query(sql);
        JSONObject jsonObject = iotService.query(sql);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray values = data.getJSONArray("values");
        JSONArray columnNames = data.getJSONArray("columnNames");
        JSONArray timestamps = data.getJSONArray("timestamps");
        if (values.size() == 1) {
            JSONArray da = values.getJSONArray(0);
            for (int i = 0; i < da.size(); i++) {
                Pair<String, String> pair = new Pair<>(columnNames.getStr(i), da.getStr(i));
                list.add(pair);
            }
        }

        try (Workbook workbook = new XSSFWorkbook(); FileOutputStream outputStream = new FileOutputStream("D:\\SYSTEM\\Desktop\\temp\\excel\\后整烫剪机-明细" + System.currentTimeMillis() + ".xlsx")) {
            Sheet sheet = workbook.createSheet();

            String[] names = {"总产量（米）", "设备名", "设备线路", "设备编号", "设备路径"};

            Row title = sheet.createRow(0);
            for (int i = 0; i < names.length; i++) {
                Cell cell = title.createCell(i);
                cell.setCellValue(names[i]);
            }
            AtomicInteger index = new AtomicInteger(1);
            list.forEach(pair -> {
                Row row = sheet.createRow(index.get());
                Cell[] cells = new Cell[names.length];
                for (int i = 0; i < names.length; i++) {
                    cells[i] = row.createCell(i);
                }
                cells[4].setCellValue(getPath(pair.getKey()));
                if (StringUtils.isNotEmpty(pair.getValue())) {
                    cells[0].setCellValue(Double.parseDouble(pair.getValue()));
                }
                cells[1].setCellValue(getName(pair.getKey()));
                cells[2].setCellValue(Integer.parseInt(getLine(pair.getKey())));
                cells[3].setCellValue(Integer.parseInt(getNo(pair.getKey())));
                index.getAndIncrement();
            });
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getPath(String key) {
        key = key.replace("SUM(DIFF(", "");
        key = key.replace(".Capacity_data_2))", "");
        return key;
    }

    public String getName(String key) {
        key = getPath(key);
        key = key.replace("root.tl.suxi.tangJianJiLine", "");
        key = key.replace("BackNo", "线-");
        key = key.replace("_PLC1", "号");
        return key;
    }

    public String getLine(String key) {
        key = getPath(key);
        key = key.replace("root.tl.suxi.tangJianJiLine", "");
        key = key.substring(0, key.indexOf("BackNo"));
        return key;
    }

    public String getNo(String key) {
        key = getPath(key);
        key = key.substring(key.indexOf("No") + 2, key.indexOf("_PLC1"));
        return key;
    }
}
