package xn.hxp.weidith.ble;

import android.bluetooth.BluetoothDevice;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatDialog;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.feasycom.common.bean.ConnectType;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.rc.httpcore.HttpConfig;
import com.rc.httpcore.bean.HxpChemicalVo;
import com.rc.httpcore.client.HttpTool;

import org.json.JSONObject;

import okhttp3.Response;
import xn.hxp.R;
import xn.hxp.app.ChemicalApp;
import xn.hxp.databinding.DialogBluetoothWeighBinding;
import xn.hxp.ui.plan.add.AddActivity;
import xn.hxp.utils.bluetooth.SppTool;

public class BluetoothWeighDialog extends AppCompatDialog {
    private DialogBluetoothWeighBinding binding;
    private final AddActivity addActivity;
    private final HxpChemicalVo hxpChemicalVo;
    private DialogCallBack dialogCallBack;

    public BluetoothWeighDialog(AddActivity addActivity, HxpChemicalVo hxpChemicalVo, DialogCallBack dialogCallBack) {
        super(addActivity);
        this.addActivity = addActivity;
        this.hxpChemicalVo = hxpChemicalVo;
        this.dialogCallBack = dialogCallBack;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DialogBluetoothWeighBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Window window = getWindow();
        if (null != window) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setGravity(Gravity.CENTER);
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        }

        // 提示图片加载
        if (null != ChemicalApp.confs && ChemicalApp.confs.getWeighHintPicture() != null && !ChemicalApp.confs.getWeighHintPicture().isEmpty()) {
            Glide.with(addActivity)
                    .load(HttpConfig.Companion.getAPI_BASE_IMG_URL() + ChemicalApp.confs.getWeighHintPicture())
                    .placeholder(R.mipmap.img_syt_cz)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                    .into(binding.hintIV);
        }
        // 净含量
        binding.netWtET.setText(String.valueOf(hxpChemicalVo.getNetContent()));
        // 规格
        binding.specsTV.setText(hxpChemicalVo.getSpecNum() + hxpChemicalVo.getSpecUnit());
        // 蓝牙称
        String sppMac = SPUtils.getInstance().getString("sppMac", "");
        if (TextUtils.isEmpty(sppMac)) {
            Toast.makeText(ActivityUtils.getTopActivity(), "未配置蓝牙称!", Toast.LENGTH_LONG).show();
        } else {
            SppTool.INSTANCE.connect(sppMac, new SppTool.BleSppCallback() {
                String weight = "";

                @Override
                public void sppPeripheralConnected(BluetoothDevice bluetoothDevice, ConnectType connectType) {

                }

                @Override
                public void packetReceived(String address, String strValue) {
                    if (!weight.equals(strValue)) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    double w = Double.parseDouble(strValue);
                                    hxpChemicalVo.setWeigh(w);
                                    binding.weighTV.setText(strValue + "g");
                                    weight = strValue;
                                } catch (Exception e) {
                                    Toast.makeText(ActivityUtils.getTopActivity(), "蓝牙称值异常! " + weight, Toast.LENGTH_SHORT).show();
                                }
                                if (binding.weightRL.getVisibility() != View.VISIBLE) {
                                    binding.weightRL.setVisibility(View.VISIBLE);
                                }
                                if (binding.loadingLAV.getVisibility() == View.VISIBLE) {
                                    binding.loadingLAV.cancelAnimation();
                                    binding.loadingLAV.setVisibility(View.GONE);
                                }
                            }
                        });
                    }
                }

                @Override
                public void sppPeripheralDisconnected(String address) {

                }
            });
        }

        // 取消
        binding.cancelBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {
                dialogCallBack.cancel(BluetoothWeighDialog.this, "取消称重!");
            }
        });
        // 确认
        binding.confirmBT.setOnClickListener(new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {

                Editable netWtETText = binding.netWtET.getText();
                if (null == netWtETText || TextUtils.isEmpty(netWtETText)) {
                    binding.netWtET.setError("请输入净含量");
                    return;
                }
                double netWt = -1.0;
                try {
                    netWt = Double.parseDouble(netWtETText.toString());
                } catch (Exception e) {
                    binding.netWtET.setError("请检查净含量内容正确");
                    return;
                }
                if (netWt <= 0) {
                    binding.netWtET.setError("请检查净含量内容正确");
                    return;
                }
                // 净含量不可大于规格
                if (netWt > hxpChemicalVo.getSpecNum()) {
                    binding.netWtET.setError("净含量不能大于规格");
                    return;
                }
                // 净含量不可大于称重
                if (netWt > hxpChemicalVo.getWeigh()) {
                    binding.netWtET.setError("净含量不能大于称重");
                    return;
                }
                hxpChemicalVo.setNetContent(netWt);
                WaitDialog.show("校验中...");
                ThreadUtils.executeByCached(new ThreadUtils.SimpleTask<String>() {
                    @Override
                    public String doInBackground() throws Throwable {
                        Response response = HttpTool.addStockCheck(hxpChemicalVo);
                        if (response.isSuccessful()) {
                            String json = response.body().string();
                            JSONObject jsonObject = new JSONObject(json);
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                return "ok";
                            } else {
                                return jsonObject.getString("message");
                            }
                        } else {
                            return response.message();
                        }
                    }

                    @Override
                    public void onSuccess(String result) {
                        WaitDialog.dismiss();
                        if ("ok".equals(result)) {
                            hxpChemicalVo.setJoinType(1);
                            dialogCallBack.confirm(BluetoothWeighDialog.this);
                        } else if (null == result || result.isEmpty()) {
                            dialogCallBack.cancel(BluetoothWeighDialog.this, "称重失败,系统异常!");
                        } else {
                            PopTip.show(result);
                        }
                    }
                });
            }
        });
        setCancelable(false);
        setCanceledOnTouchOutside(false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        SppTool.INSTANCE.disconnect();
    }


    public interface DialogCallBack {
        // 成功
        void confirm(BluetoothWeighDialog bluetoothWeighDialog);

        // 取消
        void cancel(BluetoothWeighDialog bluetoothWeighDialog, String msg);
    }

}
