package com.inspect.metadata.montdatamqhandle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.mapper.BasedataEqpBookMapper;
import com.inspect.metadata.montdata.domain.BasedataMontPatDevOnline;
import com.inspect.metadata.montdata.service.IBasedataMontPatDevOnlineService;
import com.inspect.base.websocket.configure.WsPool;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.ip.IpUtils;
import com.inspect.base.redis.service.RedisService;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    private final Logger log = LoggerFactory.getLogger(RedisKeyExpirationListener.class);
    private static final String PATROL_DEVICE_ONLINE_STATUS_KEY = "mont_patrol_device_online_status:";
    private static final String PATROL_DEVICE_OFFLINE_COUNT = "mont_patrol_device_offline_count:";
    private static final String PATROL_DEVICE_CHANNEL_ONLINE_STATUS_KEY = "mont_patrol_device_channel_online_status:";
    final
    RedisService redisService;
    final
    IBasedataMontPatDevOnlineService basedataMontPatDevOnlineService;
    final
    BasedataEqpBookMapper basedataEqpbookMapper;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer, RedisService redisService, IBasedataMontPatDevOnlineService basedataMontPatDevOnlineService, BasedataEqpBookMapper basedataEqpbookMapper) {
        super(listenerContainer);
        this.redisService = redisService;
        this.basedataMontPatDevOnlineService = basedataMontPatDevOnlineService;
        this.basedataEqpbookMapper = basedataEqpbookMapper;
    }

    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("[REDIS] expiredKey: {}", expiredKey);
        int index;
        String patrolDeviceChannelCode;
        String dateTimeNow;
        Date nowTime;
        JSONObject returnJsonObject;
        String jsonString;
        if (expiredKey.startsWith(PATROL_DEVICE_ONLINE_STATUS_KEY)) {
            index = expiredKey.indexOf(":");
            patrolDeviceChannelCode = expiredKey.substring(index + 1);
            this.invokeIncrementCount(PATROL_DEVICE_OFFLINE_COUNT + patrolDeviceChannelCode);
            dateTimeNow = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            nowTime = DateUtils.getNowDate();
            this.addBasedataMontPatDevOnline(patrolDeviceChannelCode, nowTime);
            returnJsonObject = new JSONObject();
            returnJsonObject.put("patroldeviceCode", patrolDeviceChannelCode);
            returnJsonObject.put("patroldeviceOnlineStatus", "0");
            returnJsonObject.put("heart_beat_time", dateTimeNow);
            returnJsonObject.put("receiveTime", dateTimeNow);
            returnJsonObject.put("event", "mont/montHeartBeatData");
            jsonString = JSON.toJSONString(returnJsonObject);
            WsPool.sendMessageToAll(jsonString);
        } else if (expiredKey.startsWith(PATROL_DEVICE_CHANNEL_ONLINE_STATUS_KEY)) {
            index = expiredKey.indexOf(":");
            patrolDeviceChannelCode = expiredKey.substring(index + 1);
            dateTimeNow = DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss");
            nowTime = DateUtils.getNowDate();
            returnJsonObject = new JSONObject();
            returnJsonObject.put("patroldeviceChannelCode", patrolDeviceChannelCode);
            returnJsonObject.put("patroldeviceOnlineStatus", "0");
            returnJsonObject.put("heart_beat_time", dateTimeNow);
            returnJsonObject.put("receiveTime", dateTimeNow);
            returnJsonObject.put("event", "mont/montHeartBeatData");
            jsonString = JSON.toJSONString(returnJsonObject);
            WsPool.sendMessageToAll(jsonString);
        }

    }

    public void invokeIncrementCount(String key) {
        Boolean redisKey = this.redisService.hasKey(key);
        if (redisKey) {
            this.redisService.redisTemplate.opsForValue().increment(key, 1L);
        } else {
            this.redisService.redisTemplate.opsForValue().set(key, 1);
        }

    }

    private void addBasedataMontPatDevOnline(String patrolDeviceCode, Date nowTime) {
        BasedataMontPatDevOnline patDevOnline = new BasedataMontPatDevOnline();
        BasedataEqpBook basedataEqpbook = new BasedataEqpBook();
        basedataEqpbook.setPatrolDeviceCode(patrolDeviceCode);
        List<BasedataEqpBook> eqpBooks = this.basedataEqpbookMapper.selectBasedataEqpBookList(basedataEqpbook);
        if (null != eqpBooks && !eqpBooks.isEmpty()) {
            patDevOnline.setEqpBookId(eqpBooks.get(0).getEqpBookId());
        }

        patDevOnline.setPatrolDeviceCode(patrolDeviceCode);
        patDevOnline.setStatus("0");
        patDevOnline.setActionTime(nowTime);
        patDevOnline.setOfflineTime(nowTime);
        patDevOnline.setCreateTime(nowTime);
        patDevOnline.setCreateBy("sys");
        patDevOnline.setUpdateBy(IpUtils.getHostIp());
        this.basedataMontPatDevOnlineService.insertBasedataMontPatDevOnline(patDevOnline);
    }
}
