package com.xhpc.pp.server;

import cn.hutool.core.util.StrUtil;
import com.xhpc.common.enums.StationDeviceEnum;
import com.xhpc.pp.domain.XhpcDeviceMessage;
import com.xhpc.pp.mapper.XhpcDeviceMessageMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Map;
import java.util.Set;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.evcs.dto.ConnectorStatusInfo.OFF_LINE;
import static com.xhpc.pp.config.EarlierBeanConf.getLocalIPAndPort;
import static com.xhpc.pp.logic.RegisterLogic.DISCONNECTED;

@Component
public class HBCheckTask {

    @Resource
    XhpcDeviceMessageMapper deviceMessageMapper;

    @Scheduled(fixedRate = 10000)
    protected void run() {

        String svcSrvKey = "svcSrvGuns:".concat(getLocalIPAndPort());
        Set<String> cacheGunkeySet = REDIS.getCacheSet(svcSrvKey);
        Long now = Calendar.getInstance().getTimeInMillis();
        for (String gunkey : cacheGunkeySet) {
            Map<String, Object> cacheGun = REDIS.getCacheMap(gunkey);
            Long hbtime = (Long) cacheGun.get("hbtime");
            hbtime = hbtime == null ? 0 : hbtime;
            if ((now - hbtime) > 75000) {
                if (!DISCONNECTED.equals(cacheGun.get("status"))) {
                    cacheGun.put("statusInt", OFF_LINE);
                    cacheGun.put("status", DISCONNECTED);
                    REDIS.setCacheMap(gunkey, cacheGun);

                    XhpcDeviceMessage deviceMessage = new XhpcDeviceMessage();
                    deviceMessage.setType(StationDeviceEnum.PILE.getCode());

                    String pileId = StrUtil.sub(gunkey.substring(gunkey.lastIndexOf(":") + 1), 0, -2);
                    deviceMessage.setSerialNumber(pileId);
                    deviceMessage.setStatus(0);
                    deviceMessage.setRemark("充电桩心跳掉线");
                    deviceMessageMapper.insertByDomain(deviceMessage);
                }
            }
        }
    }

}
