package org.wcs.quartzJob;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.wcs.business.etag.EtagCommon;
import org.wcs.business.etag.EtagDataHandler;
import org.wcs.business.etag.EtagTaskExecute;
import org.wcs.business.redis.EtagRedis;
import org.wcs.constant.enums.common.OnOrOffEnum;
import org.wcs.constant.enums.common.TrueOrFalseEnum;
import org.wcs.mapper.intf.AppEtagControllerInfoService;
import org.wcs.mapper.intf.AppEtagTagInfoService;
import org.wcs.mapper.intf.AppEtagTagLocationService;
import org.wcs.model.po.app.AppEtagControllerInfo;
import org.wcs.model.po.app.AppEtagTagInfo;
import org.wcs.model.po.app.AppEtagTagLocation;
import org.wcs.plugin.tcp.SocketClient;
import org.wcs.plugin.tcp.intf.ISocketClientEvent;
import org.wcs.plugin.tcp.model.SocketDataItem;

import java.util.List;

/**
 * 电子标签定时任务类
 */
@Slf4j
@DisallowConcurrentExecution
@RequiredArgsConstructor
public class EtagJob implements Job {

    private final EtagRedis etagRedis; // 电子标签 redis 操作类
    private final EtagDataHandler etagDataHandler; // 电子标签数据处理类
    private final AppEtagControllerInfoService etagControllerInfoService; // 控制器信息数据表操作类
    private final AppEtagTagInfoService etagTagInfoService; // 电子标签小标信息数据表操作类
    private final AppEtagTagLocationService etagTagLocationService; // 电子标签位置信息数据表操作类

    private final EtagTaskExecute etagTaskExecute; // 电子标签任务执行类


    // 是否正在加载基础数据
    private static boolean isLoadingBaseData = false;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        loadBaseData(); // 加载基础资料
        connectController(); // 连接电子标签控制器
        if(EtagCommon.socketClient == null || !isLoadingBaseData) {
            return;
        }
        etagTaskExecute.lightSmallTag(); // 点亮小标签
        etagTaskExecute.lightTunnelLight(); // 点亮通道灯
        etagTaskExecute.lightSummaryTag(); // 点亮汇总标签
    }


    /**
     * 加载基础资料
     */
    private void loadBaseData() {
        if(isLoadingBaseData) {
            return;
        }
        // 加载基础小标签信息
        List<AppEtagTagInfo> etagTagInfos = etagTagInfoService.queryAll();
        if(etagTagInfos == null) {
            return;
        }
        etagRedis.clearEtagTag();
        for (AppEtagTagInfo etagTagInfo : etagTagInfos) {
            etagRedis.setEtagTag(etagTagInfo.getTagName(), etagTagInfo);
        }
        // 加载基础标签位置信息
        List<AppEtagTagLocation> etagTagLocations = etagTagLocationService.queryAll();
        if(etagTagLocations == null) {
            return;
        }
        etagRedis.clearEtagLocation();
        for (AppEtagTagLocation etagTagLocation : etagTagLocations) {
            etagRedis.setEtagLocation(etagTagLocation.getLocation(), etagTagLocation);
        }
        isLoadingBaseData = true;
    }

    /**
     * 连接电子标签控制器
     */
    private void connectController() {
        if(EtagCommon.socketClient != null) {
            EtagCommon.socketClient.checkAndReconnect();
            return;
        }
        List<AppEtagControllerInfo> etagControllerInfoList = etagControllerInfoService.queryEtagControllerInfoByStatus(OnOrOffEnum.TRUE.getCode());
        if(etagControllerInfoList == null) {
            return;
        }
        EtagCommon.socketClient = new SocketClient();
        EtagCommon.socketClient.setSocketClientEvent(new ISocketClientEvent() {
            @Override
            public void onConnect(SocketDataItem socketDataItem) {
                log.info("电子标签控制器：{} 连接成功，IP：{}，端口：{}", socketDataItem.getSocketId(), socketDataItem.getSocketIp(), socketDataItem.getSocketPort());
                // TODO 连接成功后应当重新点亮这个控制器下的标签
            }

            @Override
            public void onDisconnect(SocketDataItem socketDataItem) {
                log.info("电子标签控制器：{} 断开连接，IP：{}，端口：{}", socketDataItem.getSocketId(), socketDataItem.getSocketIp(), socketDataItem.getSocketPort());
            }

            @Override
            public void onMessage(SocketDataItem socketDataItem, String message) {
            }

            @Override
            public void onBytes(SocketDataItem socketDataItem, byte[] bytes) {
                etagDataHandler.receiveBytes(socketDataItem, bytes);
            }

            @Override
            public void onError(SocketDataItem socketDataItem, Throwable throwable) {
                log.error("电子标签控制器：{} 连接异常，IP：{}，端口：{}", socketDataItem.getSocketId(), socketDataItem.getSocketIp(), socketDataItem.getSocketPort(), throwable);
            }
        });
        for (AppEtagControllerInfo etagControllerInfo : etagControllerInfoList) {

            EtagCommon.socketClient.addSocketDataItem(SocketDataItem.buildStart()
                    .setSocketId(etagControllerInfo.getControllerId().toString())
                    .setIp(etagControllerInfo.getIp())
                    .setPort(etagControllerInfo.getPort())
                    .setTag(etagControllerInfo.getControllerName())
                    .setHeartBeatString("")
                    .buildEnd());
        }
        EtagCommon.socketClient.connectAll();
    }




}
