package com.ruoyi.mill.udp;

import com.ruoyi.mill.protocol.TelegramCodec;
import com.ruoyi.mill.protocol.TelegramSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;

/**
 * UDP 发送服务 — L2→L3 上行电文
 * 帧结构：前6字节电文号 + 电文体
 */
@Component
public class UdpSender {

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

    @Autowired
    private UdpProperties props;

    /** K12F01 计划信息应答 */
    public void sendK12F01(Map<String, Object> data) {
        send(TelegramSchema.ID_K12F01, TelegramCodec.encode(TelegramSchema.SCHEMA_K12F01, data));
    }

    /** K12F02 计划钢卷删除 */
    public void sendK12F02(Map<String, Object> data) {
        send(TelegramSchema.ID_K12F02, TelegramCodec.encode(TelegramSchema.SCHEMA_K12F02, data));
    }

    /** K12F03 生产信息电文 */
    public void sendK12F03(Map<String, Object> data) {
        send(TelegramSchema.ID_K12F03, TelegramCodec.encode(TelegramSchema.SCHEMA_K12F03, data));
    }

    private void send(String tcNo, byte[] payload) {
        try (DatagramSocket socket = new DatagramSocket()) {
            // 帧 = 6字节电文号 + payload
            byte[] tcNoBytes = Arrays.copyOf(
                    tcNo.getBytes(StandardCharsets.US_ASCII), 6);
            byte[] frame = new byte[6 + payload.length];
            System.arraycopy(tcNoBytes, 0, frame, 0, 6);
            System.arraycopy(payload,  0, frame, 6, payload.length);

            InetAddress addr = InetAddress.getByName(props.getRemoteHost());
            DatagramPacket pkt = new DatagramPacket(frame, frame.length, addr, props.getRemotePort());
            socket.send(pkt);
            log.info("[UDP-SEND] tcNo={} -> {}:{} frameLen={}", tcNo,
                    props.getRemoteHost(), props.getRemotePort(), frame.length);
        } catch (Exception e) {
            log.error("[UDP-SEND] 发送失败 tcNo={}", tcNo, e);
        }
    }
}
