package com.zt.plat.module.qms.iot.tcpserver.device;

import com.alibaba.fastjson.JSONObject;
import com.zt.plat.module.qms.iot.tcpserver.IotDeviceType;
import com.zt.plat.module.qms.iot.tcpserver.IotPacket;
import com.zt.plat.module.qms.iot.tcpserver.core.ClientType;
import com.zt.plat.module.qms.iot.tcpserver.core.Command;
import com.zt.plat.module.qms.iot.tcpserver.core.IotDeviceSessionContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import tech.zzjc.tio.core.ChannelContext;
import tech.zzjc.tio.core.Tio;
import tech.zzjc.tio.starter.TioServerBootstrap;
import tech.zzjc.tio.utils.SystemTimer;
import tech.zzjc.tio.utils.lock.SetWithLock;

import java.nio.charset.Charset;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;

import static com.zt.plat.module.qms.iot.tcpserver.core.GroupConstant.CAA_ALL_CLIENT;

/**
 * <b>BalanceDataCommandLineRunner</b>
 * <p>更新历史：</p>
 * <pre> 版本         更新时间            更新者        更新内容
 * V1.0      2021-10-24          王兴荣         Add</pre>
 * <b>Copyright (C)  云南志者竟成科技有限公司</b> 
 * @author 王兴荣 &lt;xingrong_wang@will-way.cn&gt;
 * @version V1.0 
 * @since 2021-10-24
 */
@Slf4j
@Component
@AllArgsConstructor
public class BalanceDataCommandLineRunner implements CommandLineRunner {

    private final TioServerBootstrap tioServerBootstrap;
    
    //正确天平数据超时时间6s
    private final static long BALANCE_DATA_TIMEOUT = 6 * 1000L;
    
    @Override
    public void run(String... args) throws Exception {
//        System.out.println(args);
//        System.out.println(tioServerBootstrap.getServerTioConfig().heartbeatTimeout);
        Thread balanceDataCheckThread = new Thread(new Runnable() {

            @Override
            public void run() {
                //第一次先休息一下
                try {
                    Thread.sleep(BALANCE_DATA_TIMEOUT);
                } catch (InterruptedException e1) {
                    log.error(e1.toString(), e1);
                }
                while (!tioServerBootstrap.getServerTioConfig().isStopped()) {
                    try {
                        Thread.sleep(BALANCE_DATA_TIMEOUT);
                    } catch (InterruptedException e1) {
                        log.error(e1.toString(), e1);
                    }
                    //long start = SystemTimer.currTime;
                    SetWithLock<ChannelContext> setWithLock = tioServerBootstrap.getServerTioConfig().connections;
                    Set<ChannelContext> set = null;
                    long start1 = 0;
                    int count = 0;
                    ReadLock readLock = setWithLock.readLock();
                    readLock.lock();
                    try {
                        start1 = SystemTimer.currTime;
                        set = setWithLock.getObj();

                        for (ChannelContext channelContext : set) {
                            count++;
                            IotDeviceSessionContext sessionContext = (IotDeviceSessionContext) channelContext.get(IotDeviceSessionContext.DEFAULT_DEVICE_SESSION_CONTEXT_KEY);
                            if (sessionContext != null && IotDeviceType.BALANCE.getType().equals(sessionContext.getDeviceType())) {
                                //channelContext.get("lastBalanceDataTime") != null ? channelContext.get("lastBalanceDataTime").toString();
                                Object lastBalanceDataTime = channelContext.get("lastBalanceDataTime");
                                long compareTime = lastBalanceDataTime == null ? SystemTimer.currTime : Long.parseLong(lastBalanceDataTime.toString()) ;
                                long currtime = SystemTimer.currTime;
                                long interval = currtime - compareTime;
                                if (interval > BALANCE_DATA_TIMEOUT) {
//                                    sessionContext.setControlRealName("");
//                                    sessionContext.setControlChannelContext(null);
                                    sessionContext.setWeightValueList(null);
                                    
                                    //发送设备断开消息
                                    //System.out.println("发送设备断开。。。");
                                    JSONObject deviceStatusData = new JSONObject();
                                    deviceStatusData.put("deviceId", sessionContext.getDeviceId());
                                    deviceStatusData.put("deviceType", IotDeviceType.BALANCE.getType());
                                    deviceStatusData.put("connected", 0);
                                    
                                    JSONObject json = new JSONObject();
                                    json.put("cmd", Command.DEVICE_STATUS.getName());
                                    json.put("clientType", ClientType.CAA_CLIENT.getName());
                                    json.put("data", deviceStatusData);
                                    IotPacket packet = new IotPacket();
                                    packet.setBody((json.toJSONString() + "\r\n").getBytes(Charset.forName(IotPacket.CHARSET)));
                                    Tio.sendToGroup(channelContext.getTioConfig(), CAA_ALL_CLIENT, packet);
                                }
                                
                            }
                        }
                    } catch (Throwable e) {
                        log.error("", e);
                    } finally {
                        try {
                            readLock.unlock();
                        } catch (Throwable e) {
                            log.error("", e);
                        }
                    }
                    
                }
                
            }
        });
        balanceDataCheckThread.setDaemon(true);
        balanceDataCheckThread.setPriority(Thread.MIN_PRIORITY);
        balanceDataCheckThread.start();
    }

}
