package com.bz.rmcp.dap.service.impl;

import com.bz.rmcp.dap.common.Constants;
import com.zcxk.rmcp.api.dto.readmeter.MeterData;
import com.bz.rmcp.dap.model.OfflineData;
import com.bz.rmcp.dap.service.DeviceService;
import com.zcxk.core.utils.DateUtil;
import com.zcxk.rmcp.api.enums.DeviceStatusEnum;
import com.zcxk.rmcp.core.dao.DeviceMapper;
import com.zcxk.rmcp.core.entity.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author linqingwei
 * @date 2021-08-09 18:07
 */
@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public void handleOffline(OfflineData offlineData) {
        MeterData lastMeterData = (MeterData) redisTemplate.opsForValue().get(Constants.PREFIX_CACHE_FLAG+offlineData.getDeviceId());
        if (lastMeterData != null) {
            //24小时后上报数据时间小于或等于离线时间则离线
            if(lastMeterData.getReceiveDate().getTime() <= offlineData.getDate().getTime()){
                Device device = new Device();
                device.setId(offlineData.getDeviceId());
                device.setDeviceStatus(DeviceStatusEnum.OFFLINE.getCode());
                device.setUpdateDate(LocalDateTime.now());
                device.setOfflineDate(DateUtil.asLocalDateTime(offlineData.getDate()));
                deviceMapper.updateByPrimaryKeySelective(device);
            }
        }
    }
}
