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

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.ListView;
import android.widget.TextView;

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

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.OnBleDeviceDataListener;
import com.pingwang.bluetoothlib.listener.OnBleVersionListener;
import com.pingwang.bluetoothlib.listener.OnCallbackDis;
import com.pingwang.bluetoothlib.listener.OnMcuParameterListener;
import com.pingwang.bluetoothlib.utils.BleLog;

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.SP;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;


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

    private static String TAG = PublicWifiBleOtaActivity.class.getName();

    private final String WIFI_BLE_SSID = "WIFI_BLE_SSID_KEY";
    private final String WIFI_BLE_SSID_MAC = "WIFI_BLE_SSID_MAC";
    private final String WIFI_BLE_PWD = "WIFI_BLE_PWD";

    private final int REFRESH_DATA = 3;
    private List<String> mList;
    private ArrayAdapter listAdapter;
    private TextView tv_wifi_ssid, tv_wifi_status, tv_wifi_info;
    private Context mContext;
    private WifiBleDeviceData mWifiBleDeviceData;
    private List<DialogStringImageBean> mWifiList = new ArrayList<>();
    private String mAddress;
    private int mType;
    private int mCid;
    private byte unit = 0;

    private String mSsid = "";
    private String mMac = "";
    private String mPwd = "";

    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_wifi_ble_ota);
        mContext = this;
        mAddress = getIntent().getStringExtra("mac");
        mType = getIntent().getIntExtra("type", -1);
        mCid = getIntent().getIntExtra("cid", -1);
        mSsid = (String) SP.getInstance().get(WIFI_BLE_SSID, "");
        mMac = (String) SP.getInstance().get(WIFI_BLE_SSID_MAC, "");
        mPwd = (String) SP.getInstance().get(WIFI_BLE_PWD, "");
        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_info = findViewById(R.id.tv_wifi_info);
        tv_wifi_status = findViewById(R.id.tv_wifi_status);

        findViewById(R.id.clear).setOnClickListener(this);
        findViewById(R.id.btn_wifi).setOnClickListener(this);
        findViewById(R.id.btn_read_wifi_status).setOnClickListener(this);
        findViewById(R.id.btn_start_ota).setOnClickListener(this);


        if (tv_wifi_info != null) {
            tv_wifi_info.setText(mSsid + "\n" + mPwd);
        }

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.clear) {
            if (mList != null)
                mList.clear();
            mHandler.sendEmptyMessage(REFRESH_DATA);
            SP.getInstance().put(WIFI_BLE_SSID, "");
            SP.getInstance().put(WIFI_BLE_SSID_MAC, "");
            SP.getInstance().put(WIFI_BLE_PWD, "");
            mSsid = "";
            mMac = "";
            mPwd = "";
            if (tv_wifi_info != null) {
                tv_wifi_info.setText("");
            }
        } else if (id == R.id.btn_read_wifi_status) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getWifiCurrentState();
            }
        } else if (id == R.id.btn_start_ota) {
            if (mWifiBleDeviceData != null) {
                setConnectWifi(mMac, mPwd);
            }
        } else if (id == R.id.btn_wifi) {
            if (mWifiBleDeviceData != null) {
                mWifiBleDeviceData.getWifiList();
                mList.add(TimeUtils.getTime() + "正在扫描附近可用的wifi...");
                mHandler.sendEmptyMessage(REFRESH_DATA);
            }
            showWifiList();
        }
    }


    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);
                    mSsid = wifiBleInfoBean.getSsid();
                    MoveDataDialogFragment.newInstance()
                                          .setTitle(mSsid, "")
                                          .setContent("", "请输入密码", MoveDataDialogFragment.NAME)
                                          .setOk("OK", 0)
                                          .setCancel("取消", 0)
                                          .setOnDialogListener(new MoveDataDialogFragment.OnDialogListener() {
                                              @Override
                                              public void onSucceedListener(View v, String data) {
                                                  mMac = wifiBleInfoBean.getMac();
                                                  mPwd = data.trim();
                                                  SP.getInstance().put(WIFI_BLE_SSID, mSsid);
                                                  SP.getInstance().put(WIFI_BLE_SSID_MAC, mMac);
                                                  SP.getInstance().put(WIFI_BLE_PWD, mPwd);
                                                  setConnectWifi(mMac, mPwd);

                                              }
                                          })
                                          .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);
        }
        if (tv_wifi_info != null) {
            tv_wifi_info.setText(mSsid + "\n" + mPwd);
        }
    }


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


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

                bleDevice.setOnBleDeviceDataListener(new OnBleDeviceDataListener() {
                    @Override
                    public void onNotifyDataA6(String uuid, byte[] hex) {
                        int cmd = hex[0] & 0xff;
                        if (cmd == 0x91) {
                            int status = hex[1] & 0xff;
                            if (status == 0) {
                                mList.add(TimeUtils.getTime() + "WIFI OTA成功");
                            } else if (status == 1) {
                                mList.add(TimeUtils.getTime() + "WIFI OTA失败");
                            } else if (status == 2) {
                                mList.add(TimeUtils.getTime() + "不支持WIFI OTA");
                            } else {
                                mList.add(TimeUtils.getTime() + "模块主动开始 WIFI OTA");
                            }
                            mHandler.sendEmptyMessage(REFRESH_DATA);
                        }
                    }
                });
                bleDevice.setOnBleVersionListener(this);
                //获取版本号
                bleDevice.sendData(new SendBleBean(BleSendCmdUtil.getInstance().getBleVersion()));
                mWifiBleDeviceData.getWifiCurrentState();
                mList.add(TimeUtils.getTime() + "获取版本号指令");
                mHandler.sendEmptyMessage(REFRESH_DATA);
            }
        }
    }

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


    @Override
    public void unbindServices() {
        CallbackDisIm.getInstance().removeListener(this);
        mAILinkBleManager.disconnect(mAddress);
    }


    private void startOta() {
        mList.add(TimeUtils.getTime() + "发送开始OTA指令");
        mHandler.sendEmptyMessage(REFRESH_DATA);
        SendBleBean sendBleBean = new SendBleBean();
        sendBleBean.setHex(new byte[]{(byte) 0x91, 0x01});
        mWifiBleDeviceData.getBleDevice().sendData(sendBleBean);
    }


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


    @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 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(TimeUtils.getTime() + "蓝牙状态：" + bleStatus + "\nwifi状态：" + wifiStatusStr + "\n工作状态：" + workStatus);
            mHandler.sendEmptyMessage(REFRESH_DATA);

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

        }

        @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(TimeUtils.getTime() + "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(TimeUtils.getTime() + "设备SN号:" + sn);
            mHandler.sendEmptyMessage(REFRESH_DATA);
        }

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

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

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

        @Override
        public void onServerSettingInfo(boolean status) {
            mList.add(TimeUtils.getTime() + "服务器配置:" + (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");
    }
}
