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

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

import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.bean.BleValueBean;
import com.pingwang.bluetoothlib.config.BleConfig;
import com.pingwang.bluetoothlib.listener.OnBleBroadcastDataListener;
import com.pingwang.bluetoothlib.listener.OnCallbackDis;
import com.pingwang.bluetoothlib.utils.BleDensityUtil;
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.utils.TimeUtils;
import cn.net.aicare.modulelibrary.module.BloodOxygen.BroadcastBloodOxygenBleConfig;


/**
 * xing<br>
 * 2020/09/09<br>
 * 广播血氧仪
 */
public class BroadcastBloodOxygenActivity extends BleBaseActivity implements OnCallbackDis, OnBleBroadcastDataListener, View.OnClickListener {

    private static String TAG = BroadcastBloodOxygenActivity.class.getName();
    private final int REFRESH_DATA = 3;

    private TextView tv_broadcast_blood_oxygen, tv_broadcast_mac;

    private List<String> mList;
    private ArrayAdapter listAdapter;
    private Context mContext;
    private String mAddress = "";

    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_broadcast_blood_oxygen);
        mContext = this;
        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);

        findViewById(R.id.clear).setOnClickListener(this);
        findViewById(R.id.open).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);

        tv_broadcast_blood_oxygen = findViewById(R.id.tv_broadcast_blood_oxygen);

        tv_broadcast_mac = findViewById(R.id.tv_broadcast_mac);

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.clear) {
            if (mList != null)
                mList.clear();
            mHandler.sendEmptyMessage(REFRESH_DATA);
        } else if (id == R.id.open) {
            if (mAILinkBleManager != null) {
                mAILinkBleManager.startScan(0, BleConfig.UUID_SERVER_BROADCAST_AILINK);
            }
        } else if (id == R.id.stop) {
            if (mAILinkBleManager != null) {
                mAILinkBleManager.stopScan();
            }
        }
    }


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


    @Override
    public void onServiceSuccess() {
        BleLog.i(TAG, "服务与界面建立连接成功");
        //与服务建立连接
        if (mAILinkBleManager != null) {
            mAILinkBleManager.addOnBleBroadcastDataListener(this);
            mAILinkBleManager.startScan(0, BleConfig.UUID_SERVER_BROADCAST_AILINK);
        }
    }

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

    @Override
    public void unbindServices() {


    }

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


    @Override
    public void bleOpen() {
        mList.add(TimeUtils.getTime() + "蓝牙打开");
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    public void bleClose() {
        BleLog.i(TAG, "蓝牙未开启,可请求开启");
        mList.add(TimeUtils.getTime() + "蓝牙关闭");
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

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


    public void getBloodOxygenData(int status, int bloodOxygen, int pulseRate, int plethysmogram, int power) {
        String statusStr = "状态=";

        switch (status) {
            case BroadcastBloodOxygenBleConfig.START_TESTING:
                statusStr += "开始测试";
                break;
            case BroadcastBloodOxygenBleConfig.TESTING:
                statusStr += "正在测试";
                break;

            case BroadcastBloodOxygenBleConfig.STOP_TESTING:
                statusStr += "测试完成";
                break;

        }

        String bloodOxygenStr = "--%";
        if (bloodOxygen != 0xFF) {
            bloodOxygenStr = bloodOxygen + "%";
        }
        String pulseRateStr = "--%";
        if (pulseRate != 0xFF) {
            pulseRateStr = pulseRate + "%";
        }
        String plethysmogramStr = BleDensityUtil.getInstance().holdDecimals(plethysmogram, 1);
        String showData = TimeUtils.getTime();
        showData += statusStr;
        showData += "\n血氧=" + bloodOxygenStr + ";脉率=" + pulseRateStr + ";PI=" + plethysmogramStr + ";电量=" + power + "%";

        tv_broadcast_blood_oxygen.setText(bloodOxygenStr);

        mList.add(showData);
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

    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
    protected void onDestroy() {
        super.onDestroy();
        BleLog.i(TAG, "onDestroy");
    }


    @Override
    public void onBleBroadcastData(BleValueBean bleValueBean, byte[] payload) {
        if (bleValueBean.isBroadcastModule() && bleValueBean.getCid() == BroadcastBloodOxygenBleConfig.BROADCAST_BLOOD_OXYGEN) {
            if (TextUtils.isEmpty(mAddress) && bleValueBean.isBroadcastModule()) {
                mAddress = bleValueBean.getMac();
                if (tv_broadcast_mac != null) {
                    tv_broadcast_mac.setText(mAddress);
                }
            }
            //地址相同,并且是广播秤
            if (mAddress.equalsIgnoreCase(bleValueBean.getMac()) && bleValueBean.isBroadcastModule()) {
                byte[] manufacturerData = bleValueBean.getManufacturerData();
                int cid = bleValueBean.getCid();
                int vid = bleValueBean.getVid();
                int pid = bleValueBean.getPid();
                OnDID(cid, vid, pid);
                dataCheck(payload);
            }
        }

    }

    private int mOldNumberId = -1;

    /**
     * 校验解析数据
     *
     * @param data Payload数据
     */
    public void dataCheck(byte[] data) {
        if (data == null)
            return;
        if (data.length >= 9) {
            int numberId = data[0] & 0xff;//数据ID
            if (mOldNumberId == numberId) {
                //数据相同,已处理过了.不再处理
                return;
            }
            mOldNumberId = numberId;
            //0x00 ：开始测试
            //0x01 ：正在测试
            //0xFF ：测试结束
            int status = data[1] & 0xff;

            //0-100 %
            // 若该值无效，则为 0xFF
            int bloodOxygen = data[2] & 0xff;//血氧浓度百分比（SpO2 ，单位 %）

            //0-254
            //若该值无效，则为 0xFF
            int pulseRate = data[3] & 0xff;//脉率（pulse rate ，单位 bpm）

            //
            int plethysmogram = data[4] & 0xff;//PI （ Plethysmogram 无单位 ，1 位小数 ）

            int power = data[5] & 0xff;//电量（power ，单位%）
            getBloodOxygenData(status, bloodOxygen, pulseRate, plethysmogram, power);

        }

    }


}
