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

import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.ColumnInfo;
import com.bin.david.form.listener.OnColumnClickListener;
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.constant.MessageName;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_MATERIAL;
import com.bonait.bnframework.common.db.mode.BPA_PROCESS;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
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.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.lc_adapter;
import com.bonait.bnframework.modules.home.adapter.lcsz_adapter;
import com.bonait.bnframework.modules.home.adapter.process_adapter;
import com.bonait.bnframework.modules.home.adapter.wl_adapter;
import com.bonait.bnframework.modules.home.fragment.from.CpActivity;
import com.bonait.bnframework.modules.home.fragment.from.DiyActivity;
import com.bonait.bnframework.modules.home.fragment.from.SzActivity;
import com.bonait.bnframework.modules.home.fragment.from.WhActivity;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUITopBar;
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 SystemSeasoningsetFragment extends BaseFragment implements MyClickListener {
    @BindView(R.id.edittext)
    EditText edittext;
    @BindView(R.id.wllx)
    Spinner wllx;
    @BindView(R.id.add_wl)
    Button add_wl;
    @BindView(R.id.datatab_wl)
    ListView datatab_wl;
    Map<String,Integer> wllx_map = new LinkedHashMap<>();
    /**
     * 物料数据
     */
    ArrayList<BPA_MATERIAL> bpa_materials=new ArrayList<>();

    @BindView(R.id.datatab_lc)
    ListView datatab_lc;//料仓
    ArrayList<lcMode> lcModes=new ArrayList<>();

    @BindView(R.id.datatab_gxmx)
    ListView datatab_gxmx;//工序
    ArrayList<BPA_PROCESS> processes=new ArrayList<>();

    private Context context;
    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_system_seasoningset, 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() {
        wllx_map.put("液料",0);
        wllx_map.put("酱料",1);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(context, R.layout.spinner_text_item, new ArrayList<>(wllx_map.keySet()));
        adapter2.setDropDownViewResource(R.layout.spinner_dropdown_item);
        wllx.setAdapter(adapter2);
        Initdata_wl();
        Initdata_lc();
        Initdata_gx();
    }

    @OnClick({R.id.add_wl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_wl://增加物料
                String name= edittext.getText().toString();
                String lx=wllx.getSelectedItem().toString();
                if(name.isEmpty()){
                    ToastUtils.info("物料名称不能为空");
                    return;
                }
                if(lx.isEmpty()){
                    ToastUtils.info("物料类型不能为空");
                    return;
                }
                if(QueryDB.GetMaterialIs(name)){
                    ToastUtils.info("物料名称重复,请重新输入后重试!");
                    return;
                }
                BPA_MATERIAL bpa_material=new BPA_MATERIAL();
                bpa_material.name=name;
                bpa_material.imgUrl="";
                bpa_material.type=wllx_map.get(lx);
                bpa_material.deviceID= ConfigName.getInstance().DeviceId;
                bpa_material.userID=ConfigName.getInstance().user.userID;
                QueryDB.AddMaterial(bpa_material);
                ToastUtils.info("新增成功");
                Initdata_wl();
                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){

        }
    }

    /**
     * 初始化数据加载
     */
    public void Initdata_lc()
    {
        try{
            lcModes=DataBus.getInstance().ResGetLc();
            lcsz_adapter adapter1 = new lcsz_adapter(context, R.layout.lcsz_item,lcModes,this);
            datatab_lc.setAdapter(adapter1);
        }catch(Exception e){

        }
    }

    /**
     * 初始化数据加载
     */
    public void Initdata_gx()
    {
        try{
            processes= QueryDB.GetProcessALL();
            process_adapter adapter1 = new process_adapter(context, R.layout.process_item,processes,this);
            datatab_gxmx.setAdapter(adapter1);
        }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左滑返回上一界面。
     *
     * 切记！切记！切记！否则会闪退！
     *
     * 当在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://修改物料名称按钮
                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();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("物料名称不能为空！");
                                }
                            }
                        })
                        .show();
                break;
            case R.id.lx://选择类型
                final  String [] items=new  String[]{"液料","酱料"};
                final int checkIndex=((BPA_MATERIAL)data).type;
                new QMUIDialog.CheckableDialogBuilder(context)
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                QueryDB.UpdateMaterialType(((BPA_MATERIAL)data).id,which);
                                Initdata_wl();
                                dialog.dismiss();
                            }
                        })
                        .setCheckedIndex(checkIndex)
                        .show();
                break;
            case R.id.button_item://删除按钮
                QueryDB.DeleteMaterial((BPA_MATERIAL)data);
                Initdata_wl();
                break;
        }
    }

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

        lcMode lc= (lcMode)data;
        switch (v.getId())
        {
            case R.id.name://修改物料
                List<String> names=new ArrayList<>();
                int index=0;
                int count=0;
                ArrayList<BPA_MATERIAL> materials=new ArrayList<>();
                for (BPA_MATERIAL item: bpa_materials)
                {
                    materials.add(item);
                }
                BPA_MATERIAL wsz = new BPA_MATERIAL();
                wsz.name = "未设置";
                wsz.id = "";
                materials.add(wsz);
                for (BPA_MATERIAL item: materials)
                {
                    names.add(item.name);
                    if(item.name.equals(lc.materialName))
                    {
                        index=count;
                    }
                    count++;
                }
                String[] items =  names.toArray(new String[names.size()]);
                final int checkIndex=index;
                new QMUIDialog.CheckableDialogBuilder(context)
                        .addItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                BPA_SILOSANDMATERIAL item = new BPA_SILOSANDMATERIAL();
                                BPA_MATERIAL material = materials.get(which);
                                item.silosID = lc.id;
                                item.materialID = material.id;
                                //更新
                                if (QueryDB.UpdateSilosAndMaterial(item)) {
                                    Initdata_lc();
                                    dialog.dismiss();
                                }
                            }
                        })
                        .setCheckedIndex(checkIndex)
                        .show();
                break;
            case R.id.bjz://修改料仓报警值
                final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(context);
                builder.setTitle(lc.materialName+" 报警值(g)")
                        .setPlaceholder("在此输入报警值")
                        .setDefaultText(lc.warningValue+"")
                        .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 = builder.getEditText().getText();
                                if (text != null && text.length() > 0) {
                                    QueryDB.UpdateSilosBJZ(lc.id,Integer.parseInt(text.toString()));
                                    Initdata_lc();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("值不能为空！");
                                }
                            }
                        })
                        .show();
                break;
            case R.id.zlz://修改料仓总量值
                final QMUIDialog.EditTextDialogBuilder builder1 = new QMUIDialog.EditTextDialogBuilder(context);
                builder1.setTitle(lc.materialName+" 总量值(g)")
                        .setPlaceholder("在此输入总量值")
                        .setDefaultText(lc.siloszl+"")
                        .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.UpdateSilosZL(lc.id,Integer.parseInt(text.toString()));
                                    Initdata_lc();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("值不能为空！");
                                }
                            }
                        })
                        .show();
                break;
        }
    }
}