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.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.EightBodyFatMcuDeviceData;
import cn.net.aicare.modulelibrary.module.EightBodyfatscale.EightBodyFatUtil;

/**
 * 八电极秤 MCU
 */
public class EightBodyFatMcuActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, EightBodyFatMcuDeviceData.onEightBodyFatMcuCallback {

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

    @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("八电极秤 MCU算法:0x" + Integer.toHexString(EightBodyFatUtil.EIGHT_BODY_FAT_SCALE_MCU));
    }

    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 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 initListener() {
        findViewById(R.id.getSupportUnit).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        kg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightBodyFatDeviceData != null)
                        mEightBodyFatDeviceData.setWeightUnit(EightBodyFatUtil.KG);

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

    @Override
    public void onServiceSuccess() {
        loglist.add(0, "绑定服务成功");
        if (mAILinkBleManager != null) {
            mAILinkBleManager.setOnCallbackBle(this);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                mEightBodyFatDeviceData = new EightBodyFatMcuDeviceData(bleDevice);
                mEightBodyFatDeviceData.setEightBodyFatCallback(this);
            }
        }

    }

    @Override
    public void onServiceErr() {

    }

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

    @Override
    public void onDisConnected(String mac, int code) {
        if (mAddress.equals(mac)) {
            addLog("连接断开:" + code);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.getSupportUnit) {
            if (mEightBodyFatDeviceData != null)
                mEightBodyFatDeviceData.getUnitList();
        }else if (v.getId() == R.id.btn_update) {
            initUserInfo();
            addLog("更新用户信息");
        }
    }


    @Override
    public void onState(int opCode, int result) {
        //0x01 : 校准 0x02 : 温度单位切换 0x03：重量单位切换
        String opCodeStr = "";
        if (opCode == 0x01) {
            opCodeStr = "校准";
        } else if (opCode == 0x02) {
            opCodeStr = "温度单位切换";
        } else if (opCode == 0x03) {
            opCodeStr = "重量单位切换";
        }
        String resultStr = "";
        if (result == 0x00) {
            resultStr = "操作成功";
        } else if (result == 0x01) {
            resultStr = "操作失败";
        } else if (result == 0x02) {
            resultStr = "正在操作中";
        }
        addLog("设备返回操作指令:" + opCodeStr + " 结果:" + resultStr);
    }


    @Override
    public void onWeight(int status, int weight, int unit, int decimal) {
        String statusStr = "";
        if (status == 0x01) {
            statusStr = "实时体重";
        } else if (status == 0x02) {
            statusStr = "稳定体重";
            mUserInfoBean.setWeightKg(Float.parseFloat(UnitUtils.getWeightToKg(unit,String.valueOf(weight),decimal)));
        }
        float weightF = Float.parseFloat(UnitUtils.getHoldDecimal(decimal, weight));
        String unitStr = "";
        if (unit == EightBodyFatUtil.KG) {
            unitStr = "kg";
            mUserInfoBean.setWeightKg(weightF);
        } else if (unit == EightBodyFatUtil.JIN) {
            unitStr = "斤";
            mUserInfoBean.setWeightKg(weightF / 2);
        } else if (unit == EightBodyFatUtil.ST) {
            unitStr = "lb(未转换为st:lb)";
        } else if (unit == EightBodyFatUtil.LB) {
            unitStr = "lb";
        }
        if (et_weight != null) {
            et_weight.setText(String.valueOf(weightF));
        }
        addLog("体重:" + statusStr + "  " + weightF + unitStr);
    }

    @Override
    public void onHeight(int status, int height, int unit) {
        String statusStr = "";
        if (status == 0x01) {
            statusStr = "测量中";
        } else if (status == 0x03) {
            statusStr = "测量失败";
        } else if (status == 0x02) {
            statusStr = "测量完成";
        }
        String unitStr = "";
        if (unit == 0x00) {
            unitStr = "cm";
        } else if (unit == 0x01) {
            unitStr = "inch";
        } else if (unit == 0x02) {
            unitStr = "ft-in";
        }
        addLog("身高:" + statusStr + "  " + height + unitStr);
    }

    private EightBodyFatAdc mEightBodyFatAdc;

    @Override
    public void onImpedance(int status, EightBodyFatMcuDeviceData.EightBodyFatAdc eightBodyFatAdc, int arithmetic) {
        String statusStr = "";
        if (status == EightBodyFatUtil.IMPEDANCE_MEASUREMENT) {
            statusStr = "测量中";
            mEightBodyFatAdc = new EightBodyFatAdc();
            mEightBodyFatAdc.setAlgorithms(0x20);
        } else if (status == EightBodyFatUtil.IMPEDANCE_FAILED) {
            statusStr = "测量失败";
        } else if (status == EightBodyFatUtil.IMPEDANCE_SUCCESS_MCU) {
            statusStr = "测量完成";

        }
        String partStr = "";
        int part = eightBodyFatAdc.getPart();
        int adc = eightBodyFatAdc.getAdc();
        if (part == 0x00) {
            partStr = "双脚阻抗";
            mEightBodyFatAdc.setAdcFoot(adc);
        } else if (part == 0x01) {
            partStr = "双手阻抗";
            mEightBodyFatAdc.setAdcHand(adc);
        } else if (part == 0x02) {
            partStr = "左手阻抗";
            mEightBodyFatAdc.setAdcLeftHand(adc);
        } else if (part == 0x03) {
            partStr = "右手阻抗";
            mEightBodyFatAdc.setAdcRightHand(adc);
        } else if (part == 0x04) {
            partStr = "左脚阻抗";
            mEightBodyFatAdc.setAdcLeftFoot(adc);
        } else if (part == 0x05) {
            partStr = "右脚阻抗";
            mEightBodyFatAdc.setAdcRightFoot(adc);
        } else if (part == 0x06) {
            partStr = "左全身阻抗";
            mEightBodyFatAdc.setAdcLeftBody(adc);
        } else if (part == 0x07) {
            partStr = "右全身阻抗";
            mEightBodyFatAdc.setAdcRightBody(adc);
        } else if (part == 0x08) {
            partStr = "右手左脚阻抗";
            mEightBodyFatAdc.setAdcRightHandLeftFoot(adc);
        } else if (part == 0x09) {
            partStr = "左手右脚阻抗";
            mEightBodyFatAdc.setAdcLeftHandRightFoot(adc);
        } else if (part == 0x0A) {
            partStr = "躯干阻抗";
            mEightBodyFatAdc.setAdcBody(adc);
        }

        addLog("阻抗:" + statusStr + "  " + partStr + " : " + adc);
    }

    @Override
    public void onHeartRate(int status, int heartRate) {
        String statusStr = "";
        if (status == EightBodyFatUtil.HEART_RATE_MEASUREMENT) {
            statusStr = "测量中";
        } else if (status == EightBodyFatUtil.HEART_RATE_SUCCESS) {
            statusStr = "测量成功";
        } else if (status == EightBodyFatUtil.HEART_RATE_FAILED) {
            statusStr = "测量失败";
        }
        addLog("心率:" + statusStr + "  " + heartRate);
    }

    @Override
    public void onTemp(int sign, int temp, int unit, int decimal) {
        double tempValue = temp / (decimal * 10.0);
        if (decimal == 0) {
            tempValue = temp;
        }
        if (sign == 1) {
            tempValue = -tempValue;
        }
        String unitStr = "";
        if (unit == EightBodyFatUtil.C) {
            unitStr = "℃";
        } else if (unit == EightBodyFatUtil.F) {
            unitStr = "℉";
        }
        addLog("温度:" + tempValue + unitStr);
    }

    @Override
    public void onSyncUserInfo() {
        addLog("请求同步用户信息:" + "默认传入用户:" + mUserInfoBean.toString());
        if (mEightBodyFatDeviceData != null) {
            mEightBodyFatDeviceData.setUserInfo(mUserInfoBean.getUserId(), mUserInfoBean.getUserType(), mUserInfoBean.getSex(), mUserInfoBean.getAge(), mUserInfoBean.getHeightCm());
        }
    }

    @Override
    public void onCompletionData() {
        addLog("请求补充体脂数据");
        if (mEightBodyFatAdc != null) {
            mEightBodyFatAdc.setAlgorithms(0xFFFF);
        }
    }

    @Override
    public void onBodyFatData(int step, EightBodyFatMcuDeviceData.EightBodyFatInfo bodyFat) {
        addLog("体脂测量中,步骤:" + step);
    }

    @Override
    public void onTestSuccess(EightBodyFatMcuDeviceData.EightBodyFatInfo bodyFat) {
        //测量完成
        addLog("体脂数据:" + bodyFat.toString());
    }

    @Override
    public void onErrCode(int code) {
        addLog("错误码:" + code);
    }

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

    @Override
    public void onSupportUnit(List<SupportUnitBean> list) {
        addLog("支持单位:");
        for (SupportUnitBean supportUnitBean : list) {
            addLog(supportUnitBean.toString());
        }
    }

    @Override
    public void showData(String data) {
        addLog(data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AILinkBleManager.getInstance().disconnect(mAddress);

    }

    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();
        }
    }


}
