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

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.config.CmdConfig;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.device.BleSendCmdUtil;
import com.pingwang.bluetoothlib.device.SendBleBean;
import com.pingwang.bluetoothlib.device.wifibleDevice.WifiBleDeviceData;
import com.pingwang.bluetoothlib.device.wifibleDevice.WifiBleInfoBean;
import com.pingwang.bluetoothlib.listener.CallbackDisIm;
import com.pingwang.bluetoothlib.listener.OnBleCompanyListener;
import com.pingwang.bluetoothlib.listener.OnBleVersionListener;
import com.pingwang.bluetoothlib.listener.OnCallbackDis;
import com.pingwang.bluetoothlib.listener.OnMcuParameterListener;
import com.pingwang.bluetoothlib.utils.BleDensityUtil;
import com.pingwang.bluetoothlib.utils.BleLog;
import com.pingwang.bluetoothlib.utils.BleStrUtils;

import java.util.ArrayList;
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.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.L;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;
import cn.net.aicare.modulelibrary.module.sphygmomanometer.SphyBleConfig;
import cn.net.aicare.modulelibrary.module.sphygmomanometer.SphyWifiBleDeviceData;


/**
 * wifi ble 血压计界面
 *
 * @author xing
 * @date 2023/10/07
 */
public class WifiBleSphyActivity extends BleBaseActivity implements OnCallbackDis, OnBleVersionListener, OnMcuParameterListener, OnBleCompanyListener, View.OnClickListener {

    private static String TAG = WifiBleSphyActivity.class.getName();
    private final int REFRESH_DATA = 3;
    private List<String> mList;
    private ArrayAdapter listAdapter;
    private TextView tv_wifi_ssid, tv_wifi_status;
    private EditText et_url, et_port, et_path;
    private Context mContext;
    private SphyWifiBleDeviceData mSphyWifiBleDeviceData;
    private WifiBleDeviceData mWifiBleDeviceData;
    private List<DialogStringImageBean> mWifiList = new ArrayList<>();
    private String mAddress;
    private BleSendCmdUtil mBleSendCmdUtil;
    private int mType;
    private int mCid;
    private byte unit = 0;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == REFRESH_DATA) {
                if (listAdapter != null)
                    listAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sphy_wifi_ble);
        mContext = this;
        mAddress = getIntent().getStringExtra("mac");
        mType = getIntent().getIntExtra("type", -1);
        mCid = getIntent().getIntExtra("cid", -1);
        mBleSendCmdUtil = BleSendCmdUtil.getInstance();
        init();
    }

    private void init() {
        mList = new ArrayList<>();
        ListView listView = findViewById(R.id.listview);
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        listView.setAdapter(listAdapter);

        Button clear = findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mList != null)
                    mList.clear();
                mHandler.sendEmptyMessage(REFRESH_DATA);
            }
        });

        tv_wifi_ssid = findViewById(R.id.tv_wifi_ssid);
        tv_wifi_status = findViewById(R.id.tv_wifi_status);
        et_url = findViewById(R.id.et_url);
        et_port = findViewById(R.id.et_port);
        et_path = findViewById(R.id.et_path);

        findViewById(R.id.btnVersion).setOnClickListener(this);
        findViewById(R.id.btnBattery).setOnClickListener(this);
        findViewById(R.id.btn_get_did).setOnClickListener(this);
        findViewById(R.id.btn_voice).setOnClickListener(this);
        findViewById(R.id.clear).setOnClickListener(this);
        findViewById(R.id.btn_wifi).setOnClickListener(this);
        findViewById(R.id.btn_config).setOnClickListener(this);
        findViewById(R.id.btn_read_config).setOnClickListener(this);
        findViewById(R.id.btn_read_wifi_status).setOnClickListener(this);

        cmdBtn();
    }


    private void cmdBtn() {
        Button btn_set_unit = findViewById(R.id.btn_set_unit);
        btn_set_unit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (unit == SphyBleConfig.SPHY_UNIT_MMHG) {
                    unit = SphyBleConfig.SPHY_UNIT_KPA;
                    mSphyWifiBleDeviceData.setUnit(unit);
                } else {
                    unit = SphyBleConfig.SPHY_UNIT_MMHG;
                    mSphyWifiBleDeviceData.setUnit(unit);
                }
            }
        });

        Button btn_start = findViewById(R.id.btn_start);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSphyWifiBleDeviceData.startMeasuring();
            }
        });

        Button btn_stop = findViewById(R.id.btn_stop);
        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSphyWifiBleDeviceData.stopMeasuring();
            }
        });
    }


    private int mVoiceStatus = 0;

    @Override
    public void onClick(View v) {
        SendBleBean sendBleBean = new SendBleBean();
        int id = v.getId();
        if (id == R.id.btnVersion) {
            sendBleBean.setHex(mBleSendCmdUtil.getBleVersion());
            mSphyWifiBleDeviceData.sendData(sendBleBean);
        } else if (id == R.id.btnBattery) {
            sendBleBean.setHex(mBleSendCmdUtil.getMcuBatteryStatus());
            mSphyWifiBleDeviceData.sendData(sendBleBean);
        } else if (id == R.id.btn_get_did) {
            sendBleBean.setHex(mBleSendCmdUtil.getDid());
            mSphyWifiBleDeviceData.sendData(sendBleBean);
        } else if (id == R.id.btn_voice) {
            if (mVoiceStatus == 0) {
                mVoiceStatus = 1;
            } else {
                mVoiceStatus = 0;

            }
            mSphyWifiBleDeviceData.setSphyVoice(mVoiceStatus);
        } else if (id == R.id.clear) {
            if (mList != null)
                mList.clear();
            mHandler.sendEmptyMessage(REFRESH_DATA);
        } else if (id == R.id.btn_config) {
            String ip = et_url.getText().toString().trim();
            String port = et_port.getText().toString().trim();
            String path = et_path.getText().toString().trim();
            if (ip.length() == 0 || port.length() == 0) {
                mList.add(TimeUtils.getTime() + "配置失败:ip或端口为空");
                mHandler.sendEmptyMessage(REFRESH_DATA);
                return;
            }
            setServiceInfo(ip, Integer.parseInt(port), path);
            mList.add(TimeUtils.getTime() + "配置服务器信息中...");
            mHandler.sendEmptyMessage(REFRESH_DATA);
        } else if (id == R.id.btn_read_config) {
            getWifiConnectInfo();
        } else if (id == R.id.btn_read_wifi_status) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getWifiCurrentState();
            }
        } else if (id == R.id.btn_wifi) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getWifiList();
                mList.add(TimeUtils.getTime() + "正在扫描附近可用的wifi...");
                mHandler.sendEmptyMessage(REFRESH_DATA);
            }
            showWifiList();
        }
    }


    /**
     * 获取wifi连接信息
     */
    public void getWifiConnectInfo() {
        if (mWifiBleDeviceData != null) {
            mWifiBleDeviceData.getIp();
            mWifiBleDeviceData.getPort();
            mWifiBleDeviceData.getPath();
            mWifiBleDeviceData.getDeviceSn();
        }
    }

    /**
     * 设置服务信息
     *
     * @param ip   知识产权
     * @param port 港口
     * @param path 路径
     */
    public void setServiceInfo(String ip, int port, String path) {
        if (mWifiBleDeviceData != null) {
            mWifiBleDeviceData.setServiceInfo(ip, port, path);
        }
    }

    private ShowListDialogFragment mShowListDialogFragment;

    private void showWifiList() {
        if (mShowListDialogFragment == null) {
            mShowListDialogFragment = ShowListDialogFragment.newInstance();
            mShowListDialogFragment.setList(mWifiList);
            mShowListDialogFragment.setTitle("选择WIFI");
            mShowListDialogFragment.setCancel("取消", 0);
            mShowListDialogFragment.setOnDialogListener(new ShowListDialogFragment.onDialogListener() {
                @Override
                public void onItemListener(int position) {
                    WifiBleInfoBean wifiBleInfoBean = mWifiBleInfoBeanList.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());
    }

    //-------------------BLE send---------------

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


    //---------------------------------服务---------------------------------------------------


    @Override
    public void onServiceSuccess() {
        CallbackDisIm.getInstance().addListListener(this);
        BleLog.i(TAG, "服务与界面建立连接成功");
        //与服务建立连接
        if (mAILinkBleManager != null) {
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                mSphyWifiBleDeviceData = SphyWifiBleDeviceData.getInstance(bleDevice);
                mWifiBleDeviceData = mSphyWifiBleDeviceData.getWifiBleDeviceData();
                mWifiBleDeviceData.setOnWiFiBleCallback(new WifiBleDeviceListener());
                mSphyWifiBleDeviceData.setType(mCid);
                mSphyWifiBleDeviceData.setOnNotifyData(new NotifyData());
                mSphyWifiBleDeviceData.setOnBleVersionListener(WifiBleSphyActivity.this);
                mSphyWifiBleDeviceData.setOnMcuParameterListener(WifiBleSphyActivity.this);
                mSphyWifiBleDeviceData.setOnCompanyListener(WifiBleSphyActivity.this);
            }
        }
    }

    @Override
    public void onServiceErr() {
        BleLog.i(TAG, "服务与界面连接断开");
        //与服务断开连接
        mAILinkBleManager = null;
    }


    @Override
    public void unbindServices() {
        CallbackDisIm.getInstance().removeListener(this);
        if (mSphyWifiBleDeviceData != null) {
            mSphyWifiBleDeviceData.disconnect();
            mSphyWifiBleDeviceData.clear();
            mSphyWifiBleDeviceData = null;
        }
    }


    //-----------------状态-------------------


    @Override
    public void onConnecting(@NonNull String mac) {
        //TODO 连接中
        if (mAddress.equals(mac)) {
            BleLog.i(TAG, "连接中");
        }
    }

    @Override
    public void onDisConnected(@NonNull String mac, int code) {
        //TODO 连接断开
        if (mAddress.equals(mac)) {
            BleLog.i(TAG, "连接断开");
            finish();
        }
    }

    @Override
    public void onServicesDiscovered(@NonNull String mac) {
        //TODO 连接成功(获取服务成功)
        if (mAddress.equals(mac))
            BleLog.i(TAG, "连接成功(获取服务成功)");
    }


    @Override
    public void bleOpen() {

    }

    @Override
    public void bleClose() {
        BleLog.i(TAG, "蓝牙未开启,可请求开启");
        finish();
    }


    //-----------------通知-------------------

    private class NotifyData implements SphyWifiBleDeviceData.onNotifyData {
        @Override
        public void onData(byte[] status, int type) {
            String data = "";
            if (status != null)
                data = BleStrUtils.byte2HexStr(status);
            if (type == 100) {
                mList.add(TimeUtils.getTime() + "send->" + data);
            } else {
                mList.add(TimeUtils.getTime() + "notify->" + data);
            }
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onSphyCmd(byte cmd) {
            String cmdStr = "";
            switch (cmd) {
                case SphyBleConfig.SHPY_CMD_START:
                    cmdStr += "开始测量";
                    break;
                case SphyBleConfig.SHPY_CMD_STOP:
                    cmdStr += "停止测试";
                    break;
                case SphyBleConfig.SHPY_CMD_MCU_START:
                    cmdStr += "mcu 开机";
                    break;
                case SphyBleConfig.SHPY_CMD_MCU_STOP:
                    cmdStr += "mcu 关机";
                    break;
            }
            mList.add(TimeUtils.getTime() + "指令:" + cmdStr);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onSphyVoice(byte cmd) {
            String cmdStr = "";
            switch (cmd) {
                case 0x00:
                    cmdStr += "打开语音";
                    break;
                case 0x01:
                    cmdStr += "关闭语音";
                    break;
            }
            mList.add(TimeUtils.getTime() + "指令:" + cmdStr);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onSphyDataNow(int dia, int sys, int decimal, int pul, int unit) {
            String diaStr = BleDensityUtil.getInstance().holdDecimals(dia, decimal);
            String sysStr = BleDensityUtil.getInstance().holdDecimals(sys, decimal);
            mList.add(TimeUtils.getTime() + "实时:舒张压=" + diaStr + "  收缩压=" + sysStr + "  心率=" + pul + "  单位=" + (unit == 0 ? "mmhg" : "kPa"));
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onSphyData(int dia, int sys, int decimal, int pul, int unit) {
            String diaStr = BleDensityUtil.getInstance().holdDecimals(dia, decimal);
            String sysStr = BleDensityUtil.getInstance().holdDecimals(sys, decimal);
            mList.add(TimeUtils.getTime() + "稳定:舒张压=" + diaStr + "  收缩压=" + sysStr + "  心率=" + pul + "  单位=" + (unit == 0 ? "mmhg" : "kPa"));
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onUnit(int unit) {
            String showData = "";
            switch (unit) {
                case CmdConfig.SETTING_SUCCESS:
                    showData = "设置单位成功";
                    break;
                case CmdConfig.SETTING_FAILURE:
                    showData = "设置单位失败";

                    break;
                case CmdConfig.SETTING_ERR:

                    showData = "设置单位错误";
                    break;
            }
            mList.add(TimeUtils.getTime() + showData);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onErr(byte status) {
            String errStr = "";
            switch ((int) status) {

                case 0:
                    errStr += "未找到高压";
                    break;
                case 1:
                    errStr += "无法正常加压，请检查是否插入袖带，或者重新插拔袖带气 管";
                    break;
                case 2:
                    errStr += "电量低";
                    break;
                case 3:
                    errStr += "传感器信号异常";
                    break;
                case 4:
                    errStr += "测量结果异常";
                    break;
                case 5:
                    errStr += "腕带过紧或气路堵塞";
                    break;
                case 60:
                    errStr += "测量中压力干扰严重";
                    break;
                case 7:
                    errStr += "压力超 290";
                    break;
                case 8:
                    errStr += "标定数据异常或存储 IC 异常";
                    break;

            }
            mList.add(TimeUtils.getTime() + "错误:" + errStr);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }
    }


    private List<WifiBleInfoBean> mWifiBleInfoBeanList;

    private class WifiBleDeviceListener implements WifiBleDeviceData.OnWiFiBleCallback {
        /**
         * 在ble和wifi状态
         *
         * @param bleStatus  ble状态
         * @param wifiStatus wifi状态
         * @param workStatus 工作状态
         */
        @Override
        public void onBleAndWifiStatus(int bleStatus, int wifiStatus, int workStatus) {

            String wifiStatusStr = "";
            switch (wifiStatus) {
                case 0:
                    wifiStatusStr = "未配置AP";
                    break;
                case 1:
                    wifiStatusStr = "连接AP失败";
                    break;
                case 2:
                    wifiStatusStr = "连接的AP信号不好";
                    break;
                case 3:
                    wifiStatusStr = "成功连接上AP";
                    break;
                case 4:
                    wifiStatusStr = "正在连接AP";
                    break;

            }
            mList.add("蓝牙状态：" + bleStatus + "\nwifi状态：" + wifiStatusStr + "\n工作状态：" + workStatus);
            mHandler.sendEmptyMessage(REFRESH_DATA);

            if (tv_wifi_status != null) {
                tv_wifi_status.setText(wifiStatusStr);
            }
        }

        @Override
        public void onWifiScanStatus(int status) {

        }

        @Override
        public void onConnectWifiName(String name) {
            if (tv_wifi_ssid != null) {
                tv_wifi_ssid.setText(name);
            }
        }

        @Override
        public void onWifiScanBean(WifiBleInfoBean wifiBleInfoBean) {
            L.i("扫描到的wifi信息:" + wifiBleInfoBean.toString());
        }

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

        /**
         * 设置wifi名字或密码的状态回调
         *
         * @param type   类型
         * @param status 状态
         */
        @Override
        public void onSetWifiNameOrPwdOrConnectCallback(int type, int status) {

        }

        @Override
        public void onWifiConnecting(int status) {
            L.i("wifi正在连接中:" + status);
            mList.add("wifi正在连接中...");
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        /**
         * 当前连接的wifi mac地址
         *
         * @param mac mac
         */
        @Override
        public void onConnectWifiMac(String mac) {

        }

        @Override
        public void onConnectWifiPwd(String pwd) {

        }

        @Override
        public void onDeviceSn(long sn) {
            //主要用于查询设备是否在服务器注册成功
            mList.add("设备SN号:" + sn);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onServerIp(String ip) {
            mList.add("设备ip地址:" + ip);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onServerPort(int port) {
            mList.add("设备端口:" + port);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onServerPath(String path) {
            mList.add("设备路径地址:" + path);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

        @Override
        public void onServerSettingInfo(boolean status) {
            mList.add("服务器配置:" + (status?"成功":"失败"));
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }
    }


    @Override
    public void onBmVersion(String version) {
        mList.add(TimeUtils.getTime() + "版本号:" + version);
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void OnDID(int cid, int vid, int pid) {
        String didStr = "cid:" + cid + "||vid:" + vid + "||pid:" + pid;
        mList.add(TimeUtils.getTime() + "ID:" + didStr);
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onMcuBatteryStatus(int status, int battery) {
        mList.add(TimeUtils.getTime() + "电量:" + battery + "%");
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void onSysTime(int status, int[] times) {
        String time = times[0] + "-" + times[1] + "-" + times[2] + "  " + times[3] + ":" + times[4] + ":" + times[5];
        mList.add(TimeUtils.getTime() + "系统时间:" + time);
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleLog.i(TAG, "onDestroy");
    }
}
