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

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.pingwang.bluetoothlib.config.BleConfig;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.listener.CallbackDisIm;
import com.pingwang.bluetoothlib.listener.OnCallbackDis;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.CheckPermissionUtils;
import cn.net.aicare.modulelibrary.module.bw05.Bw05WatchBleDevice;
import cn.net.aicare.modulelibrary.module.bw05.OnBw05WatchDataListener;

/**
 * @author ljl
 * on 2024/6/4
 */
public class Bw05WatchActivity extends BleBaseActivity implements OnBw05WatchDataListener,
        View.OnClickListener, OnCallbackDis {

    //01:B6:EC:E6:C8:8D
    private String connectMac = "";

    private Button btnSetTime, btnQueryInfo, btnQueryThreshold;
    private Button btnSetCheckTime, btnSetBleName, btnSetThreshold;
    private Button btnConnect, btnClearLog, btnHisTime;
    private Button btnQueryTheme, btnSetThemeNum;

    private Button btnQueryVersion, btnSetBind, btnQueryHardware;

    private EditText etCheckTime, etBleName;
    private EditText etHrMin, etHrMax;
    private EditText etSpo2Min, etSpo2Max;
    private EditText etTempMin, etTempMax;
    private EditText etSbpMin, etSbpMax;
    private EditText etDbpMin, etDbpMax;
    private EditText etMac, etThemeNum, etHisTime;

    private CheckBox cbCheckTime, cbHisTime;

    private ListView log_list;

    private List<String> mList;
    private ArrayAdapter mListAdapter;

    private String checkTimeOp, hisTimeOp;

    private Bw05WatchBleDevice mBw05WatchBleDevice;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bw05_watch);
        initView();
        initData();
    }

    private void initView() {
        btnSetTime = findViewById(R.id.btnSetTime);
        btnSetTime.setOnClickListener(this);
        btnQueryInfo = findViewById(R.id.btnQueryInfo);
        btnQueryInfo.setOnClickListener(this);
        btnQueryThreshold = findViewById(R.id.btnQueryThreshold);
        btnQueryThreshold.setOnClickListener(this);
        btnSetCheckTime = findViewById(R.id.btnSetCheckTime);
        btnSetCheckTime.setOnClickListener(this);
        btnSetBleName = findViewById(R.id.btnSetBleName);
        btnSetBleName.setOnClickListener(this);
        btnSetThreshold = findViewById(R.id.btnSetThreshold);
        btnSetThreshold.setOnClickListener(this);
        btnConnect = findViewById(R.id.btnConnect);
        btnConnect.setOnClickListener(this);
        btnClearLog = findViewById(R.id.btnClearLog);
        btnClearLog.setOnClickListener(this);
        btnQueryTheme = findViewById(R.id.btnQueryTheme);
        btnQueryTheme.setOnClickListener(this);
        btnSetThemeNum = findViewById(R.id.btnSetThemeNum);
        btnSetThemeNum.setOnClickListener(this);
        btnQueryVersion = findViewById(R.id.btnQueryVersion);
        btnQueryVersion.setOnClickListener(this);
        btnSetBind = findViewById(R.id.btnSetBind);
        btnSetBind.setOnClickListener(this);
        btnQueryHardware = findViewById(R.id.btnQueryHardware);
        btnQueryHardware.setOnClickListener(this);
        btnHisTime = findViewById(R.id.btnHisTime);
        btnHisTime.setOnClickListener(this);

        etCheckTime = findViewById(R.id.etCheckTime);
        etBleName = findViewById(R.id.etBleName);
        etHrMin = findViewById(R.id.etHrMin);
        etHrMax = findViewById(R.id.etHrMax);
        etSpo2Min = findViewById(R.id.etSpo2Min);
        etSpo2Max = findViewById(R.id.etSpo2Max);
        etTempMin = findViewById(R.id.etTempMin);
        etTempMax = findViewById(R.id.etTempMax);
        etSbpMin = findViewById(R.id.etSbpMin);
        etSbpMax = findViewById(R.id.etSbpMax);
        etDbpMin = findViewById(R.id.etDbpMin);
        etDbpMax = findViewById(R.id.etDbpMax);
        etMac = findViewById(R.id.etMac);
        etThemeNum = findViewById(R.id.etThemeNum);
        etHisTime = findViewById(R.id.etHisTime);

        cbCheckTime = findViewById(R.id.cbCheckTime);
        cbHisTime = findViewById(R.id.cbHisTime);

        checkTimeOp = cbCheckTime.isChecked() ? "1" : "0";
        hisTimeOp = cbHisTime.isChecked() ? "1" : "0";

        cbCheckTime.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                checkTimeOp = "1";
            } else {
                checkTimeOp = "0";
            }
        });

        cbHisTime.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                hisTimeOp = "1";
            } else {
                hisTimeOp = "0";
            }
        });

        etTempMin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().length() == 1 && s.toString().equals(".")) {
                    s.clear();
                }
            }
        });

        etTempMax.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().length() == 1 && s.toString().equals(".")) {
                    s.clear();
                }
            }
        });

        log_list = findViewById(R.id.log_list);
    }

    private void initData() {
        mList = new ArrayList<>();
        mListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        log_list.setAdapter(mListAdapter);

        new CheckPermissionUtils(this).checkPermissions(() -> {

        });

        // 没有蓝牙权限就请求蓝牙权限
        if (!hasBluetooth()) {
            requestBluetooth();
            return;
        }
        // 没有定位权限就请求定位权限
        if (!hasLocationPermission()) {
            requestLocationPermission(this);
            return;
        }
        // 没有定位服务就请求定位服务
        if (!hasLocationService()) {
            requestLocationService();
            return;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        int id = v.getId();
        if (id == R.id.btnSetTime) {//设置时间
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.setTime();
            }
        } else if (id == R.id.btnQueryInfo) {//查询信息
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.queryInfo();
            }
        } else if (id == R.id.btnQueryThreshold) {//查询阈值
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.queryThreshold();
            }
        } else if (id == R.id.btnSetCheckTime) {//设置检测间隔时间
            if (!TextUtils.isEmpty(etCheckTime.getText().toString())) {
                if (etCheckTime.getText().toString().length() < 4 && mBw05WatchBleDevice != null) {
                    mBw05WatchBleDevice.setCheckTime(checkTimeOp + formatDataStr(etCheckTime.getText().toString(), 3));
                }
            }
        } else if (id == R.id.btnSetBleName) {//设置蓝牙名称
            if (!TextUtils.isEmpty(etBleName.getText().toString())) {
                if (mBw05WatchBleDevice != null) {
                    mBw05WatchBleDevice.setBleName(etBleName.getText().toString());
                }
            }
        } else if (id == R.id.btnSetThreshold) {//设置阈值
            if (!TextUtils.isEmpty(getFloatThresholdValue(etTempMin.getText().toString(), etTempMin.getHint().toString()))
                    && !TextUtils.isEmpty(getFloatThresholdValue(etTempMax.getText().toString(), etTempMax.getHint().toString()))) {
                if (mBw05WatchBleDevice != null) {
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(getIntThresholdValue(etHrMin.getText().toString(), etHrMin.getHint().toString()));
                    stringBuilder.append(getIntThresholdValue(etHrMax.getText().toString(), etHrMax.getHint().toString()));
                    stringBuilder.append(getIntThresholdValue(etSpo2Min.getText().toString(), etSpo2Min.getHint().toString()));
                    stringBuilder.append(getIntThresholdValue(etSpo2Max.getText().toString(), etSpo2Max.getHint().toString()));
//                        stringBuilder.append(getIntThresholdValue(etSbpMin.getText().toString(), etSbpMin.getHint().toString()));
//                        stringBuilder.append(getIntThresholdValue(etSbpMax.getText().toString(), etSbpMax.getHint().toString()));
//                        stringBuilder.append(getIntThresholdValue(etDbpMin.getText().toString(), etDbpMin.getHint().toString()));
//                        stringBuilder.append(getIntThresholdValue(etDbpMax.getText().toString(), etDbpMax.getHint().toString()));
                    stringBuilder.append(getFloatThresholdValue(etTempMin.getText().toString(), etTempMin.getHint().toString()));
                    stringBuilder.append(getFloatThresholdValue(etTempMax.getText().toString(), etTempMax.getHint().toString()));

                    String payLoadStr = stringBuilder.toString();
                    mBw05WatchBleDevice.setRangeValue(payLoadStr);
                }
            }
        } else if (id == R.id.btnConnect) {//连接设备
            if (btnConnect.getText().toString().equals("连接")) {
                if (!TextUtils.isEmpty(etMac.getText().toString()) && isValidMacAddress(etMac.getText().toString()) && mAILinkBleManager != null) {
                    connectMac = etMac.getText().toString();
                    connectBle(connectMac.toUpperCase());
                } else {
                    Toast.makeText(this, "MAC地址出错", Toast.LENGTH_SHORT).show();
                }
            } else {
                if (mAILinkBleManager != null && !TextUtils.isEmpty(connectMac)) {
                    mAILinkBleManager.disconnect(connectMac.toUpperCase());
                }
            }
        } else if (id == R.id.btnQueryTheme) {//查询主题
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.queryTheme();
            }
        } else if (id == R.id.btnSetThemeNum) {//设置主题
            if (!TextUtils.isEmpty(etThemeNum.getText().toString()) && ("1".equals(etThemeNum.getText().toString())
                    || "2".equals(etThemeNum.getText().toString()) || "3".equals(etThemeNum.getText().toString()))) {
                if (mBw05WatchBleDevice != null) {
                    mBw05WatchBleDevice.setTheme(etThemeNum.getText().toString());
                }
            } else {
                Toast.makeText(this, "只支持输入1，2，3", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.btnQueryVersion) {//查询手环版本号
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.queryVersion();
            }
        } else if (id == R.id.btnSetBind) {//设置手环进入绑定模式
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.setBindMode();
            }
        } else if (id == R.id.btnQueryHardware) {//查询硬件状态
            if (mBw05WatchBleDevice != null) {
                mBw05WatchBleDevice.queryHardware();
            }
        } else if (id == R.id.btnHisTime) {//设置历史上传间隔
            if (!TextUtils.isEmpty(etHisTime.getText().toString())) {
                if (etHisTime.getText().toString().length() < 5 && mBw05WatchBleDevice != null) {
                    int time = Integer.parseInt(etHisTime.getText().toString());
                    mBw05WatchBleDevice.setHisTime(hisTimeOp + String.format(Locale.US, "%04d", time));
                }
            }
        } else if (id == R.id.btnClearLog) {
            clearText();
        }
    }

    // 清空文本
    private void clearText() {
        mList.clear();
        mListAdapter.notifyDataSetChanged();
    }

    private SimpleDateFormat mSdf;

    // 添加一条文本
    private void addText(String text) {
        if (mSdf == null) {
            mSdf = new SimpleDateFormat("HH:mm:ss:SSS", Locale.US);
        }
        mList.add(mSdf.format(System.currentTimeMillis()) + "：\n" + text);
        mListAdapter.notifyDataSetChanged();
        log_list.smoothScrollToPosition(mList.size() - 1);
    }

    @Override
    public void onServiceSuccess() {
        CallbackDisIm.getInstance().addListListener(this);
    }

    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {

    }

    @Override
    public void bleClose() {
        addText("蓝牙未开启,请退出打开蓝牙重试");
    }

    @Override
    public void onDataStr(String dataStr) {
        addText(dataStr);
    }

    @Override
    public void onConnecting(String mac) {
        addText("正在连接设备:" + mac);
    }

    @Override
    public void onConnectionSuccess(String mac) {
        BleConfig.setHandshakeStatus(mac, false);
    }

    @Override
    public void onServicesDiscovered(String mac) {
        addText("连接成功:" + mac);
        if (mAILinkBleManager != null) {
            runOnUiThread(() -> {
                btnConnect.setText("断开");
            });
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mac);
            Bw05WatchBleDevice.init(bleDevice);
            mBw05WatchBleDevice = Bw05WatchBleDevice.getInstance();
            mBw05WatchBleDevice.setOnBw05WatchDataListener(this);
        }
    }

    @Override
    public void onDisConnected(String mac, int code) {
        addText("连接断开:" + mac + "错误码:" + code);
        runOnUiThread(() -> {
            btnConnect.setText("连接");
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CallbackDisIm.getInstance().removeListener(this);
        if (mAILinkBleManager != null) {
            mAILinkBleManager.disconnect(connectMac);
        }
    }

    /**
     * 转整数
     *
     * @param inputStr 输入的数据
     * @return
     */
    private int getIntData(String inputStr) {
        try {
            return Integer.parseInt(inputStr);
        } catch (Exception e) {
            return -1000;
        }
    }

    /**
     * 转浮点型
     *
     * @param inputStr 输入的数据
     * @return
     */
    private float getFloatData(String inputStr) {
        try {
            return Float.parseFloat(inputStr);
        } catch (Exception e) {
            return -1000;
        }
    }

    /**
     * 阈值整数数值处理
     *
     * @param inputStr
     * @param hintStr
     * @return
     */
    private String getIntThresholdValue(String inputStr, String hintStr) {
        if (TextUtils.isEmpty(inputStr)) {
            return formatDataStr(hintStr, 3);
        } else {
            return formatDataStr(inputStr, 3);
        }
    }

    private String getFloatThresholdValue(String inputStr, String hintStr) {
        if (TextUtils.isEmpty(inputStr)) {
            return hintStr;
        } else {
            if ((Float.parseFloat(inputStr) + "").length() > 4) {
                Toast.makeText(this, "输入的范围过大", Toast.LENGTH_SHORT).show();
                return "";
            } else {
                return formatDataStr((Float.parseFloat(inputStr) + ""), 4);
            }
        }
    }

    /**
     * 不足有效数据位需要补零
     *
     * @param dataStr 输入的数据
     * @param digit   该数据的有效数据位
     * @return
     */
    private String formatDataStr(String dataStr, int digit) {
        if (dataStr.length() < digit) {
            int diff = digit - dataStr.length();
            StringBuilder newDataStr = new StringBuilder();
            for (int i = 0; i < diff; i++) {
                newDataStr.append("0");
            }
            newDataStr.append(dataStr);
            return newDataStr.toString();
        } else {
            return dataStr;
        }
    }

    /**
     * 判断输入的是否是合法的mac地址
     *
     * @param inputMacStr
     * @return
     */
    private boolean isValidMacAddress(String inputMacStr) {
        String regex = "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$";
        return inputMacStr.matches(regex);
    }

    public static final int REQUEST_PERMISSION_CODE = 1500;

    /**
     * 是否有定位权限
     *
     * @return boolean
     */
    private boolean hasLocationPermission() {
        return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 蓝牙是否打开
     *
     * @return boolean
     */
    private boolean hasBluetooth() {
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }

    /**
     * 定位服务是否打开
     *
     * @return boolean
     */
    private boolean hasLocationService() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return false;
        }
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }

    /**
     * 申请定位权限
     */
    private void requestLocationPermission(Activity activity) {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_CODE);
    }

    /**
     * 申请打开蓝牙
     */
    @SuppressLint("MissingPermission")
    private void requestBluetooth() {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, REQUEST_PERMISSION_CODE);
    }

    /**
     * 申请打开定位服务
     */
    private void requestLocationService() {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, REQUEST_PERMISSION_CODE);
    }
}
