package com.phlx.wool.ui.inventory;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.BaseKeyListener;
import android.text.method.DigitsKeyListener;
import android.text.method.KeyListener;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.phlx.wool.App;
import com.phlx.wool.BR;
import com.phlx.wool.Configs;
import com.phlx.wool.R;
import com.phlx.wool.data.VMFactory;
import com.phlx.wool.databinding.ActivityInventoryBinding;
import com.phlx.wool.entity.Label;
import com.phlx.wool.rfid.ModuleManager;
import com.phlx.wool.ui.base.BaseActivity;
import com.uhf.structures.InventoryParams;

import java.lang.reflect.Method;

import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;

/**
 * <pre>
 *     author : lei
 *     e-mail : 18600395998@163.com
 *     time   : 2020/04/26
 *     desc   : 盘点标签页面
 *     version: 1.0
 * </pre>
 */
public class InventoryActivity extends BaseActivity<ActivityInventoryBinding, InventoryVM> {


    private String type = null;

    private String labelStr = "";

    private int tempCount, temp2Count, temp3Count;

    @Override
    public void initParam() {
        super.initParam();
        Bundle mBundle = getIntent().getExtras();
        if (mBundle != null) {
            type = mBundle.getString("type");
        }
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_inventory;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public InventoryVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(InventoryVM.class);
    }

    @Override
    public void initData() {
        super.initData();
        setSupportActionBar(binding.include.toolbar);

//        disableShowSoftInput(binding.etInvDesc);
        viewModel.initToolbar(type);
        binding.setAdapter(new BindingRecyclerViewAdapter());
        if ("0".equals(Configs.FREQUENCY_CONFIG)) {
            if (ModuleManager.powerOn() != 0) {
                new MaterialDialog.Builder(this).title("系统提示").content("模块连接失败").cancelable(false).canceledOnTouchOutside(false).positiveText("退出").onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            App.getInstance().getLinkage().stopInventory();
                            ModuleManager.destroyLibSO();
                            finish();
                        }
                    }
                }).show();
            }
            //设置盘点内容：Epc + Tid
            InventoryParams inventoryParams = new InventoryParams();
            inventoryParams.address = 0;
            inventoryParams.inventoryArea = 1;
            inventoryParams.len = 6;
            App.getInstance().getLinkage().Radio_SetInventoryParams(inventoryParams);
        }


    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.labelSizeDialogEvent.observe(InventoryActivity.this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean b) {

                new MaterialDialog.Builder(InventoryActivity.this).title("系统提示").content(
//                        "标签中含有" + count + "个未记录的标签，是否继续？")
                        "标签未扫满20，是否跳转？")
                        .positiveText("确定").negativeText("取消").onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog,
                                        @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            viewModel.farwardNext();
                        }
                    }
                }).show();

            }
        });

//        InputConnection ic =  binding.etInvDesc.getContentDescription()
//
        binding.etInvDesc.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        && keyEvent.getKeyCode() != KeyEvent.KEYCODE_ENTER
                ) {
                    tempCount++;
                    viewModel.setTest(tempCount + "");
                } else if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    temp2Count++;
                    viewModel.setTest2(temp2Count + "");
                } else if(keyEvent.getAction() == KeyEvent.FLAG_LONG_PRESS){
                    temp3Count++;
                    viewModel.setTest3(temp3Count + "");

                }
//                if (tempCount > 1) {
//                    tempCount = 0;
//
//                    binding.etInvDesc.dispatchKeyEvent(KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_UP));
//                }
                return false;

            }
        });

//        binding.etInvDesc.setKeyListener(new DigitsKeyListener(){
//            @Override
//            public boolean onKeyDown(View view, Editable content, int keyCode, KeyEvent event) {
//                Log.e("why", "onKeyDown:" + event);
//                return super.onKeyDown(view, content, keyCode, event);
//            }
//
//            @Override
//            public boolean onKeyUp(View view, Editable content, int keyCode, KeyEvent event) {
//                Log.e("why", "onKeyUp:" + event);
//                return super.onKeyUp(view, content, keyCode, event);
//            }
//        });

        binding.etInvDesc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                labelStr =  charSequence.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable editable) {
                binding.etInvDesc.removeTextChangedListener(this);
                viewModel.trim();

//                binding.etInvDesc.setFocusable(true);
//                binding.etInvDesc.setFocusableInTouchMode(true);
                binding.etInvDesc.requestFocus();
                binding.etInvDesc.requestFocusFromTouch();

                binding.etInvDesc.setSelection(editable.length());
                binding.etInvDesc.addTextChangedListener(this);
            }
        });

        viewModel.inventoryBtnEvent.observe(this, aBoolean -> {
            if (binding.inventory.getText().equals("盘点")) {
                binding.inventory.setText("停止");
                binding.progressBar.setVisibility(View.VISIBLE);
                binding.inventory.setBackground(getResources().getDrawable(R.drawable.inventory_stop_btn_bg));
                App.getInstance().getLinkage().startInventory(1, 0);
            } else {
                binding.inventory.setText("盘点");
                binding.inventory.setBackground(getResources().getDrawable(R.drawable.inventory_start_btn_bg));
                App.getInstance().getLinkage().stopInventory();
                binding.progressBar.setVisibility(View.GONE);
            }

        });

        viewModel.labelCheckEvent.observe(this, new Observer<Label>() {
            @Override
            public void onChanged(Label _label) {
                new MaterialDialog.Builder(InventoryActivity.this).title("系统提示").content(
//                        "标签中含有" + count + "个未记录的标签，是否继续？")
                        "标签未记录，是否添加？")
                        .positiveText("确定").negativeText("取消").onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog,
                                        @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            viewModel.addLabel(_label);
                        }
                    }
                }).show();
            }
        });


    }

    /**
     * 禁止Edittext弹出软件盘，光标依然正常显示。
     */
    public static void disableShowSoftInput(EditText editText) {
        Class<EditText> cls = EditText.class;
        Method method;
        try {
            method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(editText, false);
        } catch (Exception e) {
            // TODO: 2018/8/27 处理错误
        }

    }
}
