package com.device.comm.mylibrary;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;

import com.device.comm.mylibrary.NativeDevice.BleNativeDevice;
import com.device.comm.mylibrary.NativeDevice.BleNativeEnuoBPDevice;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.UUID;

/**
 * Created by lvwang2002 on 16/1/28.
 */
public class BTClassicDevice extends BleDevice {

    private String TAG = "BT_CLASSIC_DEVICE";
    private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";// 蓝牙服务器的标识

    private String mMacAddress;
    private BTClassicDeviceManager mDeviceManager;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mBluetoothDevice;
    private BleDeviceManager mBleDeviceManager;
    public BTClassicDevice(BluetoothAdapter bluetoothAdapter,
                           BTClassicDeviceManager deviceManager,
                           BluetoothDevice bluetoothDevice){
        mDeviceManager = deviceManager;
        mMacAddress = bluetoothDevice.getAddress();
        mBluetoothAdapter = bluetoothAdapter;
        mBluetoothDevice = bluetoothDevice;
    }

    public  BTClassicDevice(
                           BleDeviceManager deviceManager,
                           BluetoothDevice bluetoothDevice){
        mBleDeviceManager = deviceManager;
        mMacAddress = bluetoothDevice.getAddress();
        mBluetoothDevice = bluetoothDevice;
    }


    public BluetoothDevice getBluetoothDevice(){
//        mDeviceManager.stopScan();

        return mBluetoothDevice;
    }

    public void tryConnect(){
//        mDeviceManager.stopScan();

        if(postNeeded()){
            post(new Runnable() {
                @Override
                public void run() {
                    bondBluetoothDevice(mBluetoothDevice);
                }
            });
        }else {
            bondBluetoothDevice(mBluetoothDevice);
        }
    }

    @Override
    public synchronized String getDeviceName() {
//        BluetoothDevice bluetoothDevice = getBluetoothDevice();
        String name = mBluetoothDevice.getName();
        return name;
    }
    @Override
    public String getMacAddress(){
        return mMacAddress;
    }

    public interface BTClassicDeviceCallback{
        public void onConnect(BTClassicDevice device);
        public void onDisconnect(BTClassicDevice device);
        public void onResult(BTClassicDevice device, String pul, String dia, String sys);
        public void onError(BTClassicDevice device, String error);
        public void onReceivedData(BTClassicDevice device, int value);
    }

    BTClassicDeviceCallback mClassicDeviceCallback = null;
    public  void setDeviceCallback(BTClassicDeviceCallback deviceCallback) {
        mClassicDeviceCallback = deviceCallback;
    }

    private DeviceConnectState mDeviceState = DeviceConnectState.Discovered; //0:被发现未被连接 1:正在连接 2:已经连接上 3.断开连接

    private boolean postNeeded() {
        return mBleDeviceManager.getUpdateLoop().postNeeded();
    }

    private void post(final Runnable runnable) {
        final UpdateLoop updateLoop = mBleDeviceManager.getUpdateLoop();

        updateLoop.postIfNeeded(runnable);
    }

    private boolean postMainThreadNeeded() {
        return mBleDeviceManager.getMainUpdateLoop().postNeeded();
    }

    private void postMainThread(final Runnable runnable) {
        final UpdateLoop updateLoop = mBleDeviceManager.getMainUpdateLoop();

        updateLoop.postIfNeeded(runnable);
    }

    public synchronized void bondBluetoothDevice(final BluetoothDevice device) {

//        mBluetoothAdapter.cancelDiscovery();

        int bondState = device.getBondState();

        if (bondState == BluetoothDevice.BOND_BONDED) {
            if(postNeeded()){
                post(new Runnable() {
                    @Override
                    public void run() {
                       connect();
                    }
                });
            }else{
                connect();
            }

        } else {
            try {
                Method createBondMethod = BluetoothDevice.class
                        .getMethod("createBond");
                createBondMethod.invoke(mBluetoothDevice);
            } catch (Exception e) {
//                e.printStackTrace();

//                UIHelper.showToast(BloodPressureCheckOperationActivity.this,
//                        R.string.bluetooth_bond_fail, Gravity.CENTER);
//                finish();

                mBleDeviceManager.uhOh(this,"create bound failure");
            }
        }
    }

    /** 得到设备的连接状态 */
    @Override
    public DeviceConnectState getDeviceState() {
        return mDeviceState;
    }

    /** 得到设备的显示名称  */
    @Override
    public String getDeviceDisplayName(){
        return "脉搏波血压计";
    }

    @Override
    public synchronized void connect(BleDeviceCallback deviceCallback) {
        mDeviceCallback = deviceCallback;
        post(new Runnable() {
            @Override
            public void run() {
                mBleDeviceManager.disableBleScan();
                bondBluetoothDevice(mBluetoothDevice);
                mBleDeviceManager.enableBleScan();
            }
        });
    }

    private BluetoothSocket mBluetoothSocket = null;
    private synchronized void connect() {
        UUID uuid = UUID.fromString(SPP_UUID);

        mDeviceState = DeviceConnectState.Connecting;
        boolean isConnected = false;
        Method m;
        try {
            mBluetoothSocket = mBluetoothDevice
                    .createInsecureRfcommSocketToServiceRecord(uuid);
            mBluetoothSocket.connect();

            Log.i(TAG, "ConnectThread no connect exception");
            isConnected = true;
            if(mClassicDeviceCallback != null){
                mClassicDeviceCallback.onConnect(this);
            }


        } catch (Exception e) {
            Log.d(TAG,"建立绑定失败.");
            mDeviceState = DeviceConnectState.ConnectFailed;
            mBleDeviceManager.uhOh(this,"create connect failure");

        }

        Log.i(TAG, "ConnectThread createInsecureRfcommSocketToServiceRecord isConnected="
                + isConnected);

        if (isConnected) {
            // 记录最新的连接设备名称
            mDeviceState = DeviceConnectState.Connected;
            postMainThread(new Runnable() {
                @Override
                public void run() {
                    if(mDeviceCallback == null){
                        return;
                    }

                    mDeviceCallback.onConnect(BTClassicDevice.this);
                }
            });

            return;
        }


        // 再试一下 createRfcommSocketToServiceRecord
        try {
            mBluetoothSocket = mBluetoothDevice
                    .createRfcommSocketToServiceRecord(uuid);
            if(mClassicDeviceCallback != null){
                mBluetoothSocket.connect();
            }

            isConnected = true;
        } catch (IOException e) {
            Log.i(TAG, "ConnectThread createRfcommSocketToServiceRecord exception=====>>"
                    + Log.getStackTraceString(e));

        }

        Log.d(TAG, "ConnectThread createRfcommSocketToServiceRecord isConnected="
                + isConnected);

        if (isConnected) {
            // 记录最新的连接设备名称

            mDeviceState = DeviceConnectState.Connected;

            if(mClassicDeviceCallback != null){
                mClassicDeviceCallback.onConnect(this);
            }

            postMainThread(new Runnable() {
                @Override
                public void run() {
                    if(mDeviceCallback == null){
                        return;
                    }

                    mDeviceCallback.onConnect(BTClassicDevice.this);
                }
            });

            return;
        }else{
            mDeviceState = DeviceConnectState.ConnectFailed;
            mBleDeviceManager.uhOh(this,"connect error");
        }

    }

//    private void startDiscoveryBluetooth(boolean startSearch) {
//        boolean flag = false;
//        // 记录最新的连接设备名称
//        if (lastDeviceName.length() > 0 && !startSearch) {
////            LogUtilBase.LogD(null, "startDiscoveryBluetooth false");
//
//            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
//                    .getBondedDevices();
//            if (pairedDevices != null && pairedDevices.size() > 0) {
//                for (BluetoothDevice device : pairedDevices) {
//                    String name = device.getName();
//                    if (!StringUtilBase.stringIsEmpty(name)
//                            && name.equals(lastDeviceName)) {
//                        LogUtilBase.LogD(null,
//                                "startDiscoveryBluetooth deviceName=" + name);
//                        bondBluetoothDevice(device, true);
//                        flag = true;
//                        break;
//                    }
//                }
//            }
//        }
//
//        if(flag){
//            return;
//        }
//
//
//
////        LogUtilBase.LogD(null, "startDiscoveryBluetooth true");
////        mIsStateOn = false;
////
////        // int flag = 0;
////        while (!mIsStateOn) {
////            // flag ++;
////            if (mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
////                mIsStateOn = true;
////                mBluetoothAdapter.startDiscovery();
////
////                mStartDiscovery = true;
////                // startCheckBlueTimer();// 监控蓝牙搜索时间
////                break;
////            }
////
////        }
//
//    }


//    ACTION_BOND_STATE_CHANGED

    public void actionBondStateChanged(){
        if(mBluetoothDevice != null &&
            mBluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDED){
            if(postNeeded()){
                post(new Runnable() {
                    @Override
                    public void run() {
                        mBleDeviceManager.disableBleScan();
                        connect();
                        mBleDeviceManager.enableBleScan();

                    }
                });
            }else{
                mBleDeviceManager.disableBleScan();
                connect();
                mBleDeviceManager.enableBleScan();
            }

        }else{
            Log.e(TAG,"绑定参数异常:"+mBluetoothDevice.getBondState());
        }

    }

    public void disconnect(){
        if (mInInputStream != null) {
            try {
                mInInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(mOutputStream !=null){
            try {
                mOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if( mBluetoothSocket == null )  return;

        try {
            mBluetoothSocket.close();

        } catch(IOException e) {
            Log.d(TAG,"关闭出现异常");
        }

        mBluetoothSocket = null;
        mDeviceState = DeviceConnectState.Disconnect;

        //TODO:为了兼容性,暂时保留下面代码
        if(mDeviceManager != null){
            mDeviceManager.remove(this);
        }
        mBleDeviceManager.removeDevice(this);

        //TODO:为了兼容性,暂时保留下面代码
        if(mClassicDeviceCallback != null){
            mClassicDeviceCallback.onDisconnect(this);
        }

        postMainThread(new Runnable() {
            @Override
            public void run() {
                if(mDeviceCallback == null){
                    return;
                }
                mDeviceCallback.onDisconnect(BTClassicDevice.this);
            }
        });

    }

    /** 设置原生设备的回掉,用于传递结果到界面 */
    BleNativeEnuoBPDevice.BleNativeRBPDeviceCallback mNativeDeviceCallback;
    @Override
    public void setNativeDeviceCallback(BleNativeDevice.BleNativeDeviceCallback deviceCallback) {
        mNativeDeviceCallback = (BleNativeEnuoBPDevice.BleNativeRBPDeviceCallback)deviceCallback;
    }

    private static final String REQUEST_POST_XUEYA_DATA = "request_post_xueya_data";

    public static final int SLEEP_RECEIVE_TIME = 100;// 100ms

    public static final int SLEEP_SEND_TIME = 100;// 再发送指令，延时100ms

    public static final int POWER_TOO_LOW = 3600;// 血压设备，电量低值

    // 发给血压计 (带校验码)
    private static final byte[] SEND_CHECK_POWER_PRESSURE = { (byte) 0xcc,
            (byte) 0x85, 0x02, 0x03, 0x04, 0x04, 0x00, 0x01 };// 查询电量
    private static final byte[] SEND_CONNECT_PRESSURE = { (byte) 0xcc,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x01, 0x00, 0x01 };// 连接血压计
    private static final byte[] SEND_START_PRESSURE = { (byte) 0xcc,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x02, 0x00, 0x02 };// 开始测量
    private static final byte[] SEND_STOP_PRESSURE = { (byte) 0xcc,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x03, 0x00, 0x03 };// 停止测量
    private static final byte[] SEND_CLOSE_PRESSURE = { (byte) 0xcc,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x04, 0x00, 0x04 };// 关手机

    // 收到血压计之后(血压计还会回复指令)匹配是否成功的字节数组 (带校验码)
    private static final Byte[] RECEIVE_CHECK_POWER_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x04, 0x04, 0x04 };// 查询电量(数组中没有放入校验码,和数据，共3个字节)
    private static final Byte[] RECEIVE_CONNECT_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x01, 0x00, 0x01 };// 连接血压计
    private static final Byte[] RECEIVE_START_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x02, 0x00, 0x02 };// 开始测量
    private static final Byte[] RECEIVE_STOP_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x03, 0x00, 0x03 };// 停止测量
    private static final Byte[] RECEIVE_CLOSE_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x04, 0x00, 0x04 };// 关手机

    // 收到血压计 (没有应答)
    private static final Byte[] RECEIVE_TEST_DATA_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x08, 0x01, 0x05 };// 发送过程数据的前几个字节
    private static final Byte[] RECEIVE_TEST_RESULT_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x0f, 0x01, 0x06 };// 发送测试结果数据
    private static final Byte[] RECEIVE_TEST_ERROR_PRESSURE = { (byte) 0xaa,
            (byte) 0x85, 0x02, 0x03, 0x01, 0x07 };// 发送了错误信息

    public static final int BLUE_TOOTH_STATE_SEARCHING = 10;// 正在查找
    public static final int BLUE_TOOTH_STATE_CONNECTED = 11;// 已连接
    public static final int BLUE_TOOTH_STATE_DIS_CONNECT = 12;// 已断开

    public static final int BLUE_TOOTH_SOCKET_CONNECT_FIRST = 0;// 第一次连接
    public static final int BLUE_TOOTH_SOCKET_CONNECT_SECURE = 1;// 安全socket连接
    public static final int BLUE_TOOTH_SOCKET_CONNECT_IN_SECURE = 2;// 不安全socket连接

    private static final int RECEIVE_DATA_ING = 13;// 接收过程数据13个字节
    private static final int RECEIVE_DATA_RESULT = 20;// 接收结果数据20个字节
    private static final int RECEIVE_DATA_ERROR = 8;// 血压计通信过程中返回错误信息
    private static final int RECEIVE_DATA_POWER = 9;// 血压计返回电量数据

    private static final int MSG_START_DATA_LIST = 100;
    private static final int MSG_MEASURE_EXCEPTION_FAIL = 101;

    private static final int MSG_CONNECT_SUCCESS = 200;
    private static final int MSG_CONNECT_FAIL = 201;

    private static final int MSG_POST_DATA_SUCCESS = 300;

    private static final int TAG_BTN_START_TEST = 10;
    private static final int TAG_BTN_STOP_TEST = 11;

    private boolean mStopReadThread = false;
    private boolean mReceiveCheckPower = false;
    private boolean mReceiveConnect = false;
    private boolean mReceiveStart = false;
    public boolean mReceiveDataIng = false;
    private boolean mReceiveClosePhone = false;// 暂时不用

    private boolean mRequestStopTest = false;// 请求停止测量

    private ReceiveMessageThread mReceiveMessageThread = null;

    private boolean mIsStateOn = false;

    private Timer mCheckBlueTimer;
    private boolean mCheckBlueFlag = false;
    private boolean mStartDiscovery = false;

    private String mUid;
    private String mName;
    private String mDepartment;
    private String mSickroom;
    private String mBednumber;

    private OutputStream mOutputStream;
    private InputStream mInInputStream;
    private static Object mLockObj = new Object();

    /*
	 * 开始测量
	 */
    public synchronized void sendStartTest() {
        // 防止用户频繁点击开始
        post(new Runnable() {
            @Override
            public void run() {
                if (mReceiveMessageThread == null) {

                    if (mBluetoothSocket == null) {
                        mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                        return;
                    }

                    // 连接血压计
                    boolean flag = sendTestMessage(SEND_CONNECT_PRESSURE);
                    if (flag) {
                        Log.i(TAG, "sendStartTest");

                        mStopReadThread = false;
                        mReceiveCheckPower = false;
                        startReceiveMessageThread();
                    } else {
                        mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                    }
                }
            }
        });


    }
    public synchronized void sendBTStopTest() {
        post(new Runnable() {
            @Override
            public void run() {
                if (mBluetoothSocket == null) {
                    mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                    return;
                }

                // mRequestStopTest = true;
                // sendTestMessage(SEND_STOP_PRESSURE);

                boolean flag = sendTestMessage(SEND_STOP_PRESSURE);
                if (flag) {
                    Log.i(TAG, "sendStopTest");
                    mRequestStopTest = true;
                } else {
                    mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                }
            }
        });

    }

    private boolean sendTestMessage(byte[] datas) {
        try {
            Thread.sleep(SLEEP_SEND_TIME);
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        }

        if (mBluetoothSocket == null) {
//            UIHelper.showToast(this, "蓝牙尚未连接", Gravity.CENTER);
            return false;
        }

        boolean flag = false;
        try {
            mOutputStream = mBluetoothSocket.getOutputStream();
            if (mOutputStream != null) {
                mOutputStream.flush();
                mOutputStream.write(datas);
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            mBleDeviceManager.uhOh(this,"exception error");
            try {
                if (mOutputStream != null) {
                    mOutputStream.flush();
                    mOutputStream.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
                mBleDeviceManager.uhOh(this,"exception error");
            }
        }
        return flag;
    }



    private void startReceiveMessageThread() {
        if (mReceiveMessageThread == null) {
            mReceiveMessageThread = new ReceiveMessageThread();
            mReceiveMessageThread.start();

            Log.d(null,
                    "===================================startReceiveMessageThread");
        }
    }

    private class ReceiveMessageThread extends Thread {
        @Override
        public void run() {
            synchronized (mLockObj) {

                if (mBluetoothSocket != null) {

                    try {
                        mInInputStream = mBluetoothSocket.getInputStream();

                        ArrayList<Byte> dataList = new ArrayList<Byte>();
                        byte[] buffer = null;
                        int len = 0;

                        int retryCount = 0;
                        while (!mStopReadThread) {
                            Log.d(TAG,
                                    "===================================mStopReadThread while begin");

                            dataList.clear();
                            buffer = new byte[100];

                            if (mInInputStream != null
                                    && mInInputStream.available() > 0) {
                                Log.d(null,
                                        "mInInputStream.available()="
                                                + mInInputStream.available());
                                len = mInInputStream.read(buffer);
                            } else {
                                len = 0;
                            }

                            // 发送过程中数据为13字节，（发送过程中，有可能每次不是13个字节，4个字节
                            // 9个字节两次发）发生丢包数据
                            for (int i = 0; i < len; i++) {
                                dataList.add(buffer[i]);
                                Log.d(
                                        null, getHexStringByByte(buffer[i])
                                                + "=======>len=" + len);
                            }

                            if (len > 0) {
                                mHandler.obtainMessage(MSG_START_DATA_LIST,
                                        dataList).sendToTarget();
                                Log.d(null,
                                        "==================================="
                                                + dataList.size());

                                retryCount = 0;
                            } else {
                                // 如果正在收数据中
                                if (mReceiveDataIng
                                        || mInInputStream.available() <= 0) {
                                    retryCount++;
                                    Log.d(null,
                                                    "=================================== len=0");
                                    if (retryCount >= 10 * 2) {// 收不到数据，再试执行20次接收数据，如果收不到，会报通信异常
                                        Log.d(null,
                                                "ReceiveMessageThread  retryCount="
                                                        + retryCount);
                                        mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                                        break;
                                    }
                                }
                            }

                            try {
                                Thread.sleep(SLEEP_RECEIVE_TIME);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            Log.d(null,
                                            "===================================mStopReadThread while end");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();

                        Log.d(null,
                                "ReceiveMessageThread  exception");
                        mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                    }
                } else {
                    Log.d(null,
                            "ReceiveMessageThread  mBluetoothSocket null");
                    mHandler.sendEmptyMessage(MSG_MEASURE_EXCEPTION_FAIL);
                }
            }
        }
    }

    BTClassicDevice selfDevice = this;
    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {


        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_POST_DATA_SUCCESS:

//                    JsonResult result = (JsonResult) msg.obj;

//                    if (result != null && result.code == JsonResult.CODE_SUCCESS) {
////					JSONObject jsonObject = (JSONObject) result.data;
////					try {
////						idPic = jsonObject.getString("id");
////						timeFlag = jsonObject.getString("timeFlag");
////					} catch (JSONException e) {
////						// TODO Auto-generated catch block
////						e.printStackTrace();
////					}
//
//                        File file = new File(JsonCacheUtils.pathXueYa + File.separator + JsonCacheUtils.upLoadXueYaFileName);
//                        if (file.exists()) {
//                            file.delete();
//                        }
//
//                        UIHelper.showToast(
//                                BloodPressureCheckOperationActivity.this,
//                                R.string.record_result_save_success_info,
//                                Gravity.BOTTOM);
//                    } else {
//                        UIHelper.showToast(
//                                BloodPressureCheckOperationActivity.this,
//                                R.string.record_result_save_fail_info,
//                                Gravity.BOTTOM);
//                    }

                    break;
                case MSG_START_DATA_LIST:
                    ArrayList<Byte> dataList = (ArrayList<Byte>) msg.obj;
                    doWithTestData(dataList);
                    break;
                case MSG_CONNECT_SUCCESS:

                    // old
//                    updateStartTestState();

                    // new
                    // 绑定完设备，自动查询电量,先发送连接设备指令
                    // sendStartTest();

                    // 建立连接后，禁止锁屏
//                    getWindow().addFlags(
//                            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                    break;
                case MSG_CONNECT_FAIL:
//                    mBtImgBtn.setBackgroundResource(R.drawable.bluetooth_no_device);
//                    mBtConStateTV.setText(R.string.blood_pressure_no_device);
                    break;
                case MSG_MEASURE_EXCEPTION_FAIL:

                    // 收消息异常
//                    UIHelper.showToast(getApplicationContext(),
//                            R.string.blood_pressure_test_exception, Gravity.CENTER);
//
                    stopReceiveMessageThread();
                    sendStopTestUI();

                    if (mInInputStream != null) {
                        try {
                            mInInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
//
//                    finish();
                    mBleDeviceManager.uhOh(selfDevice,"exception");
                    break;
                default:
                    break;
            }
        }
    };

private void doWithTestData(ArrayList<Byte> dataList) {
    if (dataList != null && dataList.size() > 0) {
        int totalSize = dataList.size();
//        if(dataList.size() == 8){
//            Log.d(TAG,"错误了");
//        }

        Log.d(TAG,"datalist:"+dataList.toString());
        // 收到连接血压计指令
        if (!mReceiveConnect) {
            boolean flag = false;
            if (totalSize == RECEIVE_CONNECT_PRESSURE.length) {
                for (int i = 0; i < RECEIVE_CONNECT_PRESSURE.length; i++) {
                    if (!RECEIVE_CONNECT_PRESSURE[i]
                            .equals(dataList.get(i))) {
                        flag = true;
                        break;
                    }
                }
            }

            if (!flag) {
                mReceiveConnect = true;
                // 每次测量前查询 power
                sendTestMessage(SEND_CHECK_POWER_PRESSURE);

            } else {
//                UIHelper.showToast(
//                        BloodPressureCheckOperationActivity.this,
//                        R.string.bluetooth_fail_receive_connect,
//                        Gravity.CENTER);
                Log.d(null,
                        "bluetooth_fail_receive_connect====>size="
                                + totalSize);

                stopReceiveMessageThread();
//                sendStopTestUI();
            }

            return;
        }

        // 查询电量
        if (!mReceiveCheckPower) {
            boolean flag = false;
            // 查询电量 返回数据 len = 9
            if (totalSize == RECEIVE_DATA_POWER) {
                for (int i = 0; i < RECEIVE_CHECK_POWER_PRESSURE.length; i++) {
                    if (!RECEIVE_CHECK_POWER_PRESSURE[i].equals(dataList
                            .get(i))) {
                        flag = true;
                        Log.d(null,
                                "bluetooth_fail_receive_check_power====>index="
                                        + i);
                        break;
                    }
                }
            }

            if (!flag) {

                String highString = getHexStringByByte(dataList
                        .get(totalSize - 3));
                String lowString = getHexStringByByte(dataList
                        .get(totalSize - 2));
                String hexString = highString + lowString;
                int power = Integer.parseInt(hexString, 16);

                Log.d(null,
                        "bluetooth_success_receive_check_power====>power="
                                + power + "mv");

                // 电量低于3600时，提示用户
                if (power < POWER_TOO_LOW) {
//                    UIHelper.showToast(this,
//                            R.string.blood_pressure_device_no_power,
//                            Gravity.BOTTOM);


                    stopReceiveMessageThread();

                    postMainThread(new Runnable() {
                        @Override
                        public void run() {
                            if(mNativeDeviceCallback == null){
                                return;
                            }

                            HashMap<String,String> errorInfo = new HashMap<>();
                            errorInfo.put("error","血压设备低电量，请您先充电");

                            mNativeDeviceCallback.onError(BTClassicDevice.this,errorInfo);
                        }
                    });
                } else {
                    mReceiveCheckPower = true;
                    // 开始测量
                    Log.d(null, "start_pressure-------启动测量");
                    sendTestMessage(SEND_START_PRESSURE);
                    postMainThread(new Runnable() {
                        @Override
                        public void run() {
                            if(mNativeDeviceCallback == null){
                                return;
                            }

                            mNativeDeviceCallback.onStartTest(BTClassicDevice.this);
                        }
                    });
                }

            } else {
                Log.d(null,
                        "bluetooth_fail_receive_check_power====>size="
                                + totalSize);

                stopReceiveMessageThread();
//                sendStopTestUI();
            }

            return;
        }

        // 收到开始测量指令
        if (!mReceiveStart) {
            boolean flag = false;
            if (totalSize == RECEIVE_START_PRESSURE.length) {
                for (int i = 0; i < RECEIVE_START_PRESSURE.length; i++) {
                    if (!RECEIVE_START_PRESSURE[i].equals(dataList.get(i))) {
                        flag = true;
                        break;
                    }
                }

            }

            if (!flag) {
                mReceiveStart = true;
//                sendStartTestUI();
                // 收到开始测量指令后，收到的都是过程数据，结果数据，错误数据
            } else {
//                UIHelper.showToast(
//                        BloodPressureCheckOperationActivity.this,
//                        R.string.bluetooth_fail_receive_begin,
//                        Gravity.CENTER);
                Log.d(null,
                        "bluetooth_fail_receive_begin====>size="
                                + totalSize);

                stopReceiveMessageThread();
                sendStopTestUI();
            }

            return;
        }

        // 收到停止测量指令
        if (mRequestStopTest && totalSize == RECEIVE_STOP_PRESSURE.length) {
            boolean flag = false;
            for (int i = 0; i < RECEIVE_STOP_PRESSURE.length; i++) {
                if (!RECEIVE_STOP_PRESSURE[i].equals(dataList.get(i))) {
//                    UIHelper.showToast(
//                            BloodPressureCheckOperationActivity.this,
//                            R.string.bluetooth_fail_receive_stop,
//                            Gravity.CENTER);
                    Log.d(null,
                            "bluetooth_fail_receive_stop====>index=" + i);

                    stopReceiveMessageThread();
                    sendStopTestUI();
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                // 停止测量，线程while循环结束
                stopReceiveMessageThread();
                sendStopTestUI();
            }

            return;
        }

        // ==============================================
        mReceiveDataIng = true;// 正在收数据

        boolean result = false;
        // TODO 处理血压测量过程中异常(错误数据 len = 8)
        if (totalSize == RECEIVE_DATA_ERROR) {
            // 字节数量为6个.
            boolean flag = false;
            for (int i = 0; i < RECEIVE_TEST_ERROR_PRESSURE.length; i++) {
                if (RECEIVE_TEST_ERROR_PRESSURE[i].equals(dataList.get(i))) {
                    flag = true;
                } else {
                    flag = false;
                }
            }

            if (flag) {
                byte error_state_a = 0x01;// 请检查血压计佩戴是否正确
                byte error_state_b = 0x02;// 血压计袖带过松或漏气
                byte error_state_c = 0x04;// 请保持安静 ，重新测量
                byte error_state_d = 0x07;// 血压计电量低，请充电
                // byte error_state_e = 0x15;// 测量出错，请重新测量

                final Map<String,String> errorInfo = new HashMap<String, String>();
                if (dataList.get(6).equals(error_state_a)) {
//                    UIHelper.showToast(
//                            BloodPressureCheckOperationActivity.this,
//                            R.string.blood_pressure_state_is_right,
//                            Gravity.CENTER);
                    Log.d(TAG, "=====>请检查血压计佩戴是否正确 ");
//                    mClassicDeviceCallback.onError(this,"请检查血压计佩戴是否正确");
                    errorInfo.put("error","请检查血压计佩戴是否正确");
                } else if (dataList.get(6).equals(error_state_b)) {
//                    UIHelper.showToast(
//                            BloodPressureCheckOperationActivity.this,
//                            R.string.blood_pressure_state_cuff_loose,
//                            Gravity.CENTER);
                    Log.d(TAG, "=====>血压计袖带过松或漏气");
//                    mClassicDeviceCallback.onError(this,"血压计袖带过松或漏气");
                    errorInfo.put("error","血压计袖带过松或漏气");

                } else if (dataList.get(6).equals(error_state_c)) {
//                    UIHelper.showToast(
//                            BloodPressureCheckOperationActivity.this,
//                            R.string.blood_pressure_state_keep_quiet,
//                            Gravity.CENTER);
//                    LogUtilBase.LogD(null, "=====>请保持安静 重新测量 ");
                    errorInfo.put("error","请保持安静 重新测量");

                } else if (dataList.get(6).equals(error_state_d)) {
//                    UIHelper.showToast(
//                            BloodPressureCheckOperationActivity.this,
//                            R.string.blood_pressure_state_power_low,
//                            Gravity.CENTER);
                    Log.d(null, "=====>血压计电量低，请充电 ");
//                    mClassicDeviceCallback.onError(this,"血压计电量低，请充电");
                    errorInfo.put("error","血压计电量低，请充电");


                } else {
                    // 发送数据过程中，出现错误, 退出测量
//                    UIHelper.showToast(
//                            BloodPressureCheckOperationActivity.this,
//                            R.string.bluetooth_fail_receive_ing,
//                            Gravity.CENTER);
                    Log.i(TAG,
                            "=====>bluetooth_fail_receive_ing 测量出错，请重新测量"
                                    + dataList.get(6) + "/ "
                                    + dataList.get(7));

//                    mClassicDeviceCallback.onError(this,"测量出错，请重新测量"+ dataList.get(6) + "/ "
//                            + dataList.get(7));
                    errorInfo.put("error","测量出错，请重新测量");


                }

                postMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mNativeDeviceCallback == null){
                            return;
                        }

                        mNativeDeviceCallback.onError(BTClassicDevice.this,errorInfo);
                    }
                });

                stopReceiveMessageThread();
                sendStopTestUI();
            }
        }

        if (totalSize == RECEIVE_DATA_ING) {
            result = false;
        } else if (totalSize == RECEIVE_DATA_RESULT) {
            result = true;
        } else {
            // 可能会有丢包数据，不处理，不更新ui
            Log.d(null,
                    "发生丢包数据=========>>" + String.valueOf(totalSize));
            return;
        }

        if (result) {
            // TODO 结果判断异常处理
            for (int i = 0; i < RECEIVE_TEST_RESULT_PRESSURE.length; i++) {
                if (!dataList.get(i)
                        .equals(RECEIVE_TEST_RESULT_PRESSURE[i])) {
                    Log.d(TAG,
                            "发生错误数据=========>>" + dataList.toString());
                    return;
                }
            }
            int pul_0 = toTenInt((dataList.get(totalSize - 2)));
            int pul_1 = toTenInt((dataList.get(totalSize - 3)));
            int dia_0 = toTenInt((dataList.get(totalSize - 4)));
            int dia_1 = toTenInt((dataList.get(totalSize - 5)));
            int sys_0 = toTenInt((dataList.get(totalSize - 6)));
            int sys_1 = toTenInt((dataList.get(totalSize - 7)));

            int pul = pul_1 ^ pul_0;
            int dia = dia_1 ^ dia_0;
            int sys = sys_1 ^ sys_0;

            Log.d(TAG, "pul=========>>" + String.valueOf(pul));
            Log.d(TAG, "dia=========>>" + String.valueOf(dia));
            Log.d(TAG, "sys=========>>" + String.valueOf(sys));
            final Map<String,String> info = new HashMap<String, String>();
            info.put("pul",""+pul);
            info.put("dia",""+dia);
            info.put("sys",""+sys);
//            mClassicDeviceCallback.onResult(this,String.valueOf(pul),String.valueOf(dia),String.valueOf(sys));
            postMainThread(new Runnable() {
                @Override
                public void run() {
                    if(mNativeDeviceCallback == null){
                        return;
                    }

                    mNativeDeviceCallback.onResult(BTClassicDevice.this,info);
                }
            });
            stopReceiveMessageThread();
            sendStopTestUI();

            // TODO 处理结果`
//            updateUI(false);
//            TextView bloodPressureHighTV = (TextView) findViewById(R.id.bloodPressureHighTextView);
//            TextView bloodPressureLowTV = (TextView) findViewById(R.id.bloodPressureLowTextView);
//            TextView bloodPressureHeartTV = (TextView) findViewById(R.id.heartTextView);
//
//            bloodPressureHighTV.setText(String.valueOf(sys));
//            bloodPressureLowTV.setText(String.valueOf(dia));
//            bloodPressureHeartTV.setText(String.valueOf(pul));
//
//            String LHPress = "已检测  " + String.valueOf(sys) + "/" + String.valueOf(dia) + "mmHg" + "  " + String.valueOf(pul) + "bpm";
//
//            for (int i = 1; i < JsonCacheUtils.PAGE_XUEYA + 1; i++) {
//                File file = new File(JsonCacheUtils.pathXueYa + File.separator + "downLoadData_" + i + ".txt");
//                if (file.exists()) {
//                    String jsonCache = JsonCacheUtils.readJsonCache(file).trim();
//                    mArrayList = JsonParserBase.parseJsonCheckMain(jsonCache , WebDataTypeBase.APP_XUEYA_CHECK_LIST);
//                    for(CheckItem ci : mArrayList){
//                        if (ci.uid.equals(mUid)) {
//                            ci.istest = LHPress;
//                        }
//                    }
//                    String savaJson = JsonCacheUtils.listToJsonStirng(mArrayList);
//                    JsonCacheUtils.writeJsonCache(savaJson, "downLoadData_" + i + ".txt" , JsonCacheUtils.pathXueYa);
//                }
//            }
//
//            // TODO 上传数据
//            postUpdateBloodPressureData(String.valueOf(sys),
//                    String.valueOf(dia), String.valueOf(pul));

        } else {
            // int d5 = UtilityBase.toTenInt(dataList
            // .get(totalSize - 7));
            int d4 = toTenInt(dataList.get(totalSize - 6));
            // int d3 = UtilityBase.toTenInt(dataList
            // .get(totalSize - 5));
            // int d2 = UtilityBase.toTenInt(dataList
            // .get(totalSize - 4));
            int d1 = toTenInt(dataList.get(totalSize - 3));
            // int d0 = UtilityBase.toTenInt(dataList
            // .get(totalSize - 2));

            int p = (d4 << 8) + (d4 ^ d1);
            Log.d(TAG, "p=========>>" + String.valueOf(p));
//            mClassicDeviceCallback.onReceivedData(this,p);
//            mBloodPreValueTV.setText(String.format("%03d", p));
            final HashMap<String,String> valueInfo = new HashMap<>();
            valueInfo.put("value",""+p);
            postMainThread(new Runnable() {
                @Override
                public void run() {
                    if(mNativeDeviceCallback == null){
                        return;
                    }

                    mNativeDeviceCallback.onProgressValue(BTClassicDevice.this,valueInfo);
                }
            });

        }
    } else {
        // ====================================
        // 这种情况不会出现，接收消息线程已判断，大于0才会进入handler
        // UIHelper.showToast(getApplicationContext(),
        // R.string.bluetooth_fail_receive_no, Gravity.CENTER);
    }
}


    private void stopReceiveMessageThread() {
        if (mReceiveMessageThread != null) {
            mReceiveConnect = false;
            mReceiveStart = false;
            mReceiveDataIng = false;

            mRequestStopTest = false;

            mStopReadThread = true;
            if (mReceiveMessageThread.isAlive()) {
                mReceiveMessageThread.interrupt();
            }
            mReceiveMessageThread = null;

            Log.d(null,
                            "===================================stopReceiveMessageThread");
        }
    }

    public static String getHexStringByByte(byte b) {
        return Integer.toHexString(b & 0xff);
    }

    /*
	 * byte====》10进制
	 */
    public static int toTenInt(byte b) {
        String hexValue = Integer.toHexString(b & 0xff);
        return Integer.parseInt(hexValue, 16);
    }

    private void sendStopTestUI() {
        Log.d(TAG,"停止界面");
    }

}
