package com.zg.project.Inventory.AutoInventory.service.impl;

import com.rfidread.Enumeration.eReadType;
import com.rfidread.Interface.IAsynchronousMessage;
import com.rfidread.Models.GPI_Model;
import com.rfidread.Models.Tag_Model;
import com.rfidread.RFIDReader;
import com.zg.framework.websocket.config.WebSocketServer;
import com.zg.project.Inventory.AutoInventory.service.IRfidService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RfidServiceImpl implements IRfidService {

    private static final Logger log = LoggerFactory.getLogger(RfidServiceImpl.class);

    // 最新一次被盘点的连接ID（用来标记 EPC 来源）
    private volatile String latestConnId = null;

    // 多设备映射
    private final Map<String, String> deviceIdToConnIdMap = new ConcurrentHashMap<>(); // deviceId -> connId
    private final Map<String, String> connIdToDeviceMap = new ConcurrentHashMap<>();   // connId -> deviceId
    private final Map<String, Boolean> deviceConnectState = new ConcurrentHashMap<>(); // deviceId -> 连接状态

    private final IAsynchronousMessage callback = new IAsynchronousMessage() {

        @Override
        public void OutPutTags(Tag_Model tagModel) {
            if (latestConnId == null) {
                log.warn("EPC 来源未知：latestConnId 为空");
                return;
            }

            String deviceId = connIdToDeviceMap.get(latestConnId);
            if (deviceId != null) {
                WebSocketServer.sendMessageToDevice(deviceId, tagModel._EPC);
                log.info("推送 EPC [{}] 给设备 [{}]", tagModel._EPC, deviceId);
            } else {
                log.warn("无法通过 latestConnId={} 找到对应 deviceId", latestConnId);
            }
        }

        @Override
        public void OutPutTagsOver() {
            log.info("标签读取完成");
        }

        @Override
        public void WriteDebugMsg(String s) {
            log.debug("[DEBUG] {}", s);
        }

        @Override
        public void WriteLog(String s) {
            log.info("[LOG] {}", s);
        }

        @Override
        public void PortConnecting(String s) {
            log.info("正在连接端口：{}", s);
        }

        @Override
        public void PortClosing(String s) {
            log.info("端口已关闭：{}", s);
        }

        @Override
        public void GPIControlMsg(GPI_Model gpiModel) {
            log.info("GPI 控制 -> 设备: {}, Index: {}, 状态: {}, 时间: {}",
                    gpiModel.ReaderName, gpiModel.GpiIndex, gpiModel.GpiState, gpiModel.UtcTime);
        }

        @Override
        public void OutPutScanData(byte[] bytes) {
            log.info("原始扫描数据: {}", new String(bytes));
        }
    };

    /**
     * 建立连接
     */
    @Override
    public boolean connect(String deviceId, String ip, int port) {
        String connId = ip + ":" + port;

        boolean connected = RFIDReader.CreateTcpConn(connId, callback);
        if (connected) {
            deviceIdToConnIdMap.put(deviceId, connId);
            connIdToDeviceMap.put(connId, deviceId);
            latestConnId = connId;
            deviceConnectState.put(deviceId, true);

            log.info("建立连接成功 -> deviceId: {}, connId: {}", deviceId, connId);
        } else {
            log.error("建立连接失败 -> connId: {}", connId);
        }

        return connected;
    }

    /**
     * 开始盘点
     */
    @Override
    public boolean startScan(String deviceId) {
        String connId = deviceIdToConnIdMap.get(deviceId);
        if (connId != null) {
            latestConnId = connId; // 🟡 更新最近扫描设备
            int result = RFIDReader._Tag6C.GetEPC(connId, 1, eReadType.Inventory);
            return result == 0;
        }
        log.warn("未找到连接信息 -> deviceId: {}", deviceId);
        return false;
    }

    /**
     * 停止盘点
     */
    @Override
    public boolean stopScan(String deviceId) {
        String connId = deviceIdToConnIdMap.get(deviceId);
        if (connId != null) {
            String result = RFIDReader.Stop(connId);
            return result != null && result.startsWith("0");
        }
        log.warn("停止失败，找不到连接 -> deviceId: {}", deviceId);
        return false;
    }

    /**
     * 断开设备连接
     */
    @Override
    public void disconnect(String deviceId) {
        String connId = deviceIdToConnIdMap.remove(deviceId);
        if (connId != null) {
            RFIDReader.CloseConn(connId);
            connIdToDeviceMap.remove(connId);
        }
        deviceConnectState.remove(deviceId);

        log.info("已彻底断开连接 -> deviceId: {}, connId: {}", deviceId, connId);
    }

    /**
     * 查询连接状态
     */
    @Override
    public boolean isConnected(String deviceId) {
        return deviceConnectState.getOrDefault(deviceId, false);
    }
}