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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bonait.bnframework.R;
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_GOODPROPERTY;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.mode.BPA_GOODSRECIPENAME;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.linktab.LinkMode;
import com.bonait.bnframework.common.linktab.makegood.MakeGoodLeftAdapter;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.KeyboardUtil;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.AttributeSetAdapter;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUIWindowInsetLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

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

public class Jcsjgl_sxgl_fragment extends BaseFragment {// implements MyClickListener

    @BindView(R.id.datatab_sx)
    RecyclerView datatab_sx;
    @BindView(R.id.root)
    QMUIWindowInsetLayout root;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.tip)
    TextView textTip;

    /**
     * 属性数据
     */
    ArrayList<BPA_GOODPROPERTY> bpa_goodproperties = new ArrayList<>();

    ArrayList<BPA_GOODSTYPE> bpa_goodstypes=new ArrayList<>();
    ConcurrentHashMap<String,String> itemstypes=new ConcurrentHashMap<>();
    private String goodsTypeId = "";

    private Context context;
    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_jcsjgl_sxgl, 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() {
        root.setOnClickListener(KeyboardUtil::hideKeyboard);
        bpa_goodstypes= QueryDB.GetGoodsTypeALL();
        itemstypes.clear();
        for (BPA_GOODSTYPE item:bpa_goodstypes)
        {
            if(!itemstypes.containsKey(item.name))
            {
                itemstypes.put(item.name,item.id);
            }
        }
        initLeftView();
    }

    private List<LinkMode> leftData = new ArrayList<>();
    private void initLeftView(){
        leftData.clear();
        int i = 0;
        for (BPA_GOODSTYPE item : QueryDB.GetGoodsTypeALL()) {
            ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(item.id);
            leftData.add(new LinkMode(item, Arrays.asList(goodsm.toArray()), i == 0 ? true : false));
            i++;
        }
        MakeGoodLeftAdapter leftAdapter = new MakeGoodLeftAdapter(R.layout.item_left_makegood, leftData, getResources(), null);
        leftAdapter.setCallBack(new MakeGoodLeftAdapter.ClickCallBack() {
            @Override
            public void onClickItem(View v, BPA_GOODSTYPE type) {
                goodsTypeId = type.id;
                Initdata_sx();
            }
        });
        recyclerView.setAdapter(leftAdapter);
        if(leftData.isEmpty()){
            llContent.setVisibility(View.GONE);
            textTip.setVisibility(View.VISIBLE);
        }else {
            llContent.setVisibility(View.VISIBLE);
            textTip.setVisibility(View.GONE);
            goodsTypeId = ((BPA_GOODSTYPE) leftData.get(0).type).id;
            Initdata_sx();
        }
    }

    /**
     * 初始化数据加载
     */
    public void Initdata_sx() {
        bpa_goodproperties = QueryDB.GetGoodsPropertyByTypeId(goodsTypeId);
        AttributeSetAdapter adapter = new AttributeSetAdapter(context,  bpa_goodproperties, bpa_goodstypes,listener);
        datatab_sx.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @OnClick({R.id.add_sx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_sx://增加属性
                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) {
                                KeyboardUtil.hideKeyboard(builder_add.getEditText());
                                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.GetGoodsPropertyIs(text.toString())) {
                                        ToastUtils.info("属性名称重复,请重新输入后重试!");
                                        return;
                                    }
                                    BPA_GOODPROPERTY bpa_goodproperty = new BPA_GOODPROPERTY();
                                    bpa_goodproperty.name = text.toString();
                                    bpa_goodproperty.foreignKeyRe = "";
                                    bpa_goodproperty.parentid = "0";
                                    bpa_goodproperty.sort=0;
                                    bpa_goodproperty.GoodsTypeId=goodsTypeId;
                                    bpa_goodproperty.deviceID = ConfigName.getInstance().DeviceId;
                                    bpa_goodproperty.userID = ConfigName.getInstance().user.userID;
                                    QueryDB.AddGoodsProperty(bpa_goodproperty);
                                    ToastUtils.info("新增成功");
//                                    Initdata_sx(bpa_goodproperties.size());
                                    bpa_goodproperties.add(bpa_goodproperty);
                                    datatab_sx.getAdapter().notifyItemChanged(bpa_goodproperties.size()-1);
                                    datatab_sx.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            datatab_sx.scrollToPosition(bpa_goodproperties.size()-1);
                                        }
                                    },100);
                                    KeyboardUtil.hideKeyboard(builder_add.getEditText());
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("属性名称不能为空！");
                                }
                            }
                        })
                        .show();
                break;
        }
    }

    private MyClickListener listener = new MyClickListener() {
        @Override
        public void clickListener(View v, Object data) {

        }

        @Override
        public void clickListenerNew(View v, int k, Object data) {
            switch (v.getId()) {
                case R.id.name://修改属性名称按钮
                    final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(context);
                    builder.setTitle("属性名称")
                            .setPlaceholder("在此输入属性名称")
                            .setDefaultText(((BPA_GOODPROPERTY) data).name)
                            .setInputType(InputType.TYPE_CLASS_TEXT)
                            .addAction("取消", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    KeyboardUtil.hideKeyboard(builder.getEditText());
                                    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.GetGoodsPropertyIs(text.toString())) {
                                            ToastUtils.info("属性名称重复,请重新输入后重试!");
                                            return;
                                        }
                                        QueryDB.UpdateGoodsPropertyName(((BPA_GOODPROPERTY) data).id, text.toString());
//                                        Initdata_sx(k);
                                        BPA_GOODPROPERTY bean = (BPA_GOODPROPERTY) data;
                                        bean.name = text.toString();
                                        bpa_goodproperties.set(k,bean);
                                        datatab_sx.getAdapter().notifyItemChanged(k);
                                        KeyboardUtil.hideKeyboard(builder.getEditText());
                                        dialog.dismiss();
                                    } else {
                                        //请填入昵称
                                        ToastUtils.info("属性名称不能为空！");
                                    }
                                }
                            })
                            .show();
                    break;
                case R.id.sort:
                    final QMUIDialog.EditTextDialogBuilder builder1 = new QMUIDialog.EditTextDialogBuilder(context);
                    builder1.setTitle("排序")
                            .setPlaceholder("在此输入排序")
                            .setDefaultText(((BPA_GOODPROPERTY) data).sort+"")
                            .setInputType(InputType.TYPE_CLASS_NUMBER)
                            .addAction("取消", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    KeyboardUtil.hideKeyboard(v);
                                    dialog.dismiss();
                                }
                            })
                            .addAction("确定", new QMUIDialogAction.ActionListener() {
                                @Override
                                public void onClick(QMUIDialog dialog, int index) {
                                    CharSequence text = builder1.getEditText().getText();
                                    if (text != null && text.length() > 0) {
                                        QueryDB.UpdateGoodsPropertySort(((BPA_GOODPROPERTY) data).id, Integer.parseInt(text.toString()));
                                        BPA_GOODPROPERTY bean = (BPA_GOODPROPERTY) data;
                                        bean.sort = Integer.parseInt(text.toString());
//                                        Initdata_sx(k);
                                        bpa_goodproperties.set(k,bean);
                                        datatab_sx.getAdapter().notifyItemChanged(k);
                                        KeyboardUtil.hideKeyboard(v);
                                        dialog.dismiss();
                                    } else {
                                        //请填入昵称
                                        ToastUtils.info("排序不能为空！");
                                    }
                                }
                            })
                            .show();
                    break;
                case R.id.button_item://删除按钮
                    String title = "温馨提示！";
                    String message = "客官确定要删除属性【"+((BPA_GOODPROPERTY) data).name+"】吗？";
                    AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            ArrayList<BPA_GOODPROPERTY> ddd=QueryDB.GetGoodsPropertyALL(((BPA_GOODPROPERTY) data).id);
                            for (BPA_GOODPROPERTY item:ddd)
                            {
                                for(BPA_GOODSRECIPENAME goodsrecipename : QueryDB.GetGoodsSrecipeNameALL()){
                                    if(goodsrecipename.name.contains(item.name)){
                                        ToastUtils.info("已有配方正在使用该属性，请先删除配方【"+goodsrecipename.name+"】再删除该属性");
                                        return;
                                    }
                                }
                                QueryDB.DeleteGoodsProperty(item);
                            }
                            QueryDB.DeleteGoodsProperty((BPA_GOODPROPERTY) data);
//                            Initdata_sx(k);
                            bpa_goodproperties.remove(k);
                            datatab_sx.getAdapter().notifyDataSetChanged();
                            datatab_sx.scrollToPosition(k-1);
                            ToastUtils.info("删除成功");
                            KeyboardUtil.hideKeyboard(v);
                            dialog.dismiss();
                        }
                    });

                    break;
                case R.id.button_add://增加子属性
                    BPA_GOODPROPERTY sx=(BPA_GOODPROPERTY) data;
                    BPA_GOODPROPERTY bpa_goodproperty = new BPA_GOODPROPERTY();
                    bpa_goodproperty.name = "子属性示例";
                    bpa_goodproperty.foreignKeyRe = "";
                    bpa_goodproperty.parentid = sx.id;
                    bpa_goodproperty.sort=0;
                    bpa_goodproperty.deviceID = ConfigName.getInstance().DeviceId;
                    bpa_goodproperty.userID = ConfigName.getInstance().user.userID;
                    QueryDB.AddGoodsProperty(bpa_goodproperty);
                    ToastUtils.info("新增成功");
                    datatab_sx.getAdapter().notifyItemChanged(k);
                    KeyboardUtil.hideKeyboard(v);
                    break;

                case R.id.save_text://保存属性
                    QueryDB.UpdateGoodsProperty((BPA_GOODPROPERTY) data);
                    ToastUtils.info("保存成功");
                    datatab_sx.getAdapter().notifyItemChanged(k);
                    KeyboardUtil.hideKeyboard(v);
                    break;
                case R.id.delete_text://删除
                    String title1 = "温馨提示！";
                    String message1 = "客官确定要删除属性【"+((BPA_GOODPROPERTY) data).name+"】吗？";
                    AlertDialogUtils.showDialog(context, title1, message1, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            for(BPA_GOODSRECIPENAME goodsrecipename : QueryDB.GetGoodsSrecipeNameALL()){
                                if(goodsrecipename.name.contains(((BPA_GOODPROPERTY) data).name)){
                                    ToastUtils.info("已有配方正在使用该属性，请先删除配方【"+goodsrecipename.name+"】再删除该属性");
                                    return;
                                }
                            }
                            QueryDB.DeleteGoodsProperty((BPA_GOODPROPERTY) data);
                            datatab_sx.getAdapter().notifyItemChanged(k);
                            ToastUtils.info("删除成功");
                            KeyboardUtil.hideKeyboard(v);
                            dialog.dismiss();
                        }
                    });
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("我的fragment销毁");
        bpa_goodproperties.clear();
        bpa_goodproperties = null;
        bpa_goodstypes.clear();
        bpa_goodstypes = null;
        itemstypes.clear();
        itemstypes = null;
        listener = null;
        datatab_sx.setAdapter(null);
        context = null;
    }

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