package com.ycgis.macall.personalcenter.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.decoration.MyDividerItemDecoration;
import com.rs.macall.androidx.basemodel.utils.BitMapUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.m.adapterbean.BluetoothOV;
import com.ycgis.macall.personalcenter.m.datamodel.PrintModel;
import com.ycgis.macall.personalcenter.m.provider.BluetoothBroadcastReceiver;
import com.ycgis.macall.personalcenter.v.adapter.BluetoothListAdapter;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * created by:   Macall
 * create time:  2025/5/29 11:22
 * copyright:    @ruansee.com
 * Describe:
 */
public class BluetoothManage {
    private static BluetoothManage bluetoothManage;
    public final static int REQUEST_OPEN_BLUETOOTH = 0x142;
    private BluetoothAdapter bluetoothAdapter;

    private BluetoothSocket bluetoothSocket;
    private OutputStream outputStream;
    private InputStream inputStream;
    private BluetoothBroadcastReceiver receiver;

    private CallBack callBack;

    // SPP UUID
    private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    private BluetoothManage() {

    }


    public static BluetoothManage getInstance() {
        if (bluetoothManage == null) {
            synchronized (BluetoothManage.class) {
                if (bluetoothManage == null) {
                    bluetoothManage = new BluetoothManage();
                }
            }
        }
        return bluetoothManage;
    }

    /**
     * 设备是否支持蓝牙
     *
     * @return
     */
    public boolean init() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            return false;
        }
        return true;
    }

    // 发送数据
    public boolean sendData(List<PrintModel> dataList) {
        if (outputStream != null) {
            if (dataList == null) return false;
            try {
                for (int i = 0; i < dataList.size(); i++) {
                    PrintModel printModel = dataList.get(i);
                    if (printModel.getPrintType() == 1) {
                        outputStream.write(printModel.getContent().getBytes("GBK")); // 部分打印机需GBK编码
                    } else if (printModel.getPrintType() == 2) {
                        Bitmap bitmap = generateQRCode(printModel.getContent(), 100);
                        if (bitmap == null) continue;
                        outputStream.write(decodeBitmap(bitmap)); // 部分打印机需GBK编码
                    } else if (printModel.getPrintType() == 3) {
                        Bitmap bitmap = BitMapUtils.base64ToBitmap(printModel.getContent());
                        if (bitmap == null) continue;
                        outputStream.write(decodeBitmap(bitmap)); // 部分打印机需GBK编码
                    }
                }
                outputStream.flush();
                return true;
            } catch (IOException | WriterException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 判断蓝牙是否打开
     *
     * @param activity
     * @return 打开 true      false 未打开，并跳转设置页面
     */
    public boolean isBluetoothOpen(Activity activity, boolean isSkipSetting) {
        if (!bluetoothAdapter.isEnabled()) {
            if (isSkipSetting) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                activity.startActivityForResult(enableBtIntent, REQUEST_OPEN_BLUETOOTH);
            }
            return false;
        }
        return true;
    }


    // 连接指定MAC地址的打印机
    public boolean connect(String macAddress) {
        if (bluetoothAdapter == null) return false;
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddress);
        try {
            bluetoothSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
            bluetoothSocket.connect();
            outputStream = bluetoothSocket.getOutputStream();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            close();
            return false;
        }
    }

    public boolean SPPOpen(BluetoothDevice myDevice) {
        boolean error = false;
        bluetoothAdapter = bluetoothAdapter;

        if (!bluetoothAdapter.isEnabled()) {
            if (callBack != null) {
                callBack.onConnect(false, "蓝牙适配器没有打开");
            }
            return false;
        }
        bluetoothAdapter.cancelDiscovery();

        try {
            //bluetoothSocket = myDevice.createRfcommSocketToServiceRecord(SPP_UUID);
            Method m = myDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            bluetoothSocket = (android.bluetooth.BluetoothSocket) m.invoke(myDevice, 1);
        } catch (SecurityException | IllegalArgumentException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            bluetoothSocket = null;
            if (callBack != null) {
                callBack.onConnect(false, "蓝牙端口错误");
            }
            return false;
        }

        try {
            bluetoothSocket.connect();
        } catch (IOException e2) {
            if (callBack != null) {
                callBack.onConnect(false, e2.getLocalizedMessage());
            }
            bluetoothSocket = null;
            return false;
        }

        try {
            outputStream = bluetoothSocket.getOutputStream();
        } catch (IOException e3) {
            outputStream = null;
            error = true;
            return false;
        }

        try {
            inputStream = bluetoothSocket.getInputStream();
        } catch (IOException e3) {
            inputStream = null;
            error = true;
            return false;
        }

        if (error) {
            //SPPClose();
            return false;
        }

        return true;
    }

    public boolean disconnect() {
        if (!SPPClose())
            return false;
        return true;
    }

    private boolean SPPClose() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        if (outputStream != null) {
            try {
                outputStream.flush();
            } catch (IOException e1) {
            }
            try {
                outputStream.close();
            } catch (IOException e) {
            }
            outputStream = null;
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
            inputStream = null;
        }
        if (bluetoothSocket != null) {
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
            }
            bluetoothSocket = null;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        return true;
    }


    // 检查是否已连接
    public boolean isConnected() {
        return bluetoothSocket != null && bluetoothSocket.isConnected();
    }

    // 断开连接
    public void close() {
        try {
            if (outputStream != null) outputStream.close();
            if (bluetoothSocket != null) bluetoothSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputStream = null;
        bluetoothSocket = null;
    }

    public BluetoothBroadcastReceiver getReceiver() {
        if (receiver == null) {
            receiver = new BluetoothBroadcastReceiver();
        }
        return receiver;
    }

    public void searchBluetoothList(ScanCallback callback) {
        if (callback == null) return;
        BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        if (bluetoothLeScanner != null) {
            stop(callback);
            bluetoothAdapter.getBluetoothLeScanner().startScan(callback);
        }
    }

    public void stop(ScanCallback callback) {
        if (callback == null) return;
        BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.stopScan(callback);
        }
    }


    /**
     * 生成二位码图片
     *
     * @param content
     * @param size
     * @return
     * @throws WriterException
     */
    public Bitmap generateQRCode(String content, int size) throws WriterException {
        QRCodeWriter writer = new QRCodeWriter();
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size);
        Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        return bmp;
    }

    /**
     * 位图转换
     *
     * @param bmp
     * @return
     */
    public byte[] decodeBitmap(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);

        // 生成 ESC/POS 位图指令
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(0x1D);
        baos.write(0x76);
        baos.write(0x30);
        baos.write(0x00);
        baos.write(width / 8); // 宽度（以8为单位）
        baos.write(0x00);
        baos.write(height % 256); // 高度低字节
        baos.write(height / 256); // 高度高字节

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x += 8) {
                byte b = 0;
                for (int n = 0; n < 8; n++) {
                    int pixel = pixels[y * width + x + n];
                    int gray = (Color.red(pixel) + Color.green(pixel) + Color.blue(pixel)) / 3;
                    if (gray < 128) {
                        b |= (1 << (7 - n));
                    }
                }
                baos.write(b);
            }
        }
        return baos.toByteArray();
    }


    public interface CallBack {

        void onConnect(boolean connect, String msg);

        void onPrintSuccess();

        void onPrintFail(String msg);

    }

}
