package com.usky.iot.service.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.backend.domain.StatusVO;
import com.usky.common.core.bean.ApiResult;
import com.usky.demo.RemoteTsdbProxyService;
import com.usky.iot.domain.BaseAlarm;
import com.usky.iot.domain.DmpDeviceInfo;
import com.usky.iot.domain.DmpDeviceStatus;
import com.usky.iot.mapper.DmpDeviceStatusMapper;
import com.usky.iot.service.BaseAlarmService;
import com.usky.iot.service.DmpDeviceStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Configuration
public class DeviceOperate {
    @Autowired
    private RemoteTsdbProxyService remoteTsdbProxyService;

    @Autowired
    DmpDeviceStatusService dmpDeviceStatusService;

    @Async("asyncServiceExecutor")
    public void updateDeviceStatus(){
        log.info("定时同步设备状态数据 start");
        ApiResult<List<Map<String,Object>>> list = remoteTsdbProxyService.getAllDeviceRealTime();
        List<Map<String,Object>> dataList = list.getData();
        if(CollectionUtils.isNotEmpty(dataList)){
            for(int i=0;i<dataList.size();i++){
                String deviceuuid = dataList.get(i).get("device_uuid").toString();
                LocalDateTime lTime = Instant.ofEpochMilli(Long.valueOf(dataList.get(i).get("realtime").toString())).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
                String date =  lTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                String currentDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                LambdaUpdateWrapper<DmpDeviceStatus> updateWrapper = Wrappers.lambdaUpdate();
                if(date.equals(currentDate)){
                    updateWrapper.set(DmpDeviceStatus::getDeviceStatus,1)  //设备在线
                            .set(DmpDeviceStatus::getLastOnlineTime,lTime)
                            .eq(DmpDeviceStatus::getDeviceUuid,deviceuuid);

                }else{
                    updateWrapper.set(DmpDeviceStatus::getDeviceStatus,2)  //设备离线
                            .set(DmpDeviceStatus::getLastOnlineTime,lTime)
                            .eq(DmpDeviceStatus::getDeviceUuid,deviceuuid);

                }
                dmpDeviceStatusService.update(updateWrapper);

            }

        }
        log.info("定时同步设备状态数据 end");
    }
}
