package com.naz.sdkdemo.helper;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.naz.sdkdemo.utils.SerialUtil;

import java.io.IOException;
import java.util.Objects;

import androidx.annotation.NonNull;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.utils.ByteUtil;

public class SerialPortManager {
    public SerialHelper serialHelper;
    private Context context;
    private Handler mHandler;
    private SerialCallBack mCallBack;

    //初始化SerialHelper对象，设定串口名称和波特率（此处为接收数据）
    public void init(Context context, String serialName, int port, SerialCallBack callBack){
        this.context = context;
        mCallBack = callBack;
        mHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                ComBean comBean = (ComBean) msg.obj;
                String rxText;
                Log.e("--------->","------->comBean.bRec="+comBean.bRec);

                // 输出转换后的UTF-8字节数组
                for (byte b : comBean.bRec) {
                    Log.e("==========>","------->comBean.bRec="+b);
                }
                rxText = ByteUtil.ByteArrToHex(comBean.bRec);
                mCallBack.dataCallBack(rxText);
            }
        };
        //-----(/dev/ttyACM0  ,  19200)
        if (serialHelper == null){
            serialHelper = new SerialHelper(serialName, port){
                @Override
                protected void onDataReceived(ComBean comBean) {
                    Message message = mHandler.obtainMessage();
                    message.obj = comBean;
                    Log.e("TAG", "onDataReceived: " + message.obj);
//            Toast.makeText(TestActivity.this, "onDataReceived: " + message.obj, Toast.LENGTH_SHORT).show();
                    mHandler.sendMessage(message);
                }
            };
            serialHelper.setStickPackageHelper(new MyStickPackageHelper());
            open();
        }
    }

    public void preValue(String hexStr){
        if (!serialHelper.isOpen()) {
            Toast.makeText(context, "串口未打开", Toast.LENGTH_SHORT).show();
            return;
        }
        serialHelper.send(SerialUtil.hexStringToByteArray(hexStr+SerialUtil.getCRC(Objects.requireNonNull(SerialUtil.hexStringToByteArray(hexStr)))));
    }
    //出标, number 1-12个工位
    public void outOfMark(int number){
        if (!serialHelper.isOpen()) {
            Toast.makeText(context, "串口未打开", Toast.LENGTH_SHORT).show();
            return;
        }
        String hexStr = "";
        switch (number){
            case 1:
                //0x01, 0x03, 0x00, 0x00, 0x00, 0x01, (byte) 0x84, (byte) 0x0A
                hexStr = "010600000001";
                break;
            case 2:
                hexStr = "010600070001";
                break;
            case 3:
                hexStr = "0106000E0001";
                break;
            case 4:
                hexStr = "010600150001";
                break;
            case 5:
                hexStr = "0106001C0001";
                break;
            case 6:
                hexStr = "010600230001";
                break;
            case 7:
                hexStr = "0106002A0001";
                break;
            case 8:
                hexStr = "010600310001";
                break;
            case 9:
                hexStr = "010600380001";
                break;
            case 10:
                hexStr = "0106003F0001";
                break;
            case 11:
                hexStr = "010600460001";
                break;
            case 12:
                hexStr = "0106004D0001";
                break;
        }
        serialHelper.send(SerialUtil.hexStringToByteArray(hexStr+SerialUtil.getCRC(Objects.requireNonNull(SerialUtil.hexStringToByteArray(hexStr)))));
    }

    //开门, number 1-3个门
    public void openDoor(int number, int type){//type 1设置，0查询
        if (!serialHelper.isOpen()) {
            Toast.makeText(context, "串口未打开", Toast.LENGTH_SHORT).show();
            return;
        }
        String hexStr = "";
        switch (number){
            case 1:
                //0x01, 0x03, 0x00, 0x00, 0x00, 0x01, (byte) 0x84, (byte) 0x0A
                if (type == 0){
                    hexStr = "010300000001";//40090~转16进制5A，待验证
                }else {
                    hexStr = "010600590001";//40090~转16进制5A，待验证
                }
                break;
            case 2:
                hexStr = "0106005A0001";
                break;
            case 3:
                hexStr = "0106005B0001";
                break;
        }
        serialHelper.send(SerialUtil.hexStringToByteArray(hexStr+SerialUtil.getCRC(Objects.requireNonNull(SerialUtil.hexStringToByteArray(hexStr)))));
    }

    //type
    //1打开黄灯 2关闭黄灯 3黄灯闪烁 4打开绿灯 5关闭绿灯 6绿灯闪烁 7打开红灯 8关闭红灯 9红灯闪烁
    //10打开蜂鸣 11间断蜂鸣 12打开红灯+蜂鸣 13打开红灯+蜂鸣 14关闭红灯+蜂鸣 15红灯闪烁+蜂鸣
    //16打开全部 17关闭全部 18全部闪烁
    // 打开黄灯：A0 01 01 A2
    //关闭黄灯：A0 01 00 A1
    //黄灯闪烁：A0 01 02 A3
    //打开绿灯：A0 02 01 A3
    //关闭绿灯：A0 02 00 A2
    //绿灯闪烁：A0 02 02 A4
    //打开红灯：A0 03 01 A4
    //关闭红灯：A0 03 00 A3
    //红灯闪烁：A0 03 02 A5
    //打开蜂鸣：A0 04 01 A5
    //关闭蜂鸣：A0 04 00 A4
    //间断蜂鸣：A0 04 02 A6
    //打开红灯+蜂鸣：A0 07 01 A8
    //关闭红灯+蜂鸣：A0 07 00 A7
    //红灯闪烁+蜂鸣：A0 07 02 A9
    //打开全部：A0 00 01 A1
    //关闭全部：A0 00 00 A0
    //全部闪烁：A0 00 02 A2
    public void turnOnLight(int type){
        if (context == null){
            return;
        }
        if (!serialHelper.isOpen()) {
            Toast.makeText(context, "串口未打开", Toast.LENGTH_SHORT).show();
            return;
        }
        String hexStr = "";
        switch (type){
            case 1:
                hexStr="A00101A2";
                break;
            case 2:
                hexStr="A00100A1";
                break;
            case 3:
                hexStr="A00102A3";
                break;
            case 4:
                hexStr="A00201A3";
                break;
            case 5:
                hexStr="A00200A2";
                break;
            case 6:
                hexStr="A00202A4";
                break;
            case 7:
                hexStr="A00301A4";
                break;
            case 8:
                hexStr="A00300A3";
                break;
            case 9:
                hexStr="A00302A5";
                break;
            case 10:
                hexStr="A00401A5";
                break;
            case 11:
                hexStr="A00400A4";
                break;
            case 12:
                hexStr="A00402A6";
                break;
            case 13:
                hexStr="A00701A8";
                break;
            case 14:
                hexStr="A00700A7";
                break;
            case 15:
                hexStr="A00702A9";
                break;
            case 16:
                hexStr="A00001A1";
                break;
            case 17:
                hexStr="A00000A0";
                break;
            case 18:
                hexStr="A00002A2";
                break;
        }

        serialHelper.send(SerialUtil.hexStringToByteArray(hexStr+SerialUtil.getCRC(Objects.requireNonNull(SerialUtil.hexStringToByteArray(hexStr)))));
    }

    //address地址码（0x01为黄灯；0x02为绿灯；0x03为红灯；0x04为蜂鸣；
    //0x05为黄灯+蜂鸣；0x06为绿灯+蜂鸣；0x07为红灯+蜂鸣；0x00为所有灯+蜂鸣）
    //type操作数据（0x00为关闭，0x01为打开，0x02为闪烁）
    //address 0,1,2,3,4,5,6,7
    //type 0,1,2
    public void turnOnLight(int address, int type){
        if (context == null){
            return;
        }
        if (!serialHelper.isOpen()) {
            Toast.makeText(context, "串口未打开", Toast.LENGTH_SHORT).show();
            return;
        }
        String addressStr = "";
        switch (address){
            case 0:
                addressStr = "00";
                break;
            case 1:
                addressStr = "01";
                break;
            case 2:
                addressStr = "02";
                break;
            case 3:
                addressStr = "03";
                break;
            case 4:
                addressStr = "04";
                break;
            case 5:
                addressStr = "05";
                break;
            case 6:
                addressStr = "06";
                break;
            case 7:
                addressStr = "07";
                break;
        }
        String typeStr = "";
        switch (type){
            case 0:
                typeStr = "00";
                break;
            case 1:
                typeStr = "01";
                break;
            case 2:
                typeStr = "02";
                break;
        }
        String hexStr = "A0"+addressStr+typeStr+hexAdd("A0", addressStr, typeStr);
        Log.e("--------->","--------->hexstr="+hexStr);

        serialHelper.send(SerialUtil.hexStringToByteArray(hexStr+SerialUtil.getCRC(Objects.requireNonNull(SerialUtil.hexStringToByteArray(hexStr)))));
    }

    //打开串口
    public void open(){
        if (serialHelper.isOpen()) {
            return;
        }
        try {
            serialHelper.open();
            if (mCallBack!=null){
                mCallBack.openCallBack(1);
            }
        } catch (Exception e) {
            if (mCallBack!=null){
                mCallBack.openCallBack(0);
            }
            e.printStackTrace();
        }
    }

    public void close(){
        if (serialHelper.isOpen()) {
            serialHelper.close();
            serialHelper = null;
        }
        if (mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        mCallBack = null;
        context = null;
    }

    public interface SerialCallBack{
        void dataCallBack(String data);
        void openCallBack(int code);//1成功，0失败
        void closeCallBack(int code);//1成功， 0失败
    }

    public static String hexAdd(String hex, String hex1, String hex2) {
        int decimal = Integer.parseInt(hex, 16);
        int decimal1 = Integer.parseInt(hex1, 16);
        int decimal2 = Integer.parseInt(hex2, 16);
        int sum = decimal + decimal1 + decimal2;
        return Integer.toHexString(sum).toUpperCase();
    }
}
