package com.malk.tonglibo.utils;

import com.malk.tonglibo.Mapper.MachineDataMapper;
import com.malk.tonglibo.Service.IMachineDataService;
import com.malk.tonglibo.entity.RawDeviceData;
import com.malk.tonglibo.entity.MachineData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能：
 * 作者：hanxue
 * 日期：2025/10/18 1:00
 */
@Slf4j
@Component
public class DeviceDataPersistTask {
    @Autowired
    private MachineDataMapper machineDataMapper;
    @Autowired
    private IMachineDataService machineDataService;

    @Autowired
    private DataBuffer dataBuffer;

    @Autowired
    private ChangeDetector changeDetector;


    @Scheduled(fixedDelay = 1000) // 每秒执行一次
    public void persist() {
        List<RawDeviceData> dataList = dataBuffer.drain(500);
        if (dataList.isEmpty()) return;

        List<MachineData> toInsert = new ArrayList<>();
        int unchangedCount = 0;

        for (RawDeviceData item : dataList) {
            MachineData data = convertToMachineData(item);
            if (data == null) continue;

            //使用 MD5 判断是否变化
            if (changeDetector.isChanged(data)) {
                String fingerprint = MD5Util.md5(changeDetector.concatFields(data)); // 或在 convert 时生成
                data.setDataFingerprint(fingerprint);
                toInsert.add(data);
                changeDetector.recordAsCurrent(data.getParamId(), fingerprint);
            } else {
                unchangedCount++;
            }
        }

        if (!toInsert.isEmpty()) {
            machineDataService.saveBatch(toInsert, 100);
            log.info("入库 {} 条（变化数据），跳过 {} 条未变数据", toInsert.size(), unchangedCount);
        } else if (unchangedCount > 0) {
            log.debug("跳过 {} 条未变化数据", unchangedCount);
        }
    }



    private MachineData convertToMachineData(RawDeviceData item) {
        try {
            String deviceId = item.getDeviceId();
            String key = item.getKey();
            List<String> data = item.getData();

            MachineData machineData = new MachineData();
            machineData.setParamId(deviceId); // 唯一设备标识
            machineData.setMachineNo(key);
            machineData.setTime(item.getTime());
            machineData.setTimestr(item.getTimeStr());

            // 填充字段（根据索引取值）
            machineData.setJqyxsh(safeGet(data, 0));
            machineData.setZcn(safeGet(data, 2));
            machineData.setZqsj(safeGet(data, 4));
            machineData.setSgdyl(safeGet(data, 6));
            machineData.setXgdyl(safeGet(data, 8));
            machineData.setYskqyl1(safeGet(data, 10));
            machineData.setYskqyl2(safeGet(data, 12));
            machineData.setZymwd1(safeGet(data, 14));
            machineData.setZymwd2(safeGet(data, 16));
            machineData.setZymwd3(safeGet(data, 18));
            machineData.setZymwd4(safeGet(data, 20));
            machineData.setSmwd1(safeGet(data, 22));
            machineData.setSmwd2(safeGet(data, 24));
            machineData.setSmwd3(safeGet(data, 26));
            machineData.setSmwd4(safeGet(data, 28));
            machineData.setXmwd1(safeGet(data, 30));
            machineData.setXmwd2(safeGet(data, 32));
            machineData.setXmwd3(safeGet(data, 34));
            machineData.setXmwd4(safeGet(data, 36));
            machineData.setXjsj(safeGet(data, 38));
            machineData.setTssj(safeGet(data, 40));
            machineData.setZysj(safeGet(data, 42));

            return machineData;

        } catch (Exception e) {
            log.error("转换数据失败: {}", item, e);
            return null;
        }
    }

    // 安全获取索引值
    private String safeGet(List<String> list, int index) {
        if (index >= 0 && index < list.size()) {
            return list.get(index);
        }
        return "";
    }
}
