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

import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import androidx.appcompat.app.ActionBar;

import com.pingwang.bluetoothlib.AILinkBleManager;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;

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

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleAppNewBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.UnitUtils;
import cn.net.aicare.modulelibrary.module.gasDetectorPlus.GasDetectorPlusBleDevice;
import cn.net.aicare.modulelibrary.module.gasDetectorPlus.OnGasDetectorPlusInfoListener;
import cn.net.aicare.modulelibrary.module.gasDetectorPlus.bean.GasAlarmInfoBean;
import cn.net.aicare.modulelibrary.module.gasDetectorPlus.bean.GasDetectorPlusCurrentInfoBean;

/**
 * 气体检测仪界面(华普)
 *
 * @author xing
 * @date 2024/09/05
 */
public class GasDetectorPlusActivity extends BleAppNewBaseActivity implements View.OnClickListener, OnCallbackBle, OnGasDetectorPlusInfoListener {

    private String mMac = "";
    private EditText et1, et2;
    private GasDetectorPlusBleDevice mGasDetectorPlusBleDevice;
    private ListView list_view;
    private List<String> mList;
    private ArrayAdapter mListAdapter;
    private List<String> mGasList = new ArrayList<>(Arrays.asList(
            "O2", "CO2", "TVOC(PID)", "TVOC", "CO", "H2S", "NO", "NO2", "SO2", "H2", "O3", "NH3", "HCN", "HCI", "H2O2", "CH2O",
            "C2H4", "Cl2", "ClO2", "C2H4O", "PH3", "HF", "F2", "C4H8S", "ASH3", "SIH4", "CH3SH", "CH4O", "C2H6O", "C4H", "C3H8O", "COF2",
            "BF3", "CH4", "C3H6O", "C2H2", "C6H6", "C6H14", "C3H8", "温度", "湿度"
    ));

    @Override
    protected void uiHandlerMessage(Message msg) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_gas_detector_plus;
    }

    @Override
    protected void initListener() {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setTitle("气体检测仪(BLE+WIFI)");
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btnClearLog) {//清除日志
            mList.clear();
            addText("清除日志");
        } else if (id == R.id.btnPauseLog) {//暂停日志
            isPause = !isPause;
            addText("暂停日志:" + isPause);
        } else if (id == R.id.btnGetSupportGas) {//支持的气体类型(0x01)
            mGasDetectorPlusBleDevice.getSupportedGas();
            addText("获取支持的气体类型(0x01)");
        } else if (id == R.id.btnGetSupportFun) {//获取支持的功能列表
            mGasDetectorPlusBleDevice.getSupportedFun();
            addText("获取支持的功能列表(0x02)");
        } else if (id == R.id.btnGetAlarmSwitch) {//警报推送开关(0x03)
            mGasDetectorPlusBleDevice.getAlarmSwitch();
            addText("获取警报推送开关(0x03)");
        } else if (id == R.id.btnSetAlarmSwitch) {//警报推送开关(0x03)
            alarmSwitch = alarmSwitch == 1 ? 0 : 1;
            mGasDetectorPlusBleDevice.setAlarmSwitch(alarmSwitch);
            addText("设置警报推送开关(0x03):" + alarmSwitch);
        } else if (id == R.id.btnGetAlarmTime) {//报警时长设置(0x04)
            mGasDetectorPlusBleDevice.getAlarmTime();
            addText("获取报警时长设置(0x04)");
        } else if (id == R.id.btnGetAlarmFrequency) {//报警频率(0x0A)
            mGasDetectorPlusBleDevice.getAlarmFrequency();
            addText("获取报警频率(0x0A)");
        } else if (id == R.id.btnGetGasInfo) {//气体信息(0x09)
            mGasDetectorPlusBleDevice.getGasInfo();
            addText("获取气体信息(0x09)");
        } else if (id == R.id.btnSaveFrequency) {//离线数据存储频率(0x07)
            int frequency = 0;
            try {
                frequency = Integer.parseInt(et1.getText().toString().trim());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            mGasDetectorPlusBleDevice.setHistorySaveFrequency(frequency);
            addText("设置离线数据存储频率(0x07):" + frequency);
        } else if (id == R.id.btnReportInterval) {//数据上报间隔(0x08)
            int interval = 0;
            try {
                interval = Integer.parseInt(et1.getText().toString().trim());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            mGasDetectorPlusBleDevice.setDataReportInterval(interval);
            addText("设置数据上报间隔(0x08):" + interval);
        } else if (id == R.id.btnGetAlarmRing) {
            int ring = 0;
            try {
                ring = Integer.parseInt(et2.getText().toString().trim());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            mGasDetectorPlusBleDevice.setAlarmRing(ring);
            addText("报警铃声设置(0x05):" + ring);
        } else if (id == R.id.btnAlarmRingTest) {
            int ringTest = 0;
            try {
                ringTest = Integer.parseInt(et2.getText().toString().trim());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            mGasDetectorPlusBleDevice.setAlarmRingTest(ringTest);
            addText("报警铃声试听(0x06):" + ringTest);
        } else if (id == R.id.btnGetPowerInfo) {//请求获取设备电量信息(0x0C)
            mGasDetectorPlusBleDevice.getPowerInfo();
            addText("请求获取设备电量信息(0x0C)");
        } else if (id == R.id.btnSetTime) {
            long second = System.currentTimeMillis() / 1000;
            mGasDetectorPlusBleDevice.setSyncTime(second);
            addText("下发同步时间(0x0E)：\n" + second + "秒");
        }
    }

    @Override
    protected void initData() {
        mMac = getIntent().getStringExtra("mac");
        mList = new ArrayList<>();
        mListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        list_view.setAdapter(mListAdapter);
        addText("连接成功:" + mMac);
        onServiceSuccess();
    }

    @Override
    protected void initView() {
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        list_view = findViewById(R.id.list_view);
    }

    @Override
    public void onServiceSuccess() {
        if (TextUtils.isEmpty(mMac)) {
            return;
        }
        if (mGasDetectorPlusBleDevice != null) {
            return;
        }
        AILinkBleManager.getInstance().setOnCallbackBle(this);
        BleDevice bleDevice = AILinkBleManager.getInstance().getBleDevice(mMac);
        mGasDetectorPlusBleDevice = GasDetectorPlusBleDevice.init(bleDevice);
        mGasDetectorPlusBleDevice.addOnGasDetectorInfoListener(this);
        mGasDetectorPlusBleDevice.setOnShowData(new GasDetectorPlusBleDevice.OnShowData() {
            @Override
            public void showData(String data) {
                addText("收到的vlaue数据:" + data);
            }
        });
    }

    @Override
    public void onServiceErr() {

    }

    @Override
    public void unbindServices() {

    }


    @Override
    public void onDisConnected(String mac, int code) {
        if (mac.equals(this.mMac)) {
            if (mGasDetectorPlusBleDevice != null) {
                mGasDetectorPlusBleDevice.removeOnGasDetectorInfoListener(this);
                mGasDetectorPlusBleDevice = null;
            }
            addText("断开连接:" + mac + "  code:" + code);
        }
    }


    @Override
    public void onSupportedGas(Map<Integer, Boolean> map) {
        StringBuilder showData = new StringBuilder();
        for (Integer key : map.keySet()) {
            if (map.get(key)) {
                if (key >= mGasList.size()) {
                    break;
                }
                String name = mGasList.get(key);
                showData.append(name).append("\n");
            }
        }
        addText("支持的气体类型(0x01)：\n" + showData);
    }

    @Override
    public void onSupportedFun(Map<Integer, Boolean> map) {
        StringBuilder data = new StringBuilder();

        for (Integer key : map.keySet()) {
            String str = map.get(key) ? "支持" : "不支持";
            switch (key) {
                case 0:
                    data.append("报警推送:").append(str).append("\n");
                    break;
                case 1:
                    data.append("报警时长:").append(str).append("\n");
                    break;
                case 2:
                    data.append("报警铃声:").append(str).append("\n");
                    break;
                case 3:
                    data.append("报警推送频率:").append(str).append("\n");
                    break;
            }
        }


        addText("支持的功能列表(0x02)：" + data);
    }

    int alarmSwitch = 0;

    @Override
    public void onAlarmSwitch(int switchStatus) {
        alarmSwitch = switchStatus;
        addText("警报推送开关(0x03)：" + (switchStatus == 1 ? "打开" : "关闭"));
    }

    @Override
    public void onAlarmTime(int current, int[] supportTimes) {
        String min;
        switch (current) {
            case 0:
                min = "一直报警";
                break;
            case 1:
                min = "15S报警";
                break;
            case 2:
                min = "30S报警";
                break;
            case 3:
                min = "45S报警";
                break;
            case 4:
                min = "1分钟报警";
                break;
            case 5:
                min = "2分钟报警";
                break;
            case 6:
                min = "3分钟报警";
                break;
            default:
                min = "未知";
                break;
        }

        addText("报警时长设置(0x04)：选中" + current + "项," + min + "分钟" + " 支持的时长选项:" + Arrays.toString(supportTimes));
    }

    @Override
    public void onAlarmRing(int current, int[] supportedRing) {
        String str;
        switch (current) {

            case 1:
                str = "铃声1";
                break;
            case 2:
                str = "铃声2";
                break;
            case 3:
                str = "铃声3";
                break;
            case 4:
                str = "铃声4";
                break;
            case 5:
                str = "铃声5";
                break;
            case 6:
                str = "铃声6";
                break;
            default:
                str = "未知";
                break;
        }
        addText("报警铃声设置(0x05)：选中" + current + "项," + str + " 支持的时长:" + Arrays.toString(supportedRing));
    }

    @Override
    public void onAlarmRingTest(int position) {
        addText("报警铃声试听(0x06)：选中" + position + "项");
    }

    @Override
    public void onHistorySaveFrequency(int frequency) {
        addText("离线数据存储频率(0x07)：频率" + frequency + "分钟");
    }

    @Override
    public void onDataReportInterval(int interval) {
        addText("数据上报间隔(0x08)：间隔" + interval + "分钟");
    }

    @Override
    public void onAlarmFrequency(int frequency) {
        addText("报警频率(0x0A)：频率" + frequency + "秒");
    }

    @Override
    public void onAlarmGasInfo(List<GasAlarmInfoBean> list) {
        StringBuilder showData = new StringBuilder();
        for (GasAlarmInfoBean gasAlarmInfoBean : list) {
            showData.append(mGasList.get(gasAlarmInfoBean.getType())).append(" ").append(gasAlarmInfoBean.getStatus() == 1 ? "报警" : "正常").append("\n");
        }
        addText("报警的气体信息(0x0B)：\n" + showData);
    }

    @Override
    public void onPowerInfo(int status, int power) {
        addText("设备电量信息(0x0C)：\n" + power + "%");
    }

    @Override
    public void onUnitInfo(int type, int unit) {
        String unitStr = "ppm";
        switch (unit) {
            case 0:
                unitStr = "ppm";
                break;
            case 1:
                unitStr = "%";
                break;
            case 2:
                unitStr = "mg/m³";
                break;
            case 3:
                unitStr = "℃";
                break;
            case 4:
                unitStr = "℉";
                break;
        }
        addText("单位设置(0x0D)：\n类型:" + mGasList.get(type) + " 单位:" + unitStr);
    }

    @Override
    public void onSyncTime() {
        long second = System.currentTimeMillis() / 1000;
        mGasDetectorPlusBleDevice.setSyncTime(second);
        addText("同步时间(0x0E)：\n" + second + "秒");
    }

    @Override
    public void onGasInfo(GasDetectorPlusCurrentInfoBean bean) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        String time = simpleDateFormat.format(bean.getTimeSeconds() * 1000);
        StringBuilder showData = new StringBuilder(time + "：\n");
        for (GasDetectorPlusCurrentInfoBean.GasInfo gasInfo : bean.getGasInfoList()) {
            String unitStr = "ppm";
            switch (gasInfo.getUnit()) {
                case 0:
                    unitStr = "ppm";
                    break;
                case 1:
                    unitStr = "%";
                    break;
                case 2:
                    unitStr = "mg/m³";
                    break;
                case 3:
                    unitStr = "℃";
                    break;
                case 4:
                    unitStr = "℉";
                    break;
            }
            String valueStr = UnitUtils.getHoldDecimal(gasInfo.getDecimal(), gasInfo.getValue());
            showData.append(mGasList.get(gasInfo.getType())).append(" ").append(valueStr).append(unitStr).append("\n");
        }

        addText("气体信息(0x09)：\n" + showData);
    }

    private SimpleDateFormat sdf;
    private String mOldText = "";
    private boolean isPause = false;

    private void addText(String text) {
        if (isPause && !mList.isEmpty()) {
            return;
        }
        if (mOldText.equals(text)) {
            return;
        }
        if (sdf == null) {
            sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
        }
        mList.add(0, sdf.format(System.currentTimeMillis()) + "：\n" + text);
        mListAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AILinkBleManager.getInstance().removeOnCallbackBle(this);
        if (mGasDetectorPlusBleDevice != null) {
            mGasDetectorPlusBleDevice.clear();
        }
    }
}
