package com.bonait.bnframework.modules.home.fragment.from.fragment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_SILOSANDMATERIAL;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.wl_adapter;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Jcsjgl_wl_fragment extends BaseFragment implements MyClickListener {
    @BindView(R.id.add_wl)
    Button add_wl;
    @BindView(R.id.datatab_wl)
    ListView datatab_wl;
    /**
     * 物料数据
     */
    ArrayList<BPA_MATERIAL> bpa_materials = new ArrayList<>();
    private Context context;

    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_jcsjgl_wl, null);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Logger.d("我的fragment创建");
        context = getContext();
        InitView();
    }
    /**
     * 初始化界面
     */
    public void InitView() {
        Initdata_wl();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj.toString()== "MSG_REFRESH") {
                Initdata_wl();
            }
        }
    };

    @OnClick({R.id.add_wl, R.id.synchronous})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_wl://增加物料
                final QMUIDialog.EditTextDialogBuilder builder_add = new QMUIDialog.EditTextDialogBuilder(context);
                builder_add.setTitle("物料名称")
                        .setPlaceholder("在此输入物料名称")
                        .setInputType(InputType.TYPE_CLASS_TEXT)
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                CharSequence text = builder_add.getEditText().getText();
                                if (text != null && text.length() > 0) {
                                    if (QueryDB.GetMaterialIs(text.toString())) {
                                        ToastUtils.info("物料名称重复,请重新输入后重试!");
                                        return;
                                    }
                                    BPA_MATERIAL bpa_material = new BPA_MATERIAL();
                                    bpa_material.name = text.toString();
                                    bpa_material.imgUrl = "";
                                    bpa_material.type = 0;
                                    bpa_material.deviceID = ConfigName.getInstance().DeviceId;
                                    bpa_material.userID = ConfigName.getInstance().user.userID;
                                    QueryDB.AddMaterial(bpa_material);
                                    ToastUtils.info("新增成功");
                                    Initdata_wl();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("物料名称不能为空！");
                                }
                            }
                        })
                        .show();
                break;
            case R.id.synchronous://同步云端
                if (NetworkUtils.checkNetworkAvailable(context)) {
                    final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(context);
                    builder.setTitle("密码确认")
                            .setPlaceholder("在此输入权限密码")
                            .setInputType(InputType.TYPE_CLASS_TEXT)
                            .addAction("取消", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    dialog.dismiss();
                                }
                            })
                            .addAction("确定", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    CharSequence text = builder.getEditText().getText();
                                    if (text != null && text.length() > 0) {
                                        if (text.toString().equals(ConfigName.getInstance().user.pass)) {
                                            ConfigData.getInstance().SyncDataInTheCloud(context,mHandler);
                                            dialog.dismiss();
                                        } else {
                                            ToastUtils.info("权限密码不正确！");
                                        }
                                    } else {
                                        ToastUtils.info("权限密码不正确！");
                                    }
                                }
                            })
                            .show();
                } else {
                    ToastUtils.warning("无网络,请先连接网络!!!");
                }
                break;
        }
    }


    //region 数据加载

    /**
     * 初始化数据加载
     */
    public void Initdata_wl() {
        try {
            bpa_materials = QueryDB.GetMaterialALL();
            wl_adapter adapter = new wl_adapter(context, R.layout.wl_item, bpa_materials, this);
            datatab_wl.setAdapter(adapter);
        } catch (Exception e) {

        }
    }
    //endregion

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (DataBus.getInstance().mListener != null) {
//            DataBus.getInstance().mListener.clickListenerNew(this.getView(), 0, "");
//        }
        Logger.d("我的fragment销毁");
    }

    /**
     * 当在activity设置viewPager + BottomNavigation + fragment时，
     * 为防止viewPager左滑动切换界面，与fragment左滑返回上一界面冲突引起闪退问题，
     * 必须加上此方法，禁止fragment左滑返回上一界面。
     * <p>
     * 切记！切记！切记！否则会闪退！
     * <p>
     * 当在fragment设置viewPager + BottomNavigation + fragment时，则不会出现这个问题。
     */
    @Override
    protected boolean canDragBack() {
        return false;
    }

    /**
     * 点击事件
     *
     * @param v
     * @param data
     */
    @Override
    public void clickListener(View v, Object data) {
        switch (v.getId()) {
            case R.id.name://修改物料名称按钮
            case R.id.button_update://修改物料名称按钮
                final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(context);
                builder.setTitle("物料名称")
                        .setPlaceholder("在此输入物料名称")
                        .setDefaultText(((BPA_MATERIAL) data).name)
                        .setInputType(InputType.TYPE_CLASS_TEXT)
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                CharSequence text = builder.getEditText().getText();
                                if (text != null && text.length() > 0) {
                                    if (QueryDB.GetMaterialIs(text.toString())) {
                                        ToastUtils.info("物料名称重复,请重新输入后重试!");
                                        return;
                                    }
                                    QueryDB.UpdateMaterialName(((BPA_MATERIAL) data).id, text.toString());
                                    Initdata_wl();
                                    ToastUtils.info("修改成功");
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("物料名称不能为空！");
                                }
                            }
                        })
                        .show();
                break;
            case R.id.button_item://删除按钮
                String title = "温馨提示！";
                String message = "客官确定要删除物料【"+((BPA_MATERIAL) data).name+"】吗？";
                AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        QueryDB.DeleteMaterial((BPA_MATERIAL) data);
                        Initdata_wl();
                        ToastUtils.info("删除成功");
                        dialog.dismiss();
                    }
                });
                break;
        }
    }

    @Override
    public void clickListenerNew(View v, int k, Object data) {

    }

}