package com.mortals.xhx.base.framework.listener;

import cn.hutool.core.util.StrUtil;
import com.mortals.xhx.common.code.DeviceOnlineStatusEnum;
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.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.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Date;

/**
 * @author: zxfei
 * @date: 2022/6/22 16:40
 * @description:
 **/
@Slf4j
@Component
public class CustomerKeyExpirationListener implements MessageListener {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private PlatformService platformService;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String key = message.toString();
        String subStr = StrUtil.removePrefix(key, RedisKey.KEY_DEVICE_ONLINE_CACHE);
        if(!subStr.equals(key)){
            DeviceEntity deviceEntity = deviceService.getExtCache(subStr);
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                if (deviceEntity.getDeviceOnlineStatus() == DeviceOnlineStatusEnum.在线.getValue()) {
                    deviceEntity.setOfflineTime(new Date());
                    deviceEntity.setDeviceOnlineStatus(DeviceOnlineStatusEnum.离线.getValue());
                    deviceService.update(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, DeviceStatusEnum.OFFLINE);
                    }
                }

                // TODO: 2022/6/23 告警信息保存与发送 
            }
        }


        log.info("监听到key:" + key + "过期");
    }
}