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

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

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.ListView;

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_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.sx_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.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)
    ListView datatab_sx;
    /**
     * 属性数据
     */
    ArrayList<BPA_GOODPROPERTY> bpa_goodproperties = new ArrayList<>();

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

    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() {
        bpa_goodstypes= QueryDB.GetGoodsTypeALL();
        itemstypes.clear();
        for (BPA_GOODSTYPE item:bpa_goodstypes)
        {
            if(!itemstypes.containsKey(item.name))
            {
                itemstypes.put(item.name,item.id);
            }
        }

        Initdata_sx();
    }

    @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) {
                                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.deviceID = ConfigName.getInstance().DeviceId;
                                    bpa_goodproperty.userID = ConfigName.getInstance().user.userID;
                                    QueryDB.AddGoodsProperty(bpa_goodproperty);
                                    ToastUtils.info("新增成功");
                                    Initdata_sx();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("属性名称不能为空！");
                                }
                            }
                        })
                        .show();
                break;
        }
    }

    /**
     * 点击事件
     *
     * @param v
     * @param data
     */
    @Override
    public void clickListener(View v, 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) {
                                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();
                                    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) {
                                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()));
                                    Initdata_sx();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("排序不能为空！");
                                }
                            }
                        })
                        .show();
                break;
            case R.id.typeS:
                ArrayList<Integer> keys=new ArrayList<Integer>();
                String[] items = itemstypes.keySet().toArray(new String[itemstypes.keySet().size()]);



                if(((BPA_GOODPROPERTY) data).GoodsTypeId!=null && !((BPA_GOODPROPERTY) data).GoodsTypeId.isEmpty())
                {
                    for (int i=0;i<items.length;i++)
                    {
                        if(((BPA_GOODPROPERTY) data).GoodsTypeId.contains(itemstypes.get(items[i])))
                        {
                            keys.add(i);
                        }
                    }
                }
                int []intarrs=new int[keys.size()];
                for(int i=0;i<intarrs.length;i++){
                    intarrs[i]=keys.get(i);
                }

                final QMUIDialog.MultiCheckableDialogBuilder builder3 = new QMUIDialog.MultiCheckableDialogBuilder(context)
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setCheckedItems(intarrs);
                builder3.addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                });
                builder3.addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        String result="";
                        for(int i=0;i<builder3.getCheckedItemIndexes().length;i++){
                            result+=""+itemstypes.get(items[builder3.getCheckedItemIndexes()[i]])+",";
                        }

                        if(result.isEmpty())
                        {
                            ToastUtils.info("必须选择一个类型!");
                            return;
                        }

                        if(!result.isEmpty())
                        {
                            result=result.substring(0, result.length() - 1);
                        }
                        QueryDB.UpdateGoodsPropertyType(((BPA_GOODPROPERTY) data).id, result);
                        Initdata_sx();

                        dialog.dismiss();
                    }
                });
                builder3.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)
                        {
                            QueryDB.DeleteGoodsProperty(item);
                        }
                        QueryDB.DeleteGoodsProperty((BPA_GOODPROPERTY) data);
                        Initdata_sx();
                        ToastUtils.info("删除成功");
                        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("新增成功");
                Initdata_sx();
                break;

            case R.id.save_text://保存属性
                QueryDB.UpdateGoodsProperty((BPA_GOODPROPERTY) data);
                ToastUtils.info("保存成功");
                Initdata_sx();
                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) {
                        QueryDB.DeleteGoodsProperty((BPA_GOODPROPERTY) data);
                        Initdata_sx();
                        ToastUtils.info("删除成功");
                        dialog.dismiss();
                    }
                });
                break;
        }
    }

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

    }
    //region 数据加载
    /**
     * 初始化数据加载
     */
    public void Initdata_sx() {
        try {

            bpa_goodproperties = QueryDB.GetGoodsPropertyALL("0");
            sx_adapter adapter = new sx_adapter(context, R.layout.sx_item, bpa_goodproperties, bpa_goodstypes,this);
            datatab_sx.setAdapter(adapter);
        } catch (Exception e) {

        }
    }
    //endregion

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("我的fragment销毁");
    }

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