package com.hboxs.serialport.sbc;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;


import com.hboxs.serialport.sbc.frame.VboxCommandFrame;
import com.hboxs.serialport.sbc.frame.VboxOrder;

import java.util.LinkedList;

/**
 * 串口发送队列
 */
public class VboxSerialPortSendQueue {
    private static final String TAG = "SerialPortSendQueue";
    private  VboxCommandFrame currentFrame ;
    private static VboxSerialPortSendQueue vboxSerialPortSendQueue;
    /**
     * 线程名称
     */
    private final String THREAD_NAME = "SERIAL_PORT_SEND_QUEUE";

    /**
     * 不允许创建对象
     */
    private VboxSerialPortSendQueue() {
        mSendCommandHandlerThread = new HandlerThread(THREAD_NAME);
        if (!mSendCommandHandlerThread.isAlive()) {
            mSendCommandHandlerThread.start();
            mHandler = new SendCommandHandler();
        }
        Log.d(TAG, "VboxSerialPortSendQueuec构造方法: ");
    }

    public static VboxSerialPortSendQueue getInstance(){
        if (vboxSerialPortSendQueue==null) {
            synchronized (VboxSerialPortSendQueue.class){
                if (vboxSerialPortSendQueue==null) {
                    Log.d(TAG, "getInstance VboxSerialPortSendQueuec: "+vboxSerialPortSendQueue);
                    vboxSerialPortSendQueue = new VboxSerialPortSendQueue();
                }

            }
        }
        return vboxSerialPortSendQueue;
    }

    //指令
    private LinkedList<VboxOrder> sMessageListRead = new LinkedList<>();
    private boolean isSendSuccess = true;

    private HandlerThread mSendCommandHandlerThread;
    private SendCommandHandler mHandler;


    /**
     * 发送命令的handler
     */
    private class SendCommandHandler extends Handler {
        private VboxCommandFrame frame;

        SendCommandHandler() {
            super(mSendCommandHandlerThread.getLooper());
            Log.d(TAG, "sendMessage: " + mSendCommandHandlerThread.getLooper());
            if (!mSendCommandHandlerThread.isAlive()) {
                throw new RuntimeException("发送命令队列线程尚未建立");
            }
        }

        @Override
        public void handleMessage(Message msg) {
            // 读取命令
            frame = (VboxCommandFrame) msg.obj;
            Log.d(TAG, "：测试 handleMessage22: "+currentFrame.getCmd());
            // 初始化参数
            VboxSerialPortManager.getInstance().sendCommandFrame(frame);
            // 轮询等待
            sMessageListRead.pollFirst();
                isSendSuccess = true;
        }
    }

    /**
     * 发送命令消息
     *
     * @param message 命令消息
     */
    private void sendMessage(Message message) {
        if (mHandler != null) {
            mHandler.sendMessage(message);
        } else {
            throw new RuntimeException("发送命令handler未启动");
        }
    }

    private void sendOrderMessage(VboxOrder order) {
        if (order != null) {
            Message message = new Message();
            Log.d(TAG, "sendOrderMessage: "+order);
            String padHex = padHexTo16Custom(order.getData()).replace(" ", "");
            StringBuilder stringBuilder=new StringBuilder();
            stringBuilder.append(padHex);
            Log.d("backinfo", "padHex:" + padHex);
            int sum = sumOfHexPairs(padHex);
            String hexString = intToHex4(sum);
            stringBuilder.append(hexString);
            VboxCommandFrame commandFrame = new VboxCommandFrame(order.getCmd(),stringBuilder.toString());
            currentFrame = commandFrame;
            message.obj = commandFrame;
            sendMessage(message);
        } else {
            isSendSuccess = true;
        }
      /*  if (order != null) {
            Message message = new Message();
            Log.d(TAG, "sendOrderMessage: "+order);
            VboxCommandFrame commandFrame = new VboxCommandFrame(order.getCmd(),order.getData());
            currentFrame = commandFrame;
            message.obj = commandFrame;
            sendMessage(message);
        } else {
            isSendSuccess = true;
        }*/
    }
    public String intToHex4(int number) {
        return String.format("%04X", number); // 大写补零
        // 若需小写，改用 %04x
    }
    /**
     * 校验位
     */
    public int sumOfHexPairs(String hexStr) {
        int sum = 0;
        int len = hexStr.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("输入字符串长度必须为偶数");
        }
        for (int i = 0; i < len; i += 2) {
            // 提取两位字符
            String pair = hexStr.substring(i, i + 2);
            // 转换为十进制数
            int value = Integer.parseInt(pair, 16);
            sum += value;
        }
        return sum;
    }

    /**
     * 10位字节数组，20个字符串
     */
    public String padHexTo16Custom(String hexStr) {
        int targetLength = 20;
        // 计算需补零的位数
        int zerosToAdd = targetLength - hexStr.length();
        if (zerosToAdd <= 0) {
            return hexStr; // 已满足或超过长度
        }
        // 后补零
        StringBuilder sb = new StringBuilder(hexStr);
        for (int i = 0; i < zerosToAdd; i++) {
            sb.append('0');
        }
        return sb.toString();
    }
    /**
     * 开启读list的线程
     */
    public void startReadListThread() {
        try {
            if (sMessageListRead.size() != 0) {
                if (isSendSuccess == true) {
                    isSendSuccess = false;
                    synchronized (VboxSerialPortSendQueue.class) {
                        sendOrderMessage(sMessageListRead.getFirst());
                    }
                }
                Thread.sleep(300);
            }
        } catch (Exception e) {
            e.printStackTrace();
            isSendSuccess = true;
        }
    }

    /**
     * 发送命令
     *
     * @param command 命令帧
     */
    public void sendCommand(VboxCommandFrame command) {

        synchronized (VboxSerialPortSendQueue.class) {
//            if (!sMessageListRead.isEmpty()) {
//                sMessageListRead.clear();
//            }
//            Message message = new Message();
//            message.obj = command;
//            sendMessage(message);

            VboxOrder order = new VboxOrder();
            order.setCmd(command.getCmd());
            order.setData(command.getData());
            if (!sMessageListRead.contains(order)) {
                sMessageListRead.add(order);
            }
        }
    }

    /**
     * 设置收到数据
     */
    public VboxCommandFrame setReceived() {
        return received();
    }

    private VboxCommandFrame received() {
        if (mHandler == null) {
            throw new RuntimeException("发送命令handler未启动");
        }
        VboxCommandFrame frame = mHandler.frame;
        return frame;
    }

    public VboxCommandFrame getCurrentFrame() {
        Log.d(TAG, this+"：测试 handleMessage21: "+currentFrame);
        return currentFrame;
    }


}
