package com.jjt.task;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.jjt.JjtApplication;
import com.jjt.biz.service.IApiYrService;
import com.jjt.biz.vo.YrCompareBackReq;
import com.jjt.rz.domain.TwinCalcHourRz;
import com.jjt.rz.domain.TwinDeviceRz;
import com.jjt.rz.domain.TwinDeviceTypeData;
import com.jjt.rz.service.ITwinCalcHourRzService;
import com.jjt.rz.service.ITwinDeviceRzService;
import com.jjt.rz.service.ITwinDeviceTypeService;
import com.jjt.rz.vo.CompareVO;
import com.jjt.utils.IotService;
import javafx.util.Pair;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * DataProcess$
 *
 * @author wukai
 * @date 2024/5/7 11:49
 */
@SpringBootTest(classes = JjtApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RzTest {
    @Resource
    private IotService iotService;
    @Resource
    private ITwinDeviceRzService rzService;
    @Resource
    private ITwinCalcHourRzService hourRzService;
    @Resource
    private ITwinDeviceTypeService typeService;

    /**
     * 2	RZ	4节定型机	root.tl.suxi.dingxingji4**
     * 3	RZ	双棍烫光机	root.tl.suxi.sgtgj**
     * 4	RZ	高梳机	root.tl.suxi.gaoShu**
     * 5	RZ	两棍刷毛机	root.tl.suxi.lgsmj**
     * 6	RZ	6节定型机	root.tl.suxi.dingxingji6**
     * 7	RZ	起毛机	root.tl.suxi.qiMaoJi**
     * 8	RZ	烘固机	root.tl.suxi.hongGuJi**
     * 9	RZ	烫剪机	root.tl.suxi.tangJianJi**
     */
    @Test
    public void curr() {
        iotService.setToken();
        List<TwinDeviceRz> list = rzService.selectTwinDeviceRzList(new TwinDeviceRz());
        List<String> strList = new ArrayList<>();
        Map<String, TwinDeviceRz> rzMap = new HashMap<>();
        list.forEach(item -> {
            String str = item.getDeviceCode() + ".Capacity_data_1";
            String mapId = item.getDevicePath() + ".Capacity_data_1";
            item.setOnline(false);
            rzMap.put(mapId, item);
            strList.add(str);
        });
        String sql = "select last %s from root.tl.suxi";
        sql = String.format(sql, String.join(",", strList));
        iotService.query(sql);
        JSONObject jsonObject = iotService.query(sql);
        JSONObject data = jsonObject.getJSONObject("data");
        System.err.println(data);
        JSONArray values = data.getJSONArray("values");
        JSONArray columnNames = data.getJSONArray("columnNames");
        JSONArray timestamps = data.getJSONArray("timestamps");
        for (int i = 0; i < values.size(); i++) {
            JSONArray da = values.getJSONArray(i);
            String type = da.getStr(0);
            TwinDeviceRz rz = rzMap.get(type);
            if (rz != null) {
                if (rz.getTypeId() == 3 || rz.getTypeId() == 5 || rz.getTypeId() == 9) {
                    //双棍烫光和两棍刷毛需要按照机器状态来判断是否开机
                    //=1 设备故障停机  ，=2 人工停机 ，=3是缺布/断布停机 ，=4满布停机，=5设备上电待机中  =6设备自动运行中，=7设备过站中
                    if (da.getStr(1).equals("6")) {
                        rz.setOnline(true);
                    }
                } else {
                    //其他类型只需要有值就表示开机
                    rz.setOnline(true);
                }
            }
//            da.getStr(1);
//            da.getStr(2);
//            for (int j = 0; j < da.size(); j++) {
//
//            }
        }
        // 按 line 分组并统计数量
//        Map<String, Long> deviceCountByLine = list.stream()
//                .collect(Collectors.groupingBy(TwinDeviceRz::getLine, Collectors.counting()));
        // 按 line 分组，分别统计总数量和 online 为 true 的数量
        Map<String, Pair<Integer, Integer>> deviceCountByLine = list.stream()
                .collect(Collectors.groupingBy(
                        TwinDeviceRz::getLine,
                        Collectors.collectingAndThen(
                                Collectors.partitioningBy(TwinDeviceRz::getOnline),
                                map -> {
                                    int total = map.get(true).size() + map.get(false).size();
                                    int open = map.get(true).size();
                                    return new Pair<>(total, open);
                                }
                        )
                ));
        // 打印结果
        deviceCountByLine.forEach((line, count) ->
                System.out.println("Line: " + line + ", Device Count: " + count.getKey() + ",online:" + count.getValue()));

        list.forEach(item -> {
            if (item.getLine().equals("8")) {
                System.err.println("device:" + item.getDeviceName() + ",online:" + item.getOnline());
            }
        });
    }

    @Test
    public void hour() {
        iotService.setToken();
        String st = "2025-06-05";
        String ed = "2025-06-06";
        LocalDate localDate = LocalDate.parse(st);
        LocalDate endDate = LocalDate.parse(ed);
        LocalDateTime start = LocalDateTime.of(localDate, LocalTime.MIN).plusHours(13);
//        hourRzService.hour(start, start.plusHours(1));
        LocalDateTime end = LocalDateTime.of(endDate.plusDays(1), LocalTime.MIN).plusHours(6);
        LocalDateTime curr = LocalDateTime.now();
        if (end.isAfter(curr)) {
            end = curr.minusHours(1);
        }
        do {
            int i = start.getHour();
            System.err.println(start.toLocalDate().toString() + "\t" + i);
            hourRzService.hour(start, start.plusHours(1));
            start = start.plusHours(1);
        } while (!start.isAfter(end));
    }

    @Test
    public void data() {
        List<TwinDeviceTypeData> all = typeService.selectTwinDeviceTypeDataAll();
        Map<Long, TwinDeviceTypeData> dataMap = all.stream()
                .collect(Collectors.toMap(
                        TwinDeviceTypeData::getDataId,
                        item -> item,
                        (existing, replacement) -> existing
                ));
        String st = "2025-06-03";
        LocalDate localDate = LocalDate.parse(st);
        Date date = Date.from(localDate.atStartOfDay(ZoneOffset.of("+8")).toInstant());
        TwinCalcHourRz search = new TwinCalcHourRz();
        search.setDataDate(date);
        search.setHour(19);
        List<TwinDeviceRz> deviceList = rzService.selectTwinDeviceRzList(new TwinDeviceRz());
        List<TwinCalcHourRz> list = hourRzService.selectTwinCalcHourRzList(search);
        list.forEach(item -> {
            System.err.println(item.getData());
            TreeMap<String, String> map = JSON.parseObject(item.getData(), TreeMap.class);
            TreeMap<String, String> treeMap = new TreeMap<>();
            map.forEach((id, value) -> {
                TwinDeviceTypeData data = dataMap.get(Long.parseLong(id));
                if (data != null) {
                    treeMap.put(data.getDataName(), value);
                }
            });

            item.setPara(treeMap);
            treeMap.forEach((name, value) -> {
                System.err.println(name + "\t" + value);
            });
        });
    }

    @Resource
    private IApiYrService apiYrService;

    @Test
    public void test() {
        String ed = "2025-06-03";
        LocalDate ld = LocalDate.parse(ed);
        LocalDateTime start = LocalDateTime.of(ld, LocalTime.MIN).plusHours(18);
        LocalDateTime end = LocalDateTime.of(ld, LocalTime.MIN).plusHours(19);

        List<YrCompareBackReq> list = new ArrayList<>();
        YrCompareBackReq req = new YrCompareBackReq();
        req.setLine(8);
        req.setStart(start);
        req.setEnd(end);
        list.add(req);
        req = new YrCompareBackReq();
        req.setLine(7);
        req.setStart(start);
        req.setEnd(end);
        list.add(req);

        List<CompareVO> vos = apiYrService.compare(list,true);
        System.err.println(vos.size());
    }
}

