package cn.gintone.service;

import cn.gintone.config.IotDbConfig;
import cn.gintone.controller.vo.DeviceReqConfListReqVO;
import cn.gintone.dal.DeviceReqConfMapper;
import cn.gintone.dto.DeviceIllLogInfo;
import cn.gintone.entity.DeviceReqConfDO;
import cn.gintone.iotdbUtils.MyDateUtils;
import cn.gintone.iotdbUtils.MyIotDbUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class MyScheduledTasks {

    @Resource
    private DeviceReqConfMapper deviceReqConfMapper;

    @Autowired
    private IotDbConfig iotDbConfig;


    @Scheduled(fixedDelay = 50000)
    public void updateDeviceState() {
        List<DeviceReqConfDO> deviceReqConfDOS = deviceReqConfMapper.selectList(new DeviceReqConfListReqVO());
        if (deviceReqConfDOS != null && deviceReqConfDOS.size() > 0) {
            for (DeviceReqConfDO deviceReqConfDO : deviceReqConfDOS) {
                Date sycnDate = deviceReqConfDO.getSycnDate();
                if (sycnDate != null && 1 != deviceReqConfDO.getState()) {
                    Long t = new Date().getTime() - sycnDate.getTime();
                    if (t > 10 * 60 * 60) {
                        deviceReqConfMapper.update(new UpdateWrapper<DeviceReqConfDO>().lambda()
                                .eq(DeviceReqConfDO::getId, deviceReqConfDO.getId())
                                .set(DeviceReqConfDO::getState, 0)
                        );

                        DeviceIllLogInfo deviceIllLogInfo = new DeviceIllLogInfo();
                        deviceIllLogInfo.setDeviceId(deviceReqConfDO.getDeviceId());
                        deviceIllLogInfo.setDeviceName(deviceReqConfDO.getDeviceName());
                        deviceIllLogInfo.setDeviceTypeId(deviceReqConfDO.getDeviceTypeId() + "");
                        deviceIllLogInfo.setDeviceTypeName(deviceReqConfDO.getDeviceTypeName());
                        deviceIllLogInfo.setAccessed(MyDateUtils.longToString(new Date().getTime()));
                        deviceIllLogInfo.setIllType("disconnected");
                        MyIotDbUtils.inserOneDeviceLogInfo_ill(iotDbConfig, deviceIllLogInfo);
                    }
                }
            }
        }
    }
}
