package vip.xiaonuo.coldchain.core.cache.monitordevice;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import rk.netDevice.sdk.p2.ParamItem;
import vip.xiaonuo.coldchain.core.renke.RenKeService;
import vip.xiaonuo.coldchain.modular.monitordevice.entity.MonitorDevice;
import vip.xiaonuo.coldchain.modular.monitordevice.service.MonitorDeviceService;

import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class MonitorDeviceCacheInitializer implements CommandLineRunner {
    private final MonitorDeviceService monitorDeviceService;
    private final MonitorDeviceCache monitorDeviceCache;
    private final RenKeService renKeService;

    /**
     * Spring Boot 应用启动时执行的方法
     */
    @Override
    public void run(String... args) {
        updateDeviceCache();
    }


    private void updateDeviceCache() {
        try {
            // 获取设备列表 只缓存建大仁科的设备
            LambdaQueryWrapper<MonitorDevice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.likeRight(MonitorDevice::getModelName, "RS");
            List<MonitorDevice> deviceList = monitorDeviceService.list(queryWrapper);
            if (deviceList.isEmpty()) {
                log.warn("采集设备列表为空，未进行缓存更新");
                return;  // 设备列表为空，跳过缓存更新
            }
            // 将设备数据加载到缓存中
            for (MonitorDevice monitorDevice : deviceList) {
                String deviceCode = monitorDevice.getDeviceCode();
                String deviceModel = monitorDevice.getModelName();
                if (!deviceCode.matches("^[0-9]+$")) {
                    log.error("Invalid device code: " + deviceCode);
                    continue;
                }
                Integer parsedDeviceCode = Integer.parseInt(deviceCode);
                // 调用设备编号配置上报参数接口
                List<Integer> paramIds = monitorDevice.getParamIds();
                if (paramIds == null || paramIds.isEmpty()) {  // Explicitly check for null and empty list
                    log.info("触发设备【编号】配置上报参数接口：采集设备编号 = {}, 采集设备型号 = {}", deviceCode, deviceModel);
                    renKeService.callParamIds(parsedDeviceCode);
                }
                // 调用设备参数配置上报参数接口
                List<ParamItem> parameters = monitorDevice.getParameters();
                if (paramIds!=null && (parameters==null || parameters.isEmpty())) {  // Check for null and empty list
                    log.info("触发设备【完整参数】配置上报参数接口：采集设备编号 = {}, 采集设备型号 = {}", deviceCode, deviceModel);
                    renKeService.callParameters(parsedDeviceCode, paramIds);
                }

                // 判断设备是否已经缓存
                if (!monitorDeviceCache.exists(deviceCode)) {
                    monitorDeviceCache.cacheDevice(deviceCode, deviceModel);
                    log.debug("采集设备缓存添加成功：采集设备编号 = {}, 采集设备型号 = {}", deviceCode, deviceModel);
                }
            }
            log.info("采集设备缓存完成，共更新了 {} 个采集设备", deviceList.size());
        } catch (NumberFormatException e) {
            log.error("设备编号格式错误，无法转换为整数", e);
        } catch (Exception e) {
            log.error("采集设备缓存更新失败，发生异常：", e);
        }
    }

    /**
     * 每 5 分钟定期执行设备缓存更新
     */
    @Scheduled(fixedRateString = "${coldchain.cache-update-interval:60000}")
    public void updateDeviceCachePeriodically() {
        log.info("定期调用[deviceCode][model_name]缓存更新方法");
        updateDeviceCache();
    }
}
