package com.fxy.mine;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.bean.BaseEventBusBean;
import com.fxy.baselibrary.tddialog.TDialog;
import com.fxy.baselibrary.tddialog.base.BindViewHolder;
import com.fxy.baselibrary.tddialog.base.TBaseAdapter;
import com.fxy.baselibrary.tddialog.list.TListDialog;
import com.fxy.baselibrary.tddialog.listener.OnBindViewListener;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.baselibrary.views.MarqueeTextView;
import com.fxy.R;
import com.fxy.bean.ActionBean;
import com.fxy.bean.BluesBean;
import com.fxy.bean.WeightBean;
import com.fxy.constant.EventCode;
import com.fxy.constant.SPCache;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.utils.BlueUtils;
import com.fxy.utils.CollUtil;
import com.fxy.utils.ValueUtils;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
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 ElectronicScaleActivity extends BaseActivity {

    @BindView(R.id.st_record_switch)
    Switch stRecordSwitch;

    @BindView(R.id.st_clear_weight)
    Switch stClearWeight;


    //秤名称
    @BindView(R.id.mt_scales_name)
    MarqueeTextView mtScalesName;


    @BindView(R.id.btn_save)
    Button btnSave;


    @BindView(R.id.btn_select_scales)
    Button btnSelectScales;

    /**
     * 自动称重
     */
    @BindView(R.id.et_auto_weight)
    EditText etAutoWeight;

    // 是否开启读取称重数量
    private volatile boolean isStart = true;

    /**
     * 蓝牙客户端socket
     */
    private BluetoothSocket mSocket;
    /**
     * 蓝牙适配器对象
     */
    BluetoothAdapter blueadapter;

    /**
     * 蓝牙参数列表
     */
    private  List<BluesBean> bluesScalePinList;


    /**
     * 当前连接蓝牙参数
     */
    private BluesBean currentBluesBean;

    /**
     * 需要再次连接电子秤
     */
    private Boolean connectAgain = false;

    private WeightBean weightBean;

    //蓝牙参数
    private String tmpWeight = "",oldWeight="";
    private Integer currentWay = 0;

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

    private TListDialog  cTListDialog=null;

    private BluesBean bluesBean;

    private List<BluesBean> bluesBeanList;

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



    private Unbinder unbinder;

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

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

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

    @Override
    protected void getBundleExtras(Bundle extras) {

    }


    @Override
    protected void initView() {
        unbinder = ButterKnife.bind(this);
        setTitleName("扫描配置");
        registerBlueLister();
        initEdit();


    }
    private void initEdit() {
        SPCache sp = SPCache.getInstance(this);
        String currentBluesScale = sp.getCurrentBluesScale();

        try {
            if (!currentBluesScale.isEmpty()){
                currentBluesBean = JsonUtil.getObject(currentBluesScale, BluesBean.class);
                currentWay  = currentBluesBean.getWay();
            }
        }catch (Exception e){
            currentBluesBean = null;
        }

        //
        String blueAddress = checkBlueAddress();
        if (!blueAddress.isEmpty()){
            new ConnectThread(blueadapter,blueAddress).start();
        }
    }

    private String checkBlueAddress() {


        // 获取已匹配的蓝牙设备
        Set<BluetoothDevice> deviceSet = blueadapter.getBondedDevices();
        if (CollUtil.isNotEmpty(deviceSet)) {
            setBluetoothSettings();
            return "";
        }

        for (BluetoothDevice bluetoothDevice : deviceSet) {
            if (currentBluesBean == null) {
                // 是否安衡电子秤
                for (BluesBean bluesBean : bluesScalePinList) {
                    if (bluetoothDevice.getName().toString().trim().equals(bluesBean.getBlueEleScale().toString().trim())) {
                        String address = bluetoothDevice.getAddress();
                        // 检查蓝牙地址是否有效
                        if (BluetoothAdapter.checkBluetoothAddress(address)) {
                            currentBluesBean = bluesBean;
                            currentWay = currentBluesBean.getWay();
                            currentBluesBean.setBlueAddress(address);


                            return address;
                        }
                    }
                }
            }else{
                if (bluetoothDevice.getName().trim().equals(currentBluesBean.getBlueEleScale().trim())) {
                    String address = bluetoothDevice.getAddress();
                    // 检查蓝牙地址是否有效
                    if (BluetoothAdapter.checkBluetoothAddress(address)) {
                        currentWay = currentBluesBean.getWay();
                        currentBluesBean.setBlueAddress(address);
                        return address;
                    }
                }
            }

        }

        //表示没有匹配到设置的蓝牙，更新缓存时需要再次触发连接蓝牙
        if (currentBluesBean == null) {
            setBluetoothSettings();
            return "";
        }
        return "";

    }
    private void setBluetoothSettings(){
        new AlertDialog.Builder(this)
                .setTitle(R.string.dl_hint)
                .setMessage("没有配对的蓝牙,是否前往配置?")
                .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //直接跳转到蓝牙设置界面
                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
            }
        }).show();
    }

    @OnClick({ R.id.mt_scales_name, R.id.btn_save, R.id.btn_select_scales,R.id.btn_link_blue})
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_save:
                //保存数据
                saveData();
                break;
            case R.id.btn_select_scales:
                getScalesName();
                break;
            case R.id.btn_link_blue:
                //直接跳转到蓝牙设置界面
                startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                break;
        }

    }
    private void saveData(){
        try {
            boolean isRecord = stRecordSwitch.isChecked();
            boolean isClear  = stClearWeight.isChecked();
            //boolean isClear = stClearWeight.ise;

            showSuccessToast(getString(R.string.str_save_success));
        }catch (Exception e){
            Toast.makeText(this, "保存数据失败", Toast.LENGTH_LONG).show();
            XLog.e("保存数据失败:",e.getMessage());
        }
    }




    private void getScalesName(){
        try {

            OkGo.<String>get(Urls.getServiceAddress(this) + Urls.GET_BLUES)
                    .execute(new MyDialogCallback(this,false,false) {
                        @Override
                        public void onSuccess(Response<String> response) {
//                        super.onSuccess(response);
                            try {
                                ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                                if (bean.code == 1) {
                                    SPCache spCache = SPCache.getInstance(ElectronicScaleActivity.this);
                                    spCache.setBluesScalePin(bean.data);//设置缓存
                                    List<BluesBean> bluesBeanList = JsonUtil.getObjects(bean.data, BluesBean.class);
                                    bluesScalePinList = bluesBeanList;
                                    showDialog(bluesBeanList);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                XLog.e("获取蓝牙配置信息出错:",e);
                            }
                        }
                    });
        }catch (Exception e){
            XLog.e("数据错误:",e);
        }
    }

    /**
     * 设备弹窗
     * @param
     */
    private void showDialog(List<BluesBean> bluesBeanList) {
        if (cTListDialog == null) {
            cTListDialog = (TListDialog) new TListDialog.Builder(this.getSupportFragmentManager())
                    .setListLayoutRes(R.layout.dialog_recyclerview_batch_number, LinearLayoutManager.VERTICAL)
                    .setDimAmount(0.6f)     //设置弹窗背景透明度(0-1f)
                    .setCancelOutside(true)//弹窗在界面外是否可以点击取消
//                    .setScreenHeightAspect(this,0.8f)
                    .setScreenWidthAspect(this, 0.8f)
                    .setGravity(Gravity.CENTER)
                    .setOnBindViewListener(new OnBindViewListener() {
                        @Override
                        public void bindView(BindViewHolder viewHolder) {
                            ((TextView) viewHolder.getView(R.id.txt_title)).setText("请选择设备");
                        }
                    })
                    .setAdapter(new TBaseAdapter<BluesBean>(R.layout.item_dialog_list_one,bluesBeanList) {
                        @Override
                        protected void onBind(BindViewHolder holder, int position, BluesBean bean) {

                            holder.setText(R.id.tv_dialog_list, bean.getBlueEleScale());
                        }
                    })

                    .setOnAdapterItemClickListener(new TBaseAdapter.OnAdapterItemClickListener<BluesBean>() {
                        @Override
                        public void onItemClick(BindViewHolder holder, int position, BluesBean bean, TDialog tDialog) {
                            bluesBean = bean;
                            mtScalesName.setText( bluesBean.getBlueEleScale());
                            boolean isRecord = bluesBean.getIsRecordLog()>0?true:false;
                            stRecordSwitch.setChecked(isRecord);
                            boolean isClear = bluesBean.getIsClearWeight()>0?true:false;
                            stClearWeight.setChecked(isClear);
                            tDialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        } else {
            if (!cTListDialog.isVisible()) {
                cTListDialog.show();
            }
        }
    }


    // 连接蓝牙
    class ConnectThread extends Thread {
        private BluetoothAdapter blueadapter;
        private String address;
        ConnectThread(BluetoothAdapter blueadapter,String address){
            this.blueadapter = blueadapter;
            this.address = address;
        }
        public void run() {
            Message msg = new Message();
            //由蓝牙设备地址获得另一蓝牙设备对象
            BluetoothDevice device = blueadapter.getRemoteDevice(address);
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                try {
                    BlueUtils.setPin(device.getClass(), device, currentBluesBean.getBlueEleScalePin());// 手机和蓝牙采集器配对
                    BlueUtils.createBond(device.getClass(), device);
                    mSocket = (BluetoothSocket) device.getClass().getDeclaredMethod("createRfcommSocket", new Class[]{int.class}).invoke(device, 1);
                    // 在连接蓝牙之前，还要先取消蓝牙设备的扫描，否则容易连接失败。
                    blueadapter.cancelDiscovery();
                    // 执行连接
                    mSocket.connect();
                    msg.what = 1;
                    // 开启电子秤监听
                    new ReadThread(mSocket).start();
                } catch (Exception e) {
                    msg.what = 0;
                    e.printStackTrace();
                    XLog.e("匹配蓝牙电子秤错误",e);
                }finally {
                    connectHandler.sendMessage(msg);
                }
            }
        }
    }
    /**
     * 注册蓝牙电子秤监听
     */
    private void registerBlueLister(){
        blueadapter = BluetoothAdapter.getDefaultAdapter();
        if (blueadapter == null) {
            showErrorView("非支持蓝牙设备,无法启用电子秤");
        } else{
            // 判断本机蓝牙是否打开,如果没打开，则打开蓝牙
            if (!blueadapter.isEnabled()) {
                showErrorView("蓝牙未启用,无法自动称重");
            } else {
                showSuccessToast("连接蓝牙电子秤可自动称重");
                startBlueEleScale();
            }
        }
    }
    /**
     * 启动蓝牙电子秤
     */
    private void startBlueEleScale(){
        // 获取已匹配的蓝牙设备
        Set<BluetoothDevice> deviceSet = blueadapter.getBondedDevices();
        if(CollUtil.isNotEmpty(deviceSet)){
            for(BluetoothDevice bluetoothDevice : deviceSet){
                // 是否安衡电子秤
                for(BluesBean bluesBean : bluesScalePinList) {
                    if(bluetoothDevice.getName().toString().trim().equals(bluesBean.getBlueEleScale().toString().trim())){
                        String address = bluetoothDevice.getAddress();
                        // 检查蓝牙地址是否有效
                        if (BluetoothAdapter.checkBluetoothAddress(address)) {
                            currentBluesBean = bluesBean;
                            currentWay  = currentBluesBean.getWay();
                            new ConnectThread(blueadapter,address).start();
                            break;
                        }
                    }
                }
            }

            //表示没有匹配到设置的蓝牙，更新缓存时需要再次触发连接蓝牙
            if (currentBluesBean==null){connectAgain = true; }

        }else{
            new AlertDialog.Builder(this)
                    .setTitle(R.string.dl_hint)
                    .setMessage("没有配对的蓝牙,是否前往配置?")
                    .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).setPositiveButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //直接跳转到蓝牙设置界面
                    startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
                }
            }).show();

        }
    }

    /**
     * EventBus接收信息的方法，开启后才会调用(非粘性事件)
     *
     * @param event
     */
    @Override
    protected void EventBean(BaseEventBusBean event) {
        if(event != null && event.getEventCode() == EventCode.refresh_blue_lister){
            startBlueEleScale();
        }
    }

    // 连接蓝牙处理
    private Handler connectHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                if (msg.what == 1) {

                    showSuccessToast("蓝牙电子秤连接成功,可自动称重");
                } else {
                    showErrorView("连接蓝牙电子秤错误");
                }
            }catch (Exception e){
                XLog.e(e.getMessage());
            }
        }
    };
    // 接受蓝牙数据处理
    private Handler  receiveHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                Integer reverse = 1;
                String data = (String) msg.obj;

                String strWeight = "";
                switch (currentBluesBean.getWay()){
                    case 2:
                        if (data.indexOf("=")== -1){
                            tmpWeight = tmpWeight+data;
                        }else{
                            String getWeight = tmpWeight.replace("=","");
                            tmpWeight = data;
                            if (oldWeight.equals(getWeight.toString().trim())) {
                                strWeight ="";
                            }else{
                                strWeight = getWeight;
                                oldWeight = getWeight;
                            }
                        }
                        break;
                    default:
                        strWeight = StringUtils.getMatcher("(-?\\d*)\\.?\\d+", data, 0);

                        int continuous = currentBluesBean.getContinuous();
                        weightBean.setWeightContinuous(data,1);
                        if (weightBean.getContinuous() < continuous){
                            strWeight = "";
                        }
                        break;
                }


                if(!strWeight.isEmpty()){
                    //接收返回数据
                    if (reverse.equals(currentBluesBean.getReverse())){
                        strWeight = new StringBuffer(strWeight).reverse().toString();
                    }
                    BigDecimal bigDecimalWeight = ValueUtils.getBigDecimal(strWeight).setScale(3, RoundingMode.HALF_UP);


                    etAutoWeight.setText(ValueUtils.getString(bigDecimalWeight));
                }


            }catch (Exception e){
                XLog.e(e.getMessage());
            }
        }

    };
    // 读取数据
    class ReadThread extends Thread {
        private BluetoothSocket bluetoothSocket;

        ReadThread(BluetoothSocket bluetoothSocket){
            this.bluetoothSocket = bluetoothSocket;
        }
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            InputStream is = null;
            int continuous = currentBluesBean.getContinuous();
            Integer is_record_log = currentBluesBean.getIsRecordLog();
            try {
                is = bluetoothSocket.getInputStream();
                while (isStart) {
                    if ((bytes = is.read(buffer)) > 0) {
                        byte[] buf_data = new byte[bytes];
                        for (int i = 0; i < bytes; i++) {
                            buf_data[i] = buffer[i];
                        }
                        String data = new String(buf_data);


                        if (is_record_log==1){
                            XLog.e("重量："+data);
                        }

                        // 启用自动读取并且数据不为空 有时候会上传#
                        if(StringUtils.isNotEmpty(data)){
                            Message msg = new Message();
                            msg.obj = data;
                            msg.what = 1;
                            receiveHandler.sendMessage(msg);
                        }
                    }
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }
    }


    @Override
    protected void onDestroy() {
        unbinder.unbind();


        isStart = false;
        unbinder.unbind();

        try {
            mSocket.close();

        }catch (Exception e){

        }
        connectHandler.removeCallbacksAndMessages(null);
        receiveHandler.removeCallbacksAndMessages(null);

        super.onDestroy();
    }

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

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



}
