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

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;

import androidx.annotation.Nullable;

import com.pingwang.bluetoothlib.AILinkBleManager;
import com.pingwang.bluetoothlib.bean.BleValueBean;
import com.pingwang.bluetoothlib.bean.SupportUnitBean;
import com.pingwang.bluetoothlib.device.BleDevice;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;

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

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.UnitUtils;
import cn.net.aicare.modulelibrary.module.EightBodyfatscale.EightBodyFatBleDeviceData;
import cn.net.aicare.modulelibrary.module.EightBodyfatscale.EightBodyFatUtil;
import cn.net.aicare.modulelibrary.module.EightBodyfatscale.EightOneBodyFatAdcBean;
import cn.net.aicare.modulelibrary.module.EightBodyfatscale.EightOneDataBodyFatBean;

/**
 * 八电极秤 (单频APP算法)
 */
public class EightBodyfatActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, EightBodyFatBleDeviceData.EightBodyFatCallback {

    private List<String> loglist;
    private ListView log_list;
    private ArrayAdapter listAdapter;
    private String mAddress;
    private EightBodyFatBleDeviceData mEightBodyFatBleDeviceData;
    private RadioButton kg, jing, stlb, lb, C, F;
    private UserInfoBean mUserInfoBean;
    private EditText et_weight, et_height, et_age, et_sex;
    private EightOneBodyFatAdcBean mEightOneBodyFatAdcBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eight_body_fata);
        mAddress = getIntent().getStringExtra("mac");

        initView();
        initData();
        initListener();
        setTitleData("八电极秤 APP算法:0x" + Integer.toHexString(EightBodyFatUtil.EIGHT_BODY_FAT_SCALE));
//        test();

    }

    private void test() {
        weight = 60;
        if (mEightOneBodyFatAdcBean == null) {
            mEightOneBodyFatAdcBean = new EightOneBodyFatAdcBean();
        }
        mEightOneBodyFatAdcBean.setAlgorithmsId(0x20);
        mEightOneBodyFatAdcBean.setAdcFoot(5784349);
        mEightOneBodyFatAdcBean.setAdcHand(5121114);
        mEightOneBodyFatAdcBean.setAdcLeftHand(12854746);
        mEightOneBodyFatAdcBean.setAdcRightHand(15738341);
        mEightOneBodyFatAdcBean.setAdcLeftFoot(1074604);
        mEightOneBodyFatAdcBean.setAdcRightFoot(13046299);
        mEightOneBodyFatAdcBean.setAdcLeftBody(7480094);
        mEightOneBodyFatAdcBean.setAdcRightBody(7480094);
        if (mEightBodyFatBleDeviceData != null) {
            mEightBodyFatBleDeviceData.getOneEightBodyData(mUserInfoBean.getSex(), mUserInfoBean.getAge(), mUserInfoBean.getWeightKg(),
                    mUserInfoBean.getHeightCm(), mEightOneBodyFatAdcBean);
        }
    }


    private void initData() {
        initUserInfo();
        loglist = new ArrayList<>();
        listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, loglist);
        log_list.setAdapter(listAdapter);
    }

    /**
     * 初始化用户信息
     */
    private void initUserInfo() {
        String weightKg = et_weight.getText().toString().trim();
        String height = et_height.getText().toString().trim();
        String age = et_age.getText().toString().trim();
        String sex = et_sex.getText().toString().trim();
        if (mUserInfoBean == null) {
            mUserInfoBean = new UserInfoBean();
            mUserInfoBean.setUserId(1);
            mUserInfoBean.setUserType(0);
        }
        mUserInfoBean.setAge(Integer.parseInt(age));
        mUserInfoBean.setSex(Integer.parseInt(sex));
        mUserInfoBean.setHeightCm(Integer.parseInt(height));
        mUserInfoBean.setWeightKg(Float.parseFloat(weightKg));
    }

    private void initView() {
        et_weight = findViewById(R.id.et_weight);
        et_height = findViewById(R.id.et_height);
        et_age = findViewById(R.id.et_age);
        et_sex = findViewById(R.id.et_sex);
        log_list = findViewById(R.id.log_list);
        kg = findViewById(R.id.kg);
        jing = findViewById(R.id.jin);
        stlb = findViewById(R.id.st_lb);
        lb = findViewById(R.id.lb);
        C = findViewById(R.id.c);
        F = findViewById(R.id.f);
    }


    private void initListener() {
        findViewById(R.id.getSupportUnit).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        findViewById(R.id.btnConnect).setOnClickListener(this);
        kg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatBleDeviceData != null)
                        mEightBodyFatBleDeviceData.setWeightUnit(EightBodyFatUtil.KG);

                }
            }
        });
        jing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatBleDeviceData != null)
                        mEightBodyFatBleDeviceData.setWeightUnit(EightBodyFatUtil.JIN);
                }
            }
        });
        stlb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatBleDeviceData != null)
                        mEightBodyFatBleDeviceData.setWeightUnit(EightBodyFatUtil.ST);
                }
            }
        });
        lb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatBleDeviceData != null)
                        mEightBodyFatBleDeviceData.setWeightUnit(EightBodyFatUtil.LB);
                }
            }
        });
        C.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatBleDeviceData != null)
                        mEightBodyFatBleDeviceData.setTempUnit(EightBodyFatUtil.C);
                }
            }
        });
        F.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatBleDeviceData != null)
                        mEightBodyFatBleDeviceData.setTempUnit(EightBodyFatUtil.F);
                }
            }
        });
        kg.setChecked(true);
        C.setChecked(true);
    }

    @Override
    public void onServiceSuccess() {
        addLog("绑定服务成功");
        if (mAILinkBleManager != null) {
            mAILinkBleManager.setOnCallbackBle(this);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                mEightBodyFatBleDeviceData = new EightBodyFatBleDeviceData(bleDevice);
                mEightBodyFatBleDeviceData.setEightBodyFatCallback(this);
            }
        }

    }

    @Override
    public void onServiceErr() {

    }

    @Override
    public void onServicesDiscovered(String mac) {
        onServiceSuccess();
    }

    @Override
    public void unbindServices() {
        if (mAILinkBleManager != null) {
            mAILinkBleManager.removeOnCallbackBle(this);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.getSupportUnit) {
            if (mEightBodyFatBleDeviceData != null)
                mEightBodyFatBleDeviceData.getUnitList();
        } else if (v.getId() == R.id.btn_update) {
            initUserInfo();
            addLog("更新用户信息");
        } else if (v.getId() == R.id.btnConnect) {
            if (mEightBodyFatBleDeviceData != null) {
                BleValueBean bleValueBean = mEightBodyFatBleDeviceData.getBleValueBean();
                if (bleValueBean != null) {
                    AILinkBleManager.getInstance().connectDevice(bleValueBean);
                }else {
                    AILinkBleManager.getInstance().connectDevice(mAddress);
                }
            }
        }
    }

    @Override
    public void onState(int type, int typeState, int result) {
        switch (type) {
//            case EightBodyfatUtil.WEIGHING:
//                switch (typeState) {
//                    case EightBodyfatUtil.WEIGHT_REAL_TIME_WEIGH:
//                        loglist.add(0, "实时体重");
//                        break;
//                    case EightBodyfatUtil.WEIGHT_STABILIZATION_WEIGHT:
//                        loglist.add(0, "稳定体重");
//                }
//                break;
            case EightBodyFatUtil.IMPEDANCE:
                String adc = "";
                switch (typeState) {
                    case EightBodyFatUtil.IMPEDANCE_MEASUREMENT:

                        adc = "阻抗测量中";
                        break;
                    case EightBodyFatUtil.IMPEDANCE_SUCCESS:
                        //阻抗测量成功
                        adc = "阻抗测量成功";
                        break;
                    case EightBodyFatUtil.IMPEDANCE_FAILED:
                        adc = "阻抗测量失败";
                        //阻抗测量失败
                        break;
                    case EightBodyFatUtil.IMPEDANCE_FINISH:
                        //阻抗测量完成
                        adc = "阻抗测量完成";
                        break;
                }
                addLog(adc);
                break;
            case EightBodyFatUtil.HEART_RATE:
                switch (typeState) {
                    case EightBodyFatUtil.HEART_RATE_MEASUREMENT:
                        //心率测量完成
                        addLog("心率测量中");
                        break;
                    case EightBodyFatUtil.HEART_RATE_SUCCESS:
                        addLog("心率测量成功");
                        //心率测量成功
                        break;
                    case EightBodyFatUtil.HEART_RATE_FAILED:
                        addLog("心率测量失败");
                        //心率测量失败
                        break;
                }
                break;
            case EightBodyFatUtil.TEMP_MEASUREMENT:
                addLog("测量温度");
                break;
            case EightBodyFatUtil.MEASUREMENT_END:
                addLog("测量完成");
                //测量完成
                if (mEightBodyFatBleDeviceData != null && mEightOneBodyFatAdcBean != null) {
                    mEightBodyFatBleDeviceData.getOneEightBodyData(mUserInfoBean.getSex(), mUserInfoBean.getAge(), mUserInfoBean.getWeightKg(),
                            mUserInfoBean.getHeightCm(), mEightOneBodyFatAdcBean);
                }

                break;
            case EightBodyFatUtil.MUC_CALL_BACK_RESULT:
                switch (typeState) {
                    case EightBodyFatUtil.APP_CMD_CALIBRATION:
                        //校验
                        if (result == EightBodyFatUtil.SUCCESS) {
                            addLog("校验成功");
                        } else if (result == EightBodyFatUtil.FAILED) {
                            addLog("校验失败");
                        } else {
                            addLog("校验中");
                        }
                        break;
                    case EightBodyFatUtil.APP_CMD_TEMP_UNIT:
                        if (result == EightBodyFatUtil.SUCCESS) {
                            addLog("切换温度成功");
                        } else if (result == EightBodyFatUtil.FAILED) {
                            addLog("切换温度失败");
                        } else {
                            addLog("切换温度中");
                        }
                        //切换温度
                        break;
                    case EightBodyFatUtil.APP_CMD_WEIGHT_UNIT:
                        if (result == EightBodyFatUtil.SUCCESS) {
                            addLog("切换体重单位成功");
                        } else if (result == EightBodyFatUtil.FAILED) {
                            addLog("切换体重单位失败");
                        } else {
                            addLog("切换体重单位中");
                        }
                        //切换温度
                        break;
                }
                break;
            case EightBodyFatUtil.ERROR_CODE:
                addLog("错误码" + typeState);
                break;

        }

    }

    private float weight;

    @Override
    public void onWeight(int state, float weight, int unit, int decimal) {
        //测量状态 1实时体重 2稳定体重
        String stateStr = "";
        if (state == EightBodyFatUtil.WEIGHT_REAL_TIME_WEIGH) {
            stateStr = "实时体重";
        } else if (state == EightBodyFatUtil.WEIGHT_STABILIZATION_WEIGHT) {
            stateStr = "稳定体重";
            mUserInfoBean.setWeightKg(Float.parseFloat(UnitUtils.getWeightToKg(unit, String.valueOf(weight), decimal)));
        }
        this.weight = weight;
        if (unit == EightBodyFatUtil.ST) {
            addLog("测量状态：" + state + stateStr + "  体重:" + EightBodyFatUtil.lbtostlb(weight) + "  体重单位:" + unit + " 小数点位" + decimal);
        } else {
            addLog("测量状态：" + state + stateStr + "  体重:" + weight + "  体重单位:" + unit + " 小数点位" + decimal);
        }
        if (et_weight != null) {
            et_weight.setText(String.valueOf(weight));
        }

    }


    @Override
    public void onImpedance(EightOneBodyFatAdcBean adcBean) {
        mEightOneBodyFatAdcBean = adcBean;
        addLog("阻抗测量完成:阻抗信息:" + adcBean);
    }

    @Override
    public void onHeartRate(int heartRate) {
        loglist.add(0, "  心率" + heartRate);
    }

    @Override
    public void onTemp(int sign, float temp, int unit, int decimal) {
        addLog("  温度 正负" + sign + "   温度:" + temp + "   单位: " + unit + "  小数位" + decimal);
    }

    @Override
    public void onVersion(String version) {
        addLog("当前版本：" + version);
    }

    @Override
    public void onSupportUnit(List<SupportUnitBean> list) {
        loglist.add(0, "支持单位:");
        for (SupportUnitBean supportUnitBean : list) {
            loglist.add(0, supportUnitBean.toString());
        }
        listAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBodyFatData(@Nullable EightOneDataBodyFatBean bodyFatBean) {
        addLog("获取体脂数据成功:\n" + bodyFatBean.toString());
    }

    @Override
    public void onBodyFatDataError(int type, String msg) {
        addLog("获取体脂数据失败:" + type + "  " + msg);
    }

    @Override
    public void showData(String data) {
//        loglist.add(0, data);
    }


    private String mOldLog = "";
    private SimpleDateFormat sdf;

    /**
     * 添加日志
     *
     * @param log 日志
     */
    private void addLog(String log) {
        if (mOldLog.equalsIgnoreCase(log)) {
            return;
        }
        if (sdf == null) {
            sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
        }
        mOldLog = log;
        loglist.add(0, sdf.format(System.currentTimeMillis()) + "：\n" + log);
        if (listAdapter != null) {
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAILinkBleManager != null) {
            mAILinkBleManager.disconnectAll();
        }
    }
}
