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


import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;

import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.bean.BleValueBean;
import com.pingwang.bluetoothlib.config.CmdConfig;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;

import java.lang.ref.WeakReference;
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.AddUserDialog;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.bean.UserBean;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.TimeUtils;
import cn.net.aicare.modulelibrary.module.BodyFatScale.HmiAppHistoryRecordBean;
import cn.net.aicare.modulelibrary.module.BodyFatScale.HmiBodyFatBleUtilsData;
import cn.net.aicare.modulelibrary.module.BodyFatScale.HmiBodyFatDataUtil;
import cn.net.aicare.modulelibrary.module.BodyFatScale.HmiBodyFatRecordBean;
import cn.net.aicare.modulelibrary.module.BodyFatScale.HmiBodyFatUserBean;
import cn.net.aicare.modulelibrary.module.BodyFatScale.HmiMcuHistoryRecordBean;

/**
 * HMI蓝牙体脂秤
 */
public class HmiBodyFatScaleBleActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, HmiBodyFatBleUtilsData.BleBodyFatCallback {
    private String TAG = HmiBodyFatScaleBleActivity.class.getName();
    private String mAddress;
    private List<String> mlogList;
    private List<String> mUserlogList;
    private ArrayAdapter listAdapter;
    private ArrayAdapter userAdapter;
    private HmiBodyFatBleUtilsData bodyFatBleUtilsData;
    private MHandler mMHandler;
    private EditText mEditText;
    private RadioButton kg, jing, stlb, lb;
    private List<HmiBodyFatUserBean> mUsers;
    private HmiBodyFatUserBean selectUser;
    private int weighunit = HmiBodyFatDataUtil.KG;
    private ListView loglistView;
    private ListView userlistView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横屏
        setContentView(R.layout.activity_hmi_body_fat_scale_ble);
        initView();
        setUnitInit();
        initdata();


    }

    private void initView() {
        findViewById(R.id.history).setOnClickListener(this);
        findViewById(R.id.userlist).setOnClickListener(this);
        findViewById(R.id.btnUser).setOnClickListener(this);
        findViewById(R.id.adduser).setOnClickListener(this);
        findViewById(R.id.syntime).setOnClickListener(this);
        kg = findViewById(R.id.kg);
        jing = findViewById(R.id.jin);
        stlb = findViewById(R.id.st_lb);
        lb = findViewById(R.id.lb);
        mEditText = findViewById(R.id.edit_Userid);
        kg.setChecked(true);
        loglistView = findViewById(R.id.log_list);
        userlistView = findViewById(R.id.user_list);


    }

    private void initdata() {
        mAddress = getIntent().getStringExtra("mac");

        WeakReference weakReference = new WeakReference(new MHandler());
        mMHandler = (MHandler) weakReference.get();

        mlogList = new ArrayList<>();
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mlogList);
        loglistView.setAdapter(listAdapter);

        HmiBodyFatUserBean defaultUser = getdefault();
        selectUser = defaultUser;

        mUsers = new ArrayList<>();
        mUsers.add(defaultUser);

        mUserlogList = new ArrayList<>();
        mUserlogList.add(defaultUser.toString());

        userAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mUserlogList);
        userlistView.setAdapter(userAdapter);
    }

    private HmiBodyFatUserBean getdefault() {
        HmiBodyFatUserBean user = new HmiBodyFatUserBean();
        user.setModeType(HmiBodyFatDataUtil.MODE_ORDINARY);
        user.setSex(HmiBodyFatDataUtil.SEX_MAN);
        user.setAge(18);
        user.setHeight(170);
        user.setAdc(560);
        user.setWeight(50);
        user.setId(1);
        return user;
    }

    private void setUnitInit() {
        kg.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                weighunit = HmiBodyFatDataUtil.KG;
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.setWeightUnit(weighunit);
                }
            }
        });
        jing.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                weighunit = HmiBodyFatDataUtil.JIN;
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.setWeightUnit(weighunit);
                }
            }
        });
        stlb.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                weighunit = HmiBodyFatDataUtil.ST;
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.setWeightUnit(weighunit);
                }
            }
        });
        lb.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                weighunit = HmiBodyFatDataUtil.LB;
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.setWeightUnit(weighunit);
                }
            }
        });
    }

    @Override
    public void onServiceSuccess() {
        mlogList.add(0, "服务与界面建立连接成功");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
//        BleLog.i(TAG, "服务与界面建立连接成功");
        //与服务建立连接
        if (mAILinkBleManager != null) {
            mAILinkBleManager.setOnCallbackBle(this);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                HmiBodyFatBleUtilsData.init(bleDevice, this);
                bodyFatBleUtilsData = HmiBodyFatBleUtilsData.getInstance();
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.setWeightUnit(weighunit);
                    bodyFatBleUtilsData.synSysTime();
                }


            }
        }
    }


    @Override
    public void onServiceErr() {
        mlogList.add(0, "服务与界面建立连接出错");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void unbindServices() {
        mlogList.add(0, "服务与界面建立断开连接成功");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        if (mAILinkBleManager != null) {
            mAILinkBleManager.removeOnCallbackBle(this);
        }
    }

    @Override
    public void onStartScan() {
        mlogList.add(0, "开始扫描");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onScanning(BleValueBean data) {
        mlogList.add(0, "扫描中");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onScanTimeOut() {
        mlogList.add(0, "扫描超时");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    @Override
    public void onConnecting(String mac) {
        mlogList.add(0, "正在连接" + mac);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onDisConnected(String mac, int code) {
        mlogList.add(0, "断开连接" + mac);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onServicesDiscovered(String mac) {
        mlogList.add(0, "发现蓝牙服务" + mac);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void bleOpen() {
        mlogList.add(0, "蓝牙打开");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void bleClose() {
        mlogList.add(0, "蓝牙关闭");
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    private String mOldData = "";

    @Override
    public void onWeightData(int status, float weight, int weightUnit, int decimals) {
        String data = "体重数据类型：" + (status == HmiBodyFatDataUtil.WEIGHT_TESTING ? "实时" : "稳定") + "\n体重: " + weight + " 单位：" + weightUnit + " 小数点位: " + decimals;
        if (mOldData.equals(data)) {
            return;
        }

        if (status == HmiBodyFatDataUtil.WEIGHT_RESULT) {
            //稳定体重
            selectUser.setWeight(weight);
            mMHandler.sendEmptyMessage(TO_REFRESH_USER);
        }

        mOldData = data;
        mlogList.add(0, data);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    private int mOldStatus = -1;

    @Override
    public void onStatus(int status) {
        if (mOldStatus == status) {
            return;
        }
        mOldStatus = status;

        switch (status) {
            case HmiBodyFatDataUtil.WEIGHT_TESTING:
                mlogList.add(0, "测量状态：" + status + " 测量实时体重");
                break;
            case HmiBodyFatDataUtil.WEIGHT_RESULT:
                mlogList.add(0, "测量状态：" + status + " 稳定体重");
                break;
            case HmiBodyFatDataUtil.IMPEDANCE_TESTING:
                mlogList.add(0, "测量状态：" + status + " 阻抗测量中");
                break;
            case HmiBodyFatDataUtil.IMPEDANCE_SUCCESS:
            case HmiBodyFatDataUtil.IMPEDANCE_SUCCESS_DATA:
                mlogList.add(0, "测量状态：" + status + " 阻抗测量成功");
                break;
            case HmiBodyFatDataUtil.IMPEDANCE_FAIL:
                mlogList.add(0, "测量状态：" + status + " 阻抗测量失败");
                break;
            case HmiBodyFatDataUtil.HEART_TESTING:
                mlogList.add(0, "测量状态：" + status + " 心率测量中");
                break;
            case HmiBodyFatDataUtil.HEART_SUCCESS:
                mlogList.add(0, "测量状态：" + status + " 心率测量成功");
                break;
            case HmiBodyFatDataUtil.HEART_FAIL:
                mlogList.add(0, "测量状态：" + status + " 心率测量失败");
                break;
            case HmiBodyFatDataUtil.TEST_FINISH:
                mlogList.add(0, "测量状态：" + status + " 测量完成");
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.updateUserInfo(selectUser);
                }
                break;
            case HmiBodyFatDataUtil.MUC_REQUEST_USER_INFO:
                mlogList.add(0, "测量状态：" + status + "请求用户信息");
                if (bodyFatBleUtilsData != null) {
                    bodyFatBleUtilsData.setUserInfo(selectUser);
                }
                break;
            default:
                mlogList.add(0, "测量状态：" + status);

        }
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onAdc(int adc, int algorithmic) {
        mlogList.add(0, "阻抗：" + adc + " 算法位：" + algorithmic);
        selectUser.setAdc(adc);
        mMHandler.sendEmptyMessage(TO_REFRESH_USER);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onHeartRate(int heartrate) {
        mlogList.add(0, "心率：" + heartrate);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onBodyFat(HmiBodyFatRecordBean bodyFatRecord) {
        mlogList.add(0, "体脂数：" + bodyFatRecord.toString());
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    @Override
    public void onError(int code) {
        mlogList.add(0, "错误码：" + code);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onHistoryMcu(HmiMcuHistoryRecordBean mcuHistoryRecordBean) {
        mlogList.add(0, "历史记录Mcu：" + mcuHistoryRecordBean.toString());
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onHistoryApp(HmiAppHistoryRecordBean appHistoryRecordBean) {
        mlogList.add(0, "历史记录app：" + appHistoryRecordBean.toString());
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onVersion(String version) {
        mlogList.add(0, "版本号：" + version);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);

    }

    @Override
    public void onMcuBatteryStatus(int status, int battery) {
        mlogList.add(0, "电量状态" + status + " 电量：" + battery);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onSysTime(int status, int[] times) {
        mlogList.add(0, "时间状态" + status);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void requestSynTime() {
        mlogList.add(0, "同步时间");
        if (bodyFatBleUtilsData != null)
            bodyFatBleUtilsData.synMcuTime();
    }

    @Override
    public void setTimeCallback(int type, int status) {
        String msg = "";
        if (type == CmdConfig.SET_SYS_TIME) {
            msg = "设置系统当前时间：";
        } else if (type == CmdConfig.SET_DEVICE_TIME) {
            msg = "同步时间";
        }
        if (status == HmiBodyFatDataUtil.STATUS_SUCCESS) {
            msg = msg + status + " 成功";
        } else if (status == HmiBodyFatDataUtil.STATUS_FAIL) {
            msg = msg + status + " 失败";
        } else if (status == HmiBodyFatDataUtil.STATUS_NOT_SUPPORT) {
            msg = msg + status + " 不支持";
        }
        mlogList.add(0, msg);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);

    }

    @Override
    public void requestSynHistoryCallback(int status) {
        if (status == 0) {
            mlogList.add(0, "请求历史记录：" + status + " 无历史记录");
        } else if (status == 1) {
            mlogList.add(0, "请求历史记录：" + status + " 开始发送历史记录");
        } else {
            mlogList.add(0, "请求历史记录：" + status + " 发送历史记录结束");
        }
    }

    @Override
    public void updateUserCallback(int status) {
        if (status == 0) {
            mlogList.add(0, "更新用户或列表回调" + status + " 更新列表成功");
        } else if (status == 1) {
            mlogList.add(0, "更新用户或列表回调" + status + " 更新个人用户成功");
        } else if (status == 2) {
            mlogList.add(0, "更新用户或列表回调" + status + " 更新列表失败");
        } else {
            mlogList.add(0, "更新用户或列表回调" + status + " 更新个人用户失败");
        }
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    /**
     * @param status {@link#Bod}
     */
    @Override
    public void setUnitCallback(int status) {
        if (status == 0) {
            mlogList.add(0, "下发单位回调" + status + " 成功");
        } else if (status == 1) {
            mlogList.add(0, "下发单位回调" + status + " 失败");
        } else {
            mlogList.add(0, "下发单位回调" + status + " 不支持");
        }
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void requestUserData(int status) {
        if (status == 0x01) {
            mlogList.add(0, "下发用户信息 " + status);
        } else if (status == 0x03) {
            mlogList.add(0, "下发用户信息成功 " + status);
        } else {
            mlogList.add(0, "下发用户信息失败 " + status);
        }
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }

    @Override
    public void onOtaCallback(int status) {

    }

    @Override
    public void onIpData(String ip) {

    }

    @Override
    public void onPortData(int port) {

    }

    @Override
    public void onUrlData(String url) {

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.history) {
            if (bodyFatBleUtilsData != null)
                bodyFatBleUtilsData.requestSynHistory();
        } else if (id == R.id.btnUser) {
            if (!mEditText.getText().toString().trim().isEmpty()) {
                int userid = Integer.parseInt(mEditText.getText().toString().trim());
                if (mUsers.size() >= userid) {
                    selectUser = mUsers.get(userid - 1);
                    if (bodyFatBleUtilsData != null) {
                        bodyFatBleUtilsData.updateUserInfo(selectUser);
                    }
                }
            } else {
                addLog("请输入正确的用户ID");
            }
        } else if (id == R.id.userlist) {
            bodyFatBleUtilsData.setUserInfoList(mUsers);
            if (bodyFatBleUtilsData != null)
                bodyFatBleUtilsData.updateUsersComplete();
        } else if (id == R.id.adduser) {
            AddUserDialog addUserDialog = new AddUserDialog(new AddUserDialog.OnDialogListener() {
                @Override
                public void tvSucceedListener(UserBean user) {
                    user.setId(mUsers.size() + 1);
                    mUsers.add(getHmiBodyFatUserBean(user));
                    mUserlogList.add(user.toString());
                    userAdapter.notifyDataSetChanged();
                }
            });
            addUserDialog.show(getSupportFragmentManager());
        } else if (id == R.id.syntime) {
            if (bodyFatBleUtilsData != null) {
                bodyFatBleUtilsData.synSysTime();
            }
        }

    }


    private HmiBodyFatUserBean getHmiBodyFatUserBean(UserBean userBean) {
        HmiBodyFatUserBean hmiBodyFatUserBean = new HmiBodyFatUserBean();
        if (userBean.getSex() == UserBean.SEX_MAN) {
            hmiBodyFatUserBean.setSex(HmiBodyFatDataUtil.SEX_MAN);
        } else {
            hmiBodyFatUserBean.setSex(HmiBodyFatDataUtil.SEX_FEMAN);
        }
        if (userBean.getModeType() == UserBean.MODE_ATHLETE) {
            hmiBodyFatUserBean.setModeType(HmiBodyFatDataUtil.MODE_ATHLETE);
        } else if (userBean.getModeType() == UserBean.MODE_PREGNANT) {
            hmiBodyFatUserBean.setModeType(HmiBodyFatDataUtil.MODE_PREGNANT);
        } else {
            hmiBodyFatUserBean.setModeType(HmiBodyFatDataUtil.MODE_ORDINARY);
        }
        hmiBodyFatUserBean.setId(userBean.getId());
        hmiBodyFatUserBean.setAge(userBean.getAge());
        hmiBodyFatUserBean.setHeight(userBean.getHeight());
        hmiBodyFatUserBean.setWeight(userBean.getWeight());
        hmiBodyFatUserBean.setAdc(userBean.getAdc());
        return hmiBodyFatUserBean;
    }


    private void addLog(String log) {
        mlogList.add(0, TimeUtils.getTimeSSS() + log);
        mMHandler.sendEmptyMessage(TO_REFRESH_UI);
    }


    private final int TO_REFRESH_UI = 300;
    private final int TO_REFRESH_USER = 301;


    private class MHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TO_REFRESH_UI:
                    if (listAdapter != null) {
                        listAdapter.notifyDataSetChanged();
                    }
                    break;
                case TO_REFRESH_USER:
                    if (userAdapter != null) {
                        mUserlogList.clear();
                        if (mUsers != null) {
                            for (HmiBodyFatUserBean user : mUsers) {
                                mUserlogList.add(user.toString());
                            }
                        }
                        userAdapter.notifyDataSetChanged();
                    }
                    break;

            }
        }
    }


}