package com.imdroid.sideslope.executor;

import com.imdroid.secapi.client.BeidouClient;
import com.imdroid.secapi.dto.GnssStatus;
import com.imdroid.sideslope.message.D3F0SelfCheckMessage;
import com.imdroid.sideslope.sal.DeviceService;
import com.imdroid.sideslope.sal.Device;
import com.imdroid.sideslope.service.DataPersistService;
import com.imdroid.common.util.ThreadManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Layton
 * @date 2023/2/2 20:40
 */
@Component
public class D3F0SelfCheckMessageExecutor implements Executor<D3F0SelfCheckMessage, Void> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DataPersistService dataPersistService;
    @Autowired
    private BeidouClient beidouClient;
    // 由于消息数据大，从缓存查询设备信息效率更高
    @Resource(name = "local")
    private DeviceService deviceService;

    @Override
    public Void execute(D3F0SelfCheckMessage message) {
        if (logger.isDebugEnabled()) {
            logger.debug("receive d3f0 message of device: "+message.getId());
        }
        // 补齐tenantId
        Device device = deviceService.findByDeviceId(message.getId());
        if(device == null) return null;
        message.setTenantId(device.getTenantId());
        device.updateRx(message.getHeader(),message.getLen(),1);

        ThreadManager.getFixedThreadPool().submit(() -> {
            GnssStatus lastGnssStatus = dataPersistService.getDeviceState(message.getId());
            try {
                if (lastGnssStatus != null && lastGnssStatus.getState() == GnssStatus.STATE_OFFLINE) {
                    beidouClient.onLine(lastGnssStatus.getDeviceid(),
                            lastGnssStatus.getTenantid(), lastGnssStatus.getUpdatetime());
                } else {
                    // 通知beidou服务设备上线
                    beidouClient.onDeviceActive(message.getId(), device.getTenantId());
                }
            }
            catch (Exception e){

            }
            dataPersistService.saveDeviceState(message);
        });

        return null;
    }


    @Override
    public Class<?> getMessageType() {
        return D3F0SelfCheckMessage.class;
    }
}
