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

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

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 java.util.Map;

import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.base.BleBaseActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.JsonLoader;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.UnitUtils;
import cn.net.aicare.modulelibrary.module.EightBodyfatscale.EightBodyFatUtil;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.BaseEightDoubleBodyFatData;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.EightDoubleBodyFatAdcBean;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.EightDoubleBodyFatBleConfig;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.EightDoubleBodyFatBleDeviceData;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.EightDoubleBodyFatBleMcuDeviceData;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.EightDoubleDataBodyFatBean;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.EightDoubleMcuBodyFatBean;
import cn.net.aicare.modulelibrary.module.EightDoubleBodyfatScale.OnEightDoubleBodyFatCallback;

/**
 * 双频八电极秤(app/mcu算法)
 *
 * @author xing
 * @date 2024/03/14
 */
public class EightDoubleBodyfatActivity extends BleBaseActivity implements View.OnClickListener, OnCallbackBle, OnEightDoubleBodyFatCallback {


    /**
     * 刷新键
     */
    private final int REFRESH_KEY = 0x01;
    private List<String> mLoglist;
    private ListView log_list;
    private ArrayAdapter mAdapter;
    private String mAddress;
    private BaseEightDoubleBodyFatData mEightDoubleBodyFatData;
    private RadioButton kg, jing, stlb, lb;
    private EditText et_weight, et_height, et_age, et_sex;
    private String mWeightKg = "78";
    private UserInfoBean mUserInfoBean;
    private Map<String, String> mMap;
    private int mCid;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESH_KEY) {
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }


        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eight_double_body_fata);
        mAddress = getIntent().getStringExtra("mac");
        mCid = getIntent().getIntExtra("cid", 0);
        initView();
        initListener();
        initData();
        setTitleData("双频八电极秤:0x" + Integer.toHexString(mCid));
    }

    private void initData() {
        mLoglist = new ArrayList<>();
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mLoglist);
        log_list.setAdapter(mAdapter);
        mMap = JsonLoader.loadJsonFromAsset(this, "text.json");
        initUserInfo();
        Button test_bodyfit = findViewById(R.id.test_bodyfit);
        test_bodyfit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testAdc2();

            }
        });

    }

    private void testAdc1(){
        List<EightDoubleBodyFatAdcBean> list = new ArrayList<>();
        EightDoubleBodyFatAdcBean adcBean = new EightDoubleBodyFatAdcBean();
        adcBean.setAdcRightHand(0x70CE5D91L);
        adcBean.setAdcLeftHand(0x61A2D714L);
        adcBean.setAdcBody(0x3013EEE0L);
        adcBean.setAdcRightFoot(0x50A93C9FL);
        adcBean.setAdcLeftFoot(0x10071D0CL);
        adcBean.setFrequencyId(0x01);
        adcBean.setAlgorithmsId(0x01);
        list.add(adcBean);

        EightDoubleBodyFatAdcBean adcBean100 = new EightDoubleBodyFatAdcBean();
        adcBean100.setAdcRightHand(0x509A9A5FL);
        adcBean100.setAdcLeftHand(0x7037B559L);
        adcBean100.setAdcBody(0x3022CEC6L);
        adcBean100.setAdcRightFoot(0x60AA8F98L);
        adcBean100.setAdcLeftFoot(0x40F72698L);
        adcBean100.setFrequencyId(0x02);
        adcBean100.setAlgorithmsId(0x01);
        list.add(adcBean100);
        onTestCompleted(list);
    }
    private void testAdc2(){
        List<EightDoubleBodyFatAdcBean> list = new ArrayList<>();
        EightDoubleBodyFatAdcBean adcBean = new EightDoubleBodyFatAdcBean();
        adcBean.setAdcRightHand(1635046219);
        adcBean.setAdcLeftHand(31463021);
        adcBean.setAdcBody(540087696);
        adcBean.setAdcRightFoot(8196483);
        adcBean.setAdcLeftFoot(4182139);
        adcBean.setFrequencyId(0x01);
        adcBean.setAlgorithmsId(0x01);
        list.add(adcBean);

        EightDoubleBodyFatAdcBean adcBean100 = new EightDoubleBodyFatAdcBean();
        adcBean100.setAdcRightHand(1343010255);
        adcBean100.setAdcLeftHand(11339343);
        adcBean100.setAdcBody(536975770);
        adcBean100.setAdcRightFoot(816731059);
        adcBean100.setAdcLeftFoot(1884060387);
        adcBean100.setFrequencyId(0x02);
        adcBean100.setAlgorithmsId(0x01);
        list.add(adcBean100);
        onTestCompleted(list);
    }



    private void initUserInfo() {
        mWeightKg = 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(mWeightKg));
    }

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


    private void initListener() {

        findViewById(R.id.getSupportUnit).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        findViewById(R.id.btn_clear_log).setOnClickListener(this);
        kg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightDoubleBodyFatData != null) {
                        mEightDoubleBodyFatData.setWeightUnit(EightBodyFatUtil.KG);
                    }
                }
            }
        });
        jing.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mEightDoubleBodyFatData != null) {
                        mEightDoubleBodyFatData.setWeightUnit(EightBodyFatUtil.JIN);
                    }

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

    @Override
    public void onServiceSuccess() {
        showData("绑定服务成功");
        if (mAILinkBleManager != null) {
            mAILinkBleManager.setOnCallbackBle(this);
            BleDevice bleDevice = mAILinkBleManager.getBleDevice(mAddress);
            if (bleDevice != null) {
                if (mCid == EightDoubleBodyFatBleConfig.CID_APP) {
                    mEightDoubleBodyFatData = EightDoubleBodyFatBleDeviceData.init(bleDevice);
                } else if (mCid == EightDoubleBodyFatBleConfig.CID_MCU) {
                    mEightDoubleBodyFatData = EightDoubleBodyFatBleMcuDeviceData.init(bleDevice);
                } else {
                    L.e("无效的CID:" + mCid);
                    return;
                }
                mEightDoubleBodyFatData.setEightBodyFatCallback(this);
            }
        }

    }

    @Override
    public void onServiceErr() {

    }

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

    @Override
    public void onDisConnected(String mac, int code) {
        showData("连接断开:" + mac + "  code=" + code);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.getSupportUnit) {
            if (mEightDoubleBodyFatData != null) {
                mEightDoubleBodyFatData.getUnitList();
            }
        } else if (v.getId() == R.id.btn_clear_log) {
            mLoglist.clear();
            mHandler.sendEmptyMessage(REFRESH_KEY);
        } else if (v.getId() == R.id.btn_update) {
            initUserInfo();
            showData("更新用户信息");
        }
    }


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

    @Override
    public void onUnitState(int state) {
        showData("单位状态:" + state);
    }

    @Override
    public void onTestCompleted(List<EightDoubleBodyFatAdcBean> adcBeanList) {
        initUserInfo();
        mLoglist.add(0, "测试完成");
        for (EightDoubleBodyFatAdcBean adcBean : adcBeanList) {
            String data = "";
            data += (adcBean.getFrequencyId() == 0x01) ? "频率:20kHz" : "频率:100kHz";
            data += "\n 左手阻抗:" + adcBean.getAdcLeftHand();
            data += "\n 右手阻抗:" + adcBean.getAdcRightHand();
            data += "\n 左脚阻抗:" + adcBean.getAdcLeftFoot();
            data += "\n 右脚阻抗:" + adcBean.getAdcRightFoot();
            data += "\n 躯干阻抗:" + adcBean.getAdcBody();
            data += "\n 算法:" + adcBean.getAlgorithmsId();
            mLoglist.add(0, data);
        }
        mLoglist.add(0, "用户信息:" + mUserInfoBean.toString());
        getBodyFatData(adcBeanList);
        mHandler.sendEmptyMessage(REFRESH_KEY);
    }


    private void getBodyFatData(List<EightDoubleBodyFatAdcBean> adcBeanList) {
        if ((mCid != EightDoubleBodyFatBleConfig.CID_APP && mCid != EightDoubleBodyFatBleConfig.CID_MCU) || adcBeanList == null || adcBeanList.isEmpty()) {
            return;
        }
        if (mEightDoubleBodyFatData!=null) {
            mEightDoubleBodyFatData.getDualEightBodyData(mUserInfoBean.getSex(), mUserInfoBean.getAge(), mUserInfoBean.getWeightKg(),
                    mUserInfoBean.getHeightCm(), adcBeanList);
        }
    }

    @Override
    public void onWeight(int state, int weight, int decimal, int unit, int batteryStatus, int power) {
        //测量状态 1实时体重 2稳定体重
        float weightF = Float.parseFloat(UnitUtils.getHoldDecimal(decimal, weight));
        String stateStr = "";
        if (state == EightDoubleBodyFatBleConfig.STATUS_WEIGHT_REAL_TIME_WEIGH) {
            stateStr = "实时体重";
        } else if (state == EightDoubleBodyFatBleConfig.STATUS_WEIGHT_STABILIZATION_WEIGHT) {
            stateStr = "稳定体重";
            mUserInfoBean.setWeightKg(Float.parseFloat(UnitUtils.getWeightToKg(unit, String.valueOf(weightF), decimal)));
            mWeightKg = String.valueOf(weightF);
            if (et_weight != null) {
                et_weight.setText(mWeightKg);
            }
        }

        if (unit == EightDoubleBodyFatBleConfig.STATUS_ST) {
            showData("测量状态：" + state + stateStr + "  体重:" + lbToStlb(weightF) + "  体重单位:" + unit + " 小数点位" + decimal);
        } else {
            showData("测量状态：" + state + stateStr + "  体重:" + weightF + "  体重单位:" + unit + " 小数点位" + decimal);
        }
    }


    public static String lbToStlb(float lb) {
        int st = (int) lb / 14;
        float mlb = lb % 14f;
        return st + ":" + mlb;
    }

    @Override
    public void onImpedanceStatus(int status) {
        String adc = "";
        switch (status) {
            case EightDoubleBodyFatBleConfig.STATUS_IMPEDANCE_MEASUREMENT:
                adc = "阻抗测量中";
                break;
            case EightDoubleBodyFatBleConfig.STATUS_IMPEDANCE_SUCCESS:
                //阻抗测量成功
                adc = "阻抗测量成功";
                break;
            case EightDoubleBodyFatBleConfig.STATUS_IMPEDANCE_FAILED:
                adc = "阻抗测量失败";
                //阻抗测量失败
                break;

        }
        showData(adc);
    }


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

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

    @Override
    public void onBodyFatMcu(EightDoubleMcuBodyFatBean bodyFatBean) {
        if (bodyFatBean == null) {
            showData("体脂数据为空");
            return;
        }
        showData("体脂数据(MCU):" + bodyFatBean);
    }

    @Override
    public void onHeartRate(int status, int heartRate) {
        String statusStr = "";
        if (status == 0x01) {
            statusStr = "心率测量中";
        } else if (status == 0x02) {
            statusStr = "心率测量成功:" + heartRate;
        } else if (status == 0x03) {
            statusStr = "心率测量失败";
        }
        showData(statusStr);
    }

    @Override
    public void onTemperature(int temp, int unit, int decimal) {
        showData("温度:" + temp + " 单位:" + unit + " 小数点位" + decimal);
    }

    @Override
    public void onSyncUser() {
        if (mEightDoubleBodyFatData != null && mEightDoubleBodyFatData instanceof EightDoubleBodyFatBleMcuDeviceData) {
            ((EightDoubleBodyFatBleMcuDeviceData) mEightDoubleBodyFatData).setUserInfo(0, 0, mUserInfoBean.getAge(), mUserInfoBean.getSex(), mUserInfoBean.getHeightCm());
        }
        showData("设备请求同步用户信息");
    }

    @Override
    public void onBodyFatDataError(int type, String msg) {
        L.i("体脂数据计算错误:type=" + type + "     msg=" + msg);
        showData("体脂数据计算错误:type=" + type + "     msg=" + msg);
    }

    @Override
    public void onBodyFatData(@Nullable EightDoubleDataBodyFatBean bodyFatBean) {
        if (bodyFatBean != null) {
            L.i("体脂数据计算成功:" + bodyFatBean.toString());
            showData("体脂数据(服务器):\n" + bodyFatBean);
        }
    }

    private String mOldLog = "";
    private SimpleDateFormat sdf;

    /**
     * 添加日志
     *
     * @param log 日志
     */
    @Override
    public void showData(String log) {
        if (mOldLog.equalsIgnoreCase(log)) {
            return;
        }
        if (sdf == null) {
            sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
        }
        mOldLog = log;
        mLoglist.add(0, sdf.format(System.currentTimeMillis()) + "：\n" + log);
        mHandler.sendEmptyMessage(REFRESH_KEY);
    }


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