package com.xydl.cac.thermal;

import com.netsdk.lib.NetSDKLib;
import com.netsdk.module.LoginModule;
import com.netsdk.module.ThermalCameraModule;
import com.xydl.cac.entity.NSensor;
import com.xydl.cac.entity.ThermalConfig;
import com.xydl.cac.service.DataService;
import com.xydl.cac.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ThermalCollectService {

    @Resource
    DataService dataService;

    public void collectAndSave(List<NSensor> list, ThermalConfig config) {
        try {
            LoginModule.init(null, null);
            NSensor sensor = list.get(0);
            LoginModule.login(sensor.getIp(), sensor.getPort(), sensor.getUsername(), sensor.getPasswd());
            log.info("登入到" + sensor.getIp() + ":" + sensor.getPort() + ", 用户名:" + sensor.getUsername());
            String time = DateUtil.format(new Date());
            for (NSensor item : list) {
                NetSDKLib.NET_RADIOMETRYINFO data = ThermalCameraModule.queryItemTemper(0, 0, sensor.getTmId(), sensor.getTmType());
                if (data == null) {
                    log.warn("没有采集到数据, 序号" + item.getTmId() + "测量项目" + sensor.getTmType());
                } else {
                    log.info("采集到序号" + item.getTmId() + "测量项目" + sensor.getTmType() + "的max="
                            + data.fTemperMax + ", min=" + data.fTemperMin + ", aver=" + data.fTemperAver);
                    if (StringUtils.isNotBlank(config.getMaxtemp())) {
                        dataService.insertData(item.getTableName(), item.getDevId(), time, config.getMaxtemp(), String.valueOf(data.fTemperMax));
                    }
                    if (StringUtils.isNotBlank(config.getMintemp())) {
                        dataService.insertData(item.getTableName(), item.getDevId(), time, config.getMintemp(), String.valueOf(data.fTemperMin));
                    }
                    if (StringUtils.isNotBlank(config.getAvertemp())) {
                        dataService.insertData(item.getTableName(), item.getDevId(), time, config.getAvertemp(), String.valueOf(data.fTemperAver));
                    }
                }
            }

            LoginModule.logout();
        } catch (Exception ex) {
            log.error("热成像测温采集异常, " + ex.getMessage(), ex);
        } finally {
            LoginModule.cleanup();
        }
    }
}
