package aicare.net.cn.sdk.ailinksdkdemoandroid.modules.wifi_ble_scale;


import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.config.CmdConfig;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.device.wifibleDevice.WifiBleDeviceData;
import com.pingwang.bluetoothlib.device.wifibleDevice.WifiBleInfoBean;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;
import com.pingwang.bluetoothlib.utils.BleLog;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.config.BleDeviceConfig;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.DialogStringImageBean;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.MoveDataDialogFragment;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.ShowListDialogFragment;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.FileUtils;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.ResultContact;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.SP;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;
import cn.net.aicare.modulelibrary.module.BodyFatScale.AppHistoryRecordBean;
import cn.net.aicare.modulelibrary.module.BodyFatScale.BodyFatBleUtilsData;
import cn.net.aicare.modulelibrary.module.BodyFatScale.BodyFatDataUtil;
import cn.net.aicare.modulelibrary.module.BodyFatScale.BodyFatRecord;
import cn.net.aicare.modulelibrary.module.BodyFatScale.BodyFatUserBean;
import cn.net.aicare.modulelibrary.module.BodyFatScale.McuHistoryRecordBean;

/**
 * wifi+ble体脂秤
 */
public class WeightScaleWifiBleActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, BodyFatBleUtilsData.BleBodyFatCallback, WifiBleDeviceData.OnWiFiBleCallback {
    private String TAG = WeightScaleWifiBleActivity.class.getName();
    private String mAddress;
    private List<String> mList;
    private ArrayAdapter listAdapter;
    //    private Button wifiStatus_btn;
    private BodyFatBleUtilsData bodyFatBleUtilsData;
    private MHandler mMHandler;
    private EditText mEditText;
    private RadioButton kg, jing, stlb, lb;

    private EditText et_ip, et_path, et_port;
    private TextView tv_path;

    private ArrayList<DialogStringImageBean> mDialogList;

    private ActivityResultLauncher<Boolean> launcher;
    private WifiBleDeviceData mWifiBleDeviceData;
    private BodyFatUserBean mSelectBodyFatUserBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏
        setContentView(R.layout.activity_weight_scale_wifi_ble);
        findViewById(R.id.getWifiStatus).setOnClickListener(this);
        findViewById(R.id.getSn).setOnClickListener(this);
        findViewById(R.id.scanWifi).setOnClickListener(this);
        findViewById(R.id.connectWifi).setOnClickListener(this);
        findViewById(R.id.disconnectWifi).setOnClickListener(this);
        findViewById(R.id.getWifiName).setOnClickListener(this);
        findViewById(R.id.setedpaw).setOnClickListener(this);
        findViewById(R.id.setedmac).setOnClickListener(this);
        findViewById(R.id.ota).setOnClickListener(this);
        findViewById(R.id.surroundings).setOnClickListener(this);
        findViewById(R.id.check_ip).setOnClickListener(this);
        findViewById(R.id.check_port).setOnClickListener(this);
        findViewById(R.id.check_path).setOnClickListener(this);
        findViewById(R.id.reset).setOnClickListener(this);
        findViewById(R.id.btn_select_file).setOnClickListener(this);

        et_ip = findViewById(R.id.et_ip);
        et_port = findViewById(R.id.et_port);
        et_path = findViewById(R.id.et_path);
        mEditText = findViewById(R.id.select_wifi_et);
        kg = findViewById(R.id.kg);
        jing = findViewById(R.id.jin);
        stlb = findViewById(R.id.st_lb);
        lb = findViewById(R.id.lb);
        kg.setChecked(true);
        mAddress = getIntent().getStringExtra("mac");
        mList = new ArrayList<>();
        ListView listView = findViewById(R.id.log_list);
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        listView.setAdapter(listAdapter);

        tv_path = findViewById(R.id.tv_path);
        tv_path.setText("文件路径:手机" + File.separator + Environment.DIRECTORY_DOCUMENTS + File.separator + FileUtils.FILE_DIR);

        WeakReference weakReference = new WeakReference(new MHandler());
        mMHandler = (MHandler) weakReference.get();
        kg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance()
                                                                .setWeightUnit(BodyFatDataUtil.KG, BleDeviceConfig.WEIGHT_BODY_FAT_SCALE_WIFI_BLE));
                }
            }
        });
        jing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance()
                                                                .setWeightUnit(BodyFatDataUtil.JIN, BleDeviceConfig.WEIGHT_BODY_FAT_SCALE_WIFI_BLE));
                }
            }
        });
        stlb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance()
                                                                .setWeightUnit(BodyFatDataUtil.ST, BleDeviceConfig.WEIGHT_BODY_FAT_SCALE_WIFI_BLE));
                }
            }
        });
        lb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance()
                                                                .setWeightUnit(BodyFatDataUtil.LB, BleDeviceConfig.WEIGHT_BODY_FAT_SCALE_WIFI_BLE));
                }
            }
        });

        FileUtils.init();
        mDialogList = new ArrayList<>();
        initLauncher();
        mSelectBodyFatUserBean = getDefault();
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.reset) {
            mList.add(0, getString(R.string.reset));
            listAdapter.notifyDataSetChanged();
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.setReset();
            }
        } else if (id == R.id.getWifiStatus) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getWifiCurrentState();
            }
        } else if (id == R.id.getSn) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getDeviceSn();
            }
        } else if (id == R.id.scanWifi) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getWifiList();
                mList.add(TimeUtils.getTime() + "sacn wifi...");
                mMHandler.sendEmptyMessage(REFRESH_DATA);
            }
            showWifiList();
        } else if (id == R.id.setedmac) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getConnectWifiMac();
            }
        } else if (id == R.id.setedpaw) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getConnectWifiPwd();
            }
        } else if (id == R.id.getWifiName) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getConnectWifiSsid();
            }
        } else if (id == R.id.disconnectWifi) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.setDisconnectWifi();
            }
        } else if (id == R.id.ota) {
            showFileChooser();
        } else if (id == R.id.surroundings) {
            String ipStr = et_ip.getText().toString();
            String port = et_port.getText().toString();
            String path = et_path.getText().toString();
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.setServiceInfo(ipStr, Integer.parseInt(port), path);
            }
            mList.add(0, getString(R.string.set_environment) + ipStr + ":" + port + path);
            listAdapter.notifyDataSetChanged();
        } else if (id == R.id.check_ip) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getIp();
            }
            mList.add(0, getString(R.string.view_environment_ip));
            listAdapter.notifyDataSetChanged();
        } else if (id == R.id.check_port) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getPort();
            }
            mList.add(0, getString(R.string.view_environment_port));
            listAdapter.notifyDataSetChanged();
        } else if (id == R.id.check_path) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getPath();
            }
            mList.add(0, getString(R.string.view_environment_path));
            listAdapter.notifyDataSetChanged();
        } else if (id == R.id.btn_select_file) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                launcher.launch(true);
            } else {
                mDialogList.clear();
                ArrayList<String> list = FileUtils.list();
                for (String s : list) {
                    mDialogList.add(new DialogStringImageBean(s, 0));
                }
                ShowListDialogFragment.newInstance()
                        .setTitle("")
                        .setCancel("", 0)
                        .setCancelBlank(true)
                        .setBackground(true)
                        .setBottom(false)
                        .setList(mDialogList)
                        .setOnDialogListener(new ShowListDialogFragment.onDialogListener() {
                            @Override
                            public void onItemListener(int position) {
                                if (mDialogList.size() > position) {
                                    DialogStringImageBean dialogStringImageBean = mDialogList.get(position);
                                    String name = dialogStringImageBean.getName();
                                    SP.getInstance().putOtaFileName(name);
                                }
                            }
                        })
                        .show(getSupportFragmentManager());
            }
        }

    }


    private ShowListDialogFragment mShowListDialogFragment;
    private List<DialogStringImageBean> mDialogShowList = new ArrayList<>();

    private void showWifiList() {
        if (mShowListDialogFragment == null) {
            mShowListDialogFragment = ShowListDialogFragment.newInstance();
            mShowListDialogFragment.setList(mDialogShowList);
            mShowListDialogFragment.setTitle(getString(R.string.select_wifi));
            mShowListDialogFragment.setCancel(getString(R.string.cancel), 0);
            mShowListDialogFragment.setOnDialogListener(new ShowListDialogFragment.onDialogListener() {
                @Override
                public void onItemListener(int position) {
                    WifiBleInfoBean wifiBleInfoBean = mWifiList.get(position);
                    String ssid = wifiBleInfoBean.getSsid();
                    MoveDataDialogFragment.newInstance()
                                          .setTitle(ssid, "")
                                          .setContent("", "请输入密码", MoveDataDialogFragment.NAME)
                                          .setOk("OK", 0)
                                          .setCancel("取消", 0)
                                          .setOnDialogListener(new MoveDataDialogFragment.OnDialogListener() {
                                              @Override
                                              public void onSucceedListener(View v, String data) {
                                                  String pwd = data.trim();
                                                  setConnectWifi(wifiBleInfoBean.getMac(), pwd);

                                              }
                                          })
                                          .show(getSupportFragmentManager());
                }

                @Override
                public void onCancelListener(View v) {

                }
            });
        }
        mShowListDialogFragment.show(getSupportFragmentManager());
    }


    private BodyFatUserBean getDefault() {
        BodyFatUserBean bodyFatUserBean = new BodyFatUserBean();
        bodyFatUserBean.setModeType(BodyFatDataUtil.MODE_ORDINARY);
        bodyFatUserBean.setSex(BodyFatDataUtil.SEX_MAN);
        bodyFatUserBean.setAge(18);
        bodyFatUserBean.setHeight(170);
        bodyFatUserBean.setAdc(560);
        bodyFatUserBean.setWeight(50);
        bodyFatUserBean.setId(1);
        return bodyFatUserBean;
    }

    private void initLauncher() {
        launcher = registerForActivityResult(new ResultContact(), result -> {
            if (!TextUtils.isEmpty(result)) {
                SP.getInstance().putOtaFileName(result);
                mList.add(0, getString(R.string.select_document) + result);
                listAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onServiceSuccess() {
        BleLog.i(TAG, "服务与界面建立连接成功");
        //与服务建立连接
        if (mAILinkBleManager != null) {
            mAILinkBleManager.setOnCallbackBle(this);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                BodyFatBleUtilsData.init(bleDevice, this);
                mWifiBleDeviceData = WifiBleDeviceData.getInstance(bleDevice);
                mWifiBleDeviceData.setOnWiFiBleCallback(this);
                bodyFatBleUtilsData = BodyFatBleUtilsData.getInstance();
            }
        }
    }


    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {
        if (mAILinkBleManager != null) {
            mAILinkBleManager.removeOnCallbackBle(this);
        }
    }


    @Override
    public void onDisConnected(String mac, int code) {
        mList.add(0, getString(R.string.disconnect) + ":" + mac + "   code=" + code);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }


    @Override
    public void bleOpen() {
        mList.add(0, "ble is Open");
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void bleClose() {
        mList.add(0, "ble is Close");
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    private String mOldData = "";

    @Override
    public void onWeightData(int status, float weight, int weightUnit, int decimals) {
        String data = "Data Type：" + (status == BodyFatDataUtil.WEIGHT_TESTING ? getString(R.string.real_time) : getString(R.string.stable)) + "\nWeight: " + weight + " \nUnit：" + weightUnit + " \nDecimal point: " + decimals;
        if (mOldData.equals(data)) {
            return;
        }
        mOldData = data;
        mList.add(0, mOldData);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    private int mOldStatus = -1;

    @Override
    public void onStatus(int status) {
        if (mOldStatus == status) {
            return;
        }
        mOldStatus = status;

        switch (status) {
            case BodyFatDataUtil.WEIGHT_TESTING:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.real_time_weight));
                break;
            case BodyFatDataUtil.WEIGHT_RESULT:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.stable_weight));
                break;
            case BodyFatDataUtil.IMPEDANCE_TESTING:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.impedance_test_progress));
                break;
            case BodyFatDataUtil.IMPEDANCE_SUCCESS_DATA:
            case BodyFatDataUtil.IMPEDANCE_SUCCESS:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.impedance_test_successful));
                break;
            case BodyFatDataUtil.IMPEDANCE_FAIL:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.impedance_test_failed));
                break;
            case BodyFatDataUtil.HEART_TESTING:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.heart_rate_measuring));
                break;
            case BodyFatDataUtil.HEART_SUCCESS:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.heart_rate_test_successful));
                break;
            case BodyFatDataUtil.HEART_FAIL:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.heart_rate_test_failed));
                break;
            case BodyFatDataUtil.TEST_FINISH:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.test_completed));
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance().sendTestStatus(1));
                }
                break;
            case BodyFatDataUtil.MUC_REQUEST_USER_INFO:
                mList.add(0, getString(R.string.measurement_status) + status + "\n" + getString(R.string.request_user_information));
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance().setUserInfo(mSelectBodyFatUserBean, BleDeviceConfig.WEIGHT_BODY_FAT_SCALE));
                }
                break;
            default:
                mList.add(0, getString(R.string.measurement_status) + status);

        }
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onOtaCallback(int status) {
        switch (status) {
            case 0x00:
                mList.add(0, "ota：" + status + " wifiOTA成功");
                break;
            case 0x01:
                mList.add(0, "ota：" + status + " wifiOTA失败");
                break;
            case 0x02:
                mList.add(0, "ota：" + status + " 不支持wifiOTA");
                break;
            case 0x03:
                mList.add(0, "ota：" + status + " 模块主动开始wifiOTA（MCU收到该指令后不能断电，需要等待OTA成功或者失败）");
                break;

        }
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onAdc(int adc, int algorithmic) {
        mList.add(0, "impedance：" + adc + " 算法位：" + algorithmic);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onHeartRate(int heartrate) {
        mList.add(0, "HR：" + heartrate);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onBodyFat(BodyFatRecord bodyFatRecord) {
        mList.add(0, bodyFatRecord.toString());
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onError(int code) {
        mList.add(0, "ERR：" + code);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onHistoryMcu(McuHistoryRecordBean mcuHistoryRecordBean) {
        mList.add(0, getString(R.string.history_mcu) + mcuHistoryRecordBean.toString());
        mMHandler.sendEmptyMessage(REFRESH_DATA);
        //        mMHandler.sendEmptyMessage(ToRefreUi);
    }

    @Override
    public void onHistoryApp(AppHistoryRecordBean appHistoryRecordBean) {
        mList.add(0, getString(R.string.history_app) + appHistoryRecordBean.toString());
        mMHandler.sendEmptyMessage(REFRESH_DATA);

    }

    @Override
    public void onVersion(String version) {
        mList.add(0, "Version：" + version);
        mMHandler.sendEmptyMessage(REFRESH_DATA);

    }

    @Override
    public void onMcuBatteryStatus(int status, int battery) {
        mList.add(0, "status:" + status + "\n" + getString(R.string.power) + battery + "%");
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onSysTime(int status, int[] times) {
        mList.add(0, getString(R.string.time_status) + status);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void requestSynTime() {
        mList.add(0, getString(R.string.syn_time));
        bodyFatBleUtilsData.sendData(BodyFatDataUtil.getInstance().synTime());
    }

    @Override
    public void setTimeCallback(int type, int status) {
        String msg = "";
        if (type == CmdConfig.SET_SYS_TIME) {
            msg = getString(R.string.set_current_system_time);
        } else if (type == CmdConfig.SET_DEVICE_TIME) {
            msg = getString(R.string.syn_time);
        }
        if (status == BodyFatDataUtil.STATUS_SUCCESS) {
            msg = msg + status + getString(R.string.success);
        } else if (status == BodyFatDataUtil.STATUS_FAIL) {
            msg = msg + status + getString(R.string.failure);
        } else if (status == BodyFatDataUtil.STATUS_NOT_SUPPORT) {
            msg = msg + status + getString(R.string.not_support);
        }
        mList.add(0, msg);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void requestSynHistoryCallback(int status) {
        if (status == 0) {
            mList.add(0, status + getString(R.string.no_history));
        } else if (status == 1) {
            mList.add(0, status + getString(R.string.start_sending_history));
        } else {
            mList.add(0, status + getString(R.string.end_sending_history));
        }
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void updateUserCallback(int status) {
        if (status == 0) {
            mList.add(0, status + getString(R.string.update_user_list_success));
        } else if (status == 1) {
            mList.add(0, status + getString(R.string.update_user_success));
        } else if (status == 2) {
            mList.add(0, status + getString(R.string.update_user_list_failed));
        } else {
            mList.add(0, status + getString(R.string.update_user_failed));
        }
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void setUnitCallback(int status) {
        if (status == 0) {
            mList.add(0, getString(R.string.issued_unit_callback) + status + getString(R.string.success));
        } else if (status == 1) {
            mList.add(0, getString(R.string.issued_unit_callback) + status + getString(R.string.failure));
        } else {
            mList.add(0, getString(R.string.issued_unit_callback) + status + getString(R.string.not_support));
        }
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void requestUserData(int status) {
        if (status == 0x01) {
            mList.add(0, getString(R.string.send_user_info) + status);
        } else if (status == 0x03) {
            mList.add(0, getString(R.string.send_user_info_success) + status);
        } else {
            mList.add(0, getString(R.string.send_user_info_failure) + status);
        }
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onIpData(String ip) {
        mList.add(0, "ip：" + ip);
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPortData(int port) {
        mList.add(0, "port：" + port);
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onUrlData(String url) {
        mList.add(0, "url：" + url);
        listAdapter.notifyDataSetChanged();
    }


    private final int REFRESH_DATA = 300;

    private class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_DATA:
                    if (listAdapter != null) {
                        listAdapter.notifyDataSetChanged();
                    }
                    break;

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            String path = uri.getPath();
            SP.getInstance().put("WIFI_BLE_OTA_FILE_PATH", path);
            mList.add(0, "select file:" + path);
            listAdapter.notifyDataSetChanged();
        }
    }

    private static final int FILE_SELECT_CODE = 0x1002;

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    //----------------wifi ble-----------------//

    /**
     * 设置连接wifi
     *
     * @param mac mac
     * @param pwd 密码
     */
    private void setConnectWifi(String mac, String pwd) {
        if (mWifiBleDeviceData != null) {
            mWifiBleDeviceData.setConnectWifiMac(mac, pwd);
            mList.add(TimeUtils.getTime() + getString(R.string.connecting_wifi));
            mMHandler.sendEmptyMessage(REFRESH_DATA);
        }
    }


    @Override
    public void onBleAndWifiStatus(int bleStatus, int wifiStatus, int workStatus) {
        L.i(TAG, "蓝牙状态: " + bleStatus + " WIFI状态: " + wifiStatus + " 工作状态: " + workStatus);
        mList.add(0, getString(R.string.ble_status) + bleStatus + "\n" + getString(R.string.wifi_status) + wifiStatus + "\n" + getString(R.string.work_status) + workStatus);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onWifiScanStatus(int status) {
        L.i(TAG, "扫描wifi状态: " + status);
        mList.add(0, getString(R.string.scan_wifi_status) + status);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onConnectWifiName(String name) {
        L.i(TAG, "当前连接的WIFI名称: " + name);
        mList.add(0, getString(R.string.current_connected_wifi_name) + name);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onWifiScanBean(WifiBleInfoBean wifiBleInfoBean) {
        L.i(TAG, "扫描到的wifi信息: " + wifiBleInfoBean.toString());
//        mList.add(0, wifiBleInfoBean.toString());
//        listAdapter.notifyDataSetChanged();

    }

    private List<WifiBleInfoBean> mWifiList = new ArrayList<>();

    @Override
    public void onWifiScanFinish(List<WifiBleInfoBean> list) {
        if (mWifiList == null) {
            mWifiList = new ArrayList<>();
        }
        mWifiList.clear();
        mDialogShowList.clear();
        for (WifiBleInfoBean wifiBleInfoBean : list) {
            String ssid = wifiBleInfoBean.getSsid();
            if (TextUtils.isEmpty(ssid)) {
                continue;
            }
            mDialogShowList.add(new DialogStringImageBean(ssid, wifiBleInfoBean.getType()));
            mWifiList.add(wifiBleInfoBean);
        }
        if (mShowListDialogFragment != null) {
            mShowListDialogFragment.setList(mDialogShowList);
        }

        L.i(TAG, "扫描到的wifi信息: " + Arrays.toString(list.toArray()));

    }


    @Override
    public void onSetWifiNameOrPwdOrConnectCallback(int type, int status) {
        L.i(TAG, "设置wifi名称或密码或连接回调: " + "type: " + type + " status: " + status);
        if (type == CmdConfig.SET_WIFI_MAC) {
            mList.add(0, getString(R.string.get_set_mac_address_status) + status);
            mMHandler.sendEmptyMessage(REFRESH_DATA);

        }
        if (type == CmdConfig.SET_WIFI_PWD) {
            mList.add(0, getString(R.string.get_set_password_status) + status);
            mMHandler.sendEmptyMessage(REFRESH_DATA);
        }
        if (type == CmdConfig.DIS_OR_CON_WIFI) {
            mList.add(0, getString(R.string.initiate_connection) + ":" + status);
            mMHandler.sendEmptyMessage(REFRESH_DATA);
        }
    }

    @Override
    public void onWifiConnecting(int status) {

        L.i(TAG, "wifi连接状态: " + status);
    }

    @Override
    public void onConnectWifiMac(String mac) {
        L.i(TAG, "连接wifi的mac地址: " + mac);
        mList.add(0, getString(R.string.get_set_wifi_mac_address) + mac);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onConnectWifiPwd(String pwd) {
        L.i(TAG, "连接wifi的密码: " + pwd);
        mList.add(0, getString(R.string.get_set_wifi_password) + pwd);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onDeviceSn(long sn) {
        L.i(TAG, "设备sn: " + sn);
        mList.add(0, "sn: " + sn);
        mMHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onServerIp(String ip) {
        L.i(TAG, "服务器ip: " + ip);
    }

    @Override
    public void onServerPort(int port) {
        L.i(TAG, "服务器端口: " + port);
    }

    @Override
    public void onServerPath(String path) {
        L.i(TAG, "服务器路径: " + path);
    }

    @Override
    public void onServerSettingInfo(boolean status) {
        L.i(TAG, "服务器设置状态: " + status);
    }
}