package com.mortals.xhx.daemon.task;

import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.common.code.DeviceMethodEnum;
import com.mortals.xhx.common.code.DeviceStatusEnum;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.service.PlatformService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备状态修正
 */
@Slf4j
@Service("DeviceStatTask")
public class DeviceStatTaskImpl implements ITaskExcuteService {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PlatformService platformService;

    @Override
    public void excuteTask(ITask task) throws AppException {

        //获取所有在线设备
        List<DeviceEntity> deviceList = deviceService.find(new DeviceQuery().deviceStatus(DeviceStatusEnum.在线.getValue()));
        //更新离线
        List<DeviceEntity> deviceOfflineList = deviceList.stream().map(item -> {
            boolean exists = cacheService.exists(RedisKey.KEY_DEVICE_ONLINE_CACHE + item.getDeviceCode());
            if (!exists) {
                item.setDeviceStatus(DeviceStatusEnum.离线.getValue());
                item.setOfflineTime(new Date());
            }
            return item;
        }).filter(f -> f.getDeviceStatus().equals(DeviceStatusEnum.离线.getValue())).collect(Collectors.toList());

        if (!ObjectUtils.isEmpty(deviceOfflineList)) {
            deviceService.update(deviceOfflineList);
            deviceOfflineList.forEach(deviceEntity -> {
                PlatformEntity platformEntity = platformService.get(deviceEntity.getPlatformId());
                ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                if (!ObjectUtils.isEmpty(platformEntity) && !ObjectUtils.isEmpty(productEntity)) {
                    //通知第三方平台
                    deviceService.sendThirdParty(deviceEntity, productEntity, platformEntity, DeviceMethodEnum.OFFLINE);
                }
            });
        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }


}
