package com.fxy.mine;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Switch;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.elvishew.xlog.XLog;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.views.MarqueeTextView;
import com.fxy.R;
import com.fxy.bean.BluesBean;
import com.fxy.bean.DictDataBean;
import com.fxy.constant.EventCode;
import com.fxy.constant.SPCache;
import com.fxy.utils.BlueUtils;
import com.fxy.utils.CollUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 蓝牙设置
 *
 * @author James.Jiang
 * @date 2020-03-10
 */
public class BlueSettingActivity extends BaseActivity {
    // 可用设备列表
    List<DictDataBean> availbleDictDataBeanList = new ArrayList<>();

    // 配对设备列表
    List<DictDataBean> bondedDictDataBeanList = new ArrayList<>();

    /**
     * 可用蓝牙列表适配器
     */
    private AvaiLableFinishWorkAdapter avaiLableFinishWorkAdapter;

    /**
     * 蓝牙开关
     */
    @BindView(R.id.st_blue_power)
    Switch stBluePower;
    /**
     * 允许被其他设备发现
     */
    @BindView(R.id.st_blue_discover)
    Switch stBlueDiscover;
    /**
     * 设备名称
     */
    @BindView(R.id.mt_device_name)
    MarqueeTextView mtDeviceName;
    /**
     * 搜索其他可用设备
     */
    @BindView(R.id.btn_search_blue)
    Button btnSearchBlue;
    /**
     * 可用设备列表
     */
    @BindView(R.id.available_recyclerview)
    RecyclerView availableRecyclerview;
    /**
     * 已配对设备列表
     */
    @BindView(R.id.bonded_recyclerview)
    RecyclerView bondedRecyclerview;

    // 没有数据显示页
    private View notDataView;
    // 错误显示页
    private View errorView;
    // 空显示页
    private View emptyView;

    // 蓝牙客户端socket
    private BluetoothSocket mSocket;

    private BluetoothSocket tmp = null;
    @Override
    public boolean isPlayMusic() {
        return true;
    }

    /**
     * 蓝牙适配器对象
     */
    BluetoothAdapter blueadapter;

    private static BluetoothDevice blueDevice = null;

    private String is_callback="";
    private BluesBean currentBluesBean = null;

    private Unbinder unbinder;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_blue_setting;
    }

    @Override
    public boolean showToolBar() {
        return true;
    }

    @Override
    public boolean openEventBus() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        is_callback = extras.getString("callback","");

    }
    @Override //监听按钮
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // requestCode 与请求开启 Bluetooth 传入的 requestCode 相对应

    }


    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName("蓝牙配置");
        initAdapter();
        blueadapter = BluetoothAdapter.getDefaultAdapter();
        String deviceName = null;
        if (blueadapter == null) {
            deviceName = Settings.Global.getString(this.getContentResolver(), Settings.Global.DEVICE_NAME);
            showWarningToast("抱歉,当前设备不支持蓝牙");
            stBluePower.setEnabled(false);
            stBlueDiscover.setEnabled(false);
            btnSearchBlue.setBackgroundResource(R.drawable.bg_gray_item);
            btnSearchBlue.setEnabled(false);
        } else {
            deviceName = blueadapter.getName();
            stBluePower.setChecked(blueadapter.isEnabled());
            stBlueDiscover.setChecked(blueadapter.isDiscovering());

            if (!blueadapter.isEnabled()) {
                //--如果蓝牙没有打开就提示用户打开
//                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                startActivityForResult(enableBtIntent, 1);
            }else{
                initBondedDevices();
            }


        }
        mtDeviceName.setText(deviceName);
    }


    /**
     * 初始化配对列表
     */
    private void initBondedDevices() {
        Set<BluetoothDevice> devices = blueadapter.getBondedDevices();
        // 清除配对设备
        if(CollUtil.isNotEmpty(availbleDictDataBeanList)){
            availbleDictDataBeanList.clear();
        }
        for (BluetoothDevice bluetoothDevice : devices) {
            if (bluetoothDevice.getName() !=null){
                DictDataBean dictDataBean = new DictDataBean(bluetoothDevice.getAddress(), bluetoothDevice.getName(), "已配对");
                availbleDictDataBeanList.add(dictDataBean);
            }
        }
        avaiLableFinishWorkAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.st_blue_power, R.id.st_blue_discover, R.id.btn_search_blue})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.st_blue_power:
                // 表示手机不支持蓝牙
                if (blueadapter == null) {
                    showWarningToast("当前设备不支持蓝牙");
                    return;
                }
                // 判断本机蓝牙是否打开,如果没打开，则打开蓝牙
                if (!blueadapter.isEnabled()) {
                    boolean enable = blueadapter.enable();
                    stBluePower.setChecked(enable);
                    btnSearchBlue.setEnabled(enable);
                    btnSearchBlue.setBackgroundResource(R.drawable.bg_orange_item);
                } else {
                    boolean disable = blueadapter.disable();
                    stBluePower.setChecked(!disable);
                    btnSearchBlue.setEnabled(!disable);
                    btnSearchBlue.setBackgroundResource(disable ? R.drawable.bg_orange_item : R.drawable.bg_gray_item);
                }
                break;
            case R.id.st_blue_discover:
                if(stBlueDiscover.isChecked()){
                    // 不在可被搜索的范围
                    if (blueadapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
                        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                        // 设置本机蓝牙在300秒内可见
                        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                        startActivity(discoverableIntent);
                    } else {
                        boolean cancelDiscovery = blueadapter.cancelDiscovery();
                        stBlueDiscover.setChecked(!cancelDiscovery);
                    }
                }
                break;
            case R.id.btn_search_blue:
                // 判断蓝牙是否正在扫描，如果是调用取消扫描方法；如果不是，则开始扫描
                availbleDictDataBeanList.clear();
                avaiLableFinishWorkAdapter.notifyDataSetChanged();
                if (blueadapter.isDiscovering()) {
                    blueadapter.cancelDiscovery();
                }
                ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                blueadapter.startDiscovery();
                break;
        }

    }

    // 初始化列表适配器
    private void initAdapter() {
        // 可用列表适配器
        emptyView = this.getLayoutInflater().inflate(R.layout.pager_empty, (ViewGroup) availableRecyclerview.getParent(), false);
        avaiLableFinishWorkAdapter = new AvaiLableFinishWorkAdapter(availbleDictDataBeanList);
        avaiLableFinishWorkAdapter.setEmptyView(emptyView);
        avaiLableFinishWorkAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        availableRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        availableRecyclerview.setAdapter(avaiLableFinishWorkAdapter);
        notDataView = this.getLayoutInflater().inflate(R.layout.pager_empty, (ViewGroup) availableRecyclerview.getParent(), false);
        errorView = this.getLayoutInflater().inflate(R.layout.pager_error, (ViewGroup) availableRecyclerview.getParent(), false);
        // 卡片项点击事件
        avaiLableFinishWorkAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                showLoadDialog("尝试连接中...");
                DictDataBean dictDataBean = (DictDataBean) adapter.getItem(position);
                BluetoothDevice bluetoothDevice = blueadapter.getRemoteDevice(dictDataBean.getCode());
                ClientThread clientThread = new ClientThread(bluetoothDevice, dictDataBean);
                clientThread.start();
            }
        });



    }

    private class AvaiLableFinishWorkAdapter extends BaseQuickAdapter<DictDataBean, BaseViewHolder> {

        public AvaiLableFinishWorkAdapter(List<DictDataBean> data) {
            super(R.layout.item_card_blue_available_list, data);
        }

        @Override
        protected void convert(BaseViewHolder holder, DictDataBean bean) {
            if (bean.getCode().equals(bean.getName())) {
                holder.setText(R.id.tv_item_card_first_one, bean.getCode()+"("+bean.getName()+")");
                holder.setText(R.id.tv_item_card_two, bean.getDescription());
            } else {
                holder.setText(R.id.tv_item_card_first_one, bean.getCode()+"("+bean.getName()+")");
                holder.setText(R.id.tv_item_card_two, bean.getDescription());
            }
        }

    }



    /**
     * 注册广播接收信号
     */
    private void initReceiver() {
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(bluetoothReceiver, intentFilter);
    }

    BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String description = "";
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING:
                        description = "配对中" ;
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        description = "已配对" ;
                        break;
                    case BluetoothDevice.BOND_NONE:
                        description = "未配对" ;
                    default:
                        break;
                }
                if (device.getName() !=null){
                    DictDataBean dictDataBean = new DictDataBean(device.getAddress(), device.getName(),description);
                    availbleDictDataBeanList.add(dictDataBean);
                    avaiLableFinishWorkAdapter.notifyDataSetChanged();
                }

            }
        }
    };

    @Override
    protected void onDestroy() {
        unbinder.unbind();
        try {
            mSocket.close();
        }catch (Exception e){

        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        unregisterReceiver(bluetoothReceiver);
    }

    /**
     * 子线程执行蓝牙配对
     */
    class ClientThread extends Thread {

        private BluetoothDevice bluetoothDevice;

        private DictDataBean dictDataBean;

        ClientThread(BluetoothDevice bluetoothDevice, DictDataBean dictDataBean) {
            this.bluetoothDevice = bluetoothDevice;
            this.dictDataBean = dictDataBean;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void run() {
            try {

                if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {
//                    boolean res = pair(bluetoothDevice.getAddress(),"1234");
//                    if (res){
//                        bluetoothDevice = blueDevice ;
//                    }
                }else if (bluetoothDevice.getBondState() == BluetoothDevice.BOND_BONDING){
                    BluetoothDevice device = blueadapter.getRemoteDevice(bluetoothDevice.getAddress());
                    Boolean res =BlueUtils.cancelBondProcess(device.getClass(), device);
                    XLog.e("设备正在匹配中", res);
                }


                mSocket = (BluetoothSocket) bluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(bluetoothDevice, 1);
                // 在连接蓝牙之前，还要先取消蓝牙设备的扫描，否则容易连接失败。
                if (blueadapter.isDiscovering()){
                    blueadapter.cancelDiscovery();
                }
                //如果当前socket处于非连接状态则调用连接
                if (!mSocket.isConnected()) {
                    //连接
                    mSocket.connect();
                }else{
                    showErrorToast(String.format("与蓝牙设备:[%s]正在连接中", dictDataBean.getName()));
                }

                XLog.i(String.format("与蓝牙设备:[%s]连接成功", dictDataBean.getName()));
                Looper.prepare();
                showSuccessToast(String.format("与蓝牙设备:[%s]连接成功", dictDataBean.getName()));


                // 刷新蓝牙监听
                EventBus.getDefault().post(new BaseEventBusBean<BluetoothSocket>(EventCode.refresh_blue_lister));
                dismissLoadDialog();
                mSocket.close();

                if (is_callback.equals("true")){
                    callbackView(dictDataBean);
                }

                Looper.loop();
            } catch (Exception e) {

                e.printStackTrace();
                Looper.prepare();
                showErrorToast("连接失败");
                dismissLoadDialog();
                Looper.loop();
                XLog.e(String.format("连接蓝牙[%s]失败,错误信息:%s", dictDataBean.getName(), e.getMessage()));
                //delBlue(bluetoothDevice);//直接删除

            }

        }
    }
    private void delBlue(BluetoothDevice bluetoothDevice){
        try {
            BlueUtils.removeBond(bluetoothDevice.getClass(),bluetoothDevice);// 删除链接
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void callbackView(DictDataBean dictDataBean){

        SPCache spCache = SPCache.getInstance(this);
        List<BluesBean> bluesBeanList = JsonUtil.getObjects(spCache.getBluesScalePin().toString(), BluesBean.class);

        for(BluesBean bluesBean : bluesBeanList) {
            if(dictDataBean.getName().trim().equals(bluesBean.getBlueEleScale().trim())){
                currentBluesBean = bluesBean;
                currentBluesBean.setBlueAddress(dictDataBean.getCode());
            }
        }
        if (currentBluesBean == null){
            showErrorToast("请联系技术人员增加适配蓝牙电子秤");
            return;
        }

        new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //实现页面跳转
                Intent intent=new Intent();
                intent.putExtra("bluesBean",currentBluesBean);
                setResult(200,intent);//返回值，2 是改返回的标志，也会返回
                finish();
                return false;
            }
        }).sendEmptyMessageDelayed(0,1500);//表示延迟3秒发送任务


    }

    /**
     * 自动配对
     * @param address 蓝牙地址
     * @param pin     PIN码
     * @return
     */
    public  boolean pair(String address, String pin) {
        boolean result = false;
        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
            // 检查蓝牙地址是否有效
            XLog.e(String.format("无效的蓝牙地址:%s", address));
        }
        //由蓝牙设备地址获得另一蓝牙设备对象
        BluetoothDevice device = blueadapter.getRemoteDevice(address);
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            try {
                BlueUtils.setPin(device.getClass(), device, pin);// 手机和蓝牙采集器配对
                BlueUtils.createBond(device.getClass(), device);
                blueDevice = device; // 配对完毕就把这个设备对象传给全局的bluetoothDevice
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }



}
