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

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.bonait.bnframework.R;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.base.BaseFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.MessageName;
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_GOODSRECIPE;
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.db.res.ResGoodProperty;
import com.bonait.bnframework.common.db.res.ResGoodsRecipe;
import com.bonait.bnframework.common.db.res.lcMode;
import com.bonait.bnframework.common.helper.I.IRunT;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.http.callback.json.JsonDialogCallback;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.linktab.LeftAdapter;
import com.bonait.bnframework.common.linktab.LinkMode;
import com.bonait.bnframework.common.linktab.RightAdapter;
import com.bonait.bnframework.common.linktab.TopItemDecoration;
import com.bonait.bnframework.common.linktab.good.GoodLeftAdapter;
import com.bonait.bnframework.common.linktab.good.GoodRightAdapter;
import com.bonait.bnframework.common.message.MessageLooper;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.model.ResAPI;
import com.bonait.bnframework.common.model.mode.ActionJsonMode;
import com.bonait.bnframework.common.model.mode.BatchingInfo;
import com.bonait.bnframework.common.model.mode.BomTechnologyActionInfo;
import com.bonait.bnframework.common.model.mode.CloudGood;
import com.bonait.bnframework.common.model.mode.GoodsTechnology;
import com.bonait.bnframework.common.model.mode.TechnologyAction;
import com.bonait.bnframework.common.model.mode.UpdateBomInfo;
import com.bonait.bnframework.common.model.mode.UpdateCloudGood;
import com.bonait.bnframework.common.oss.OssHelper;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.AddGoodDialog;
import com.bonait.bnframework.common.view.GoodEditDialog;
import com.bonait.bnframework.modules.home.fragment.GongnengFragment;
import com.bonait.bnframework.modules.home.fragment.mode.add_good_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_control;
import com.bonait.bnframework.modules.home.fragment.mode.add_pf_home_control;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
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.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class GoodPeiFangActivity extends BaseActivity {

    /**
     * 顶部标题
     */
    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;
    /**
     * 增加商品
     */
    @BindView(R.id.add_sp)
    Button add_sp;
    /**
     * 增加分类
     */
    @BindView(R.id.add_fl)
    Button add_fl;

    /**
     * 左边分类
     */
    @BindView(R.id.rv_left)
    RecyclerView rv_left;

    /**
     * 右边商品
     */
    @BindView(R.id.rv_right)
    RecyclerView rv_right;

    /**
     * 增加商品
     */
    @BindView(R.id.add_good)
    add_good_control add_good;

    /**
     * 增加配方选择页
     */
    @BindView(R.id.add_pf_home)
    add_pf_home_control add_pf_home;

    /**
     * 增加配方
     */
    @BindView(R.id.add_pf)
    add_pf_control add_pf;

    /**
     * 商品类型
     */
    ArrayList<BPA_GOODSTYPE> goodstypes = new ArrayList<>();

    private Context context;

    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodpeifang);

        ButterKnife.bind(this);
        activity = this;
        context = getContext();
        initTopBar();
        Initdata();
    }


    private void initTopBar() {
        mTopBar.setTitle("商品配方管理");
        mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        MessageManager.getInstance().registerMessageReceiver(this, MessageName.UpdateGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    BPA_GOODS xx = (BPA_GOODS) msg;
                    add_good.setData("保存", xx, goodstypes, activity);
                    add_good.setVisibility(View.VISIBLE);
                }
            }
        });

        MessageManager.getInstance().registerMessageReceiver(this, MessageName.DeleteGood1, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    BPA_GOODS xx = (BPA_GOODS) msg;

                    ArrayList<BPA_GOODSRECIPENAME>  name=QueryDB.GetGoodsRecipeNameGoodId(xx.id);
                    for (BPA_GOODSRECIPENAME item:name)
                    {
                        ArrayList<ResGoodsRecipe> re= QueryDB.GetGoodsSreciperecipeList(item.id);
                        for(ResGoodsRecipe item1:re)
                        {
                            QueryDB.DeleteGoodsSrecipe(item1);
                        }
                        QueryDB.DeleteGoodsRecipeName(item);
                    }
                    QueryDB.DeleteGoods(xx);
                    Initdata();
                    ToastUtils.info("删除成功!!!");
                }
            }
        });

        //打开
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.ClickGoodNew, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    BPA_GOODS goods = (BPA_GOODS) msg;

                    add_pf_home.SetData(goods, goodstypes);
                    add_pf_home.setVisibility(View.VISIBLE);
                }
            }
        });

        //增加商品
        add_good.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {
                if (k == 0) {
                    add_good.setVisibility(View.GONE);
                } else if (k == 1) {
                    Initdata();
                    ToastUtils.info("执行成功!!!");
                    add_good.setVisibility(View.GONE);
                } else if (k == 2) { //保存并新建配方
                    Initdata();
                    ToastUtils.info("执行成功!!!");
                    add_good.setVisibility(View.GONE);

                    //打开新建配方界面
                    BPA_GOODS good = (BPA_GOODS) data;
                    add_pf.setVisibility(View.VISIBLE);
                    add_pf.SetData(null, good, bpa_goodproperties);
                }
            }
        };

        add_pf_home.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {
                if (k == 0) {
                    add_pf_home.setVisibility(View.GONE);
                } else if (k == 1) {
                    //新建配方
                    add_pf_home.setVisibility(View.GONE);

                    //打开新建配方界面
                    BPA_GOODS good = (BPA_GOODS) data;
                    add_pf.setVisibility(View.VISIBLE);
                    add_pf.SetData(null, good, bpa_goodproperties);
                } else if (k == 2) {
                    //修改配方
                    add_pf_home.setVisibility(View.GONE);

                    BPA_GOODSRECIPENAME SelectDataName = add_pf_home.SelectData;
                    //打开新建配方界面
                    BPA_GOODS good = (BPA_GOODS) data;
                    add_pf.setVisibility(View.VISIBLE);
                    add_pf.SetData(SelectDataName, good, bpa_goodproperties);
                }
            }
        };

        add_pf.mListener = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {
            }

            @Override
            public void clickListenerNew(View v, int k, Object data) {
                if (k == 0) {
                    add_pf.setVisibility(View.GONE);
                } else if (k==1){
                    add_pf.setVisibility(View.GONE);
                    ToastUtils.info("保存成功!!!");
                }else
                {
                    ToastUtils.info("保存成功!!!");
                }
            }
        };
    }

    /**
     * 属性数据
     */
    ArrayList<ResGoodProperty> bpa_goodproperties = new ArrayList<>();
    public List<LinkMode> Fdata = new ArrayList<>();

    /**
     * 初始化数据
     */
    public void Initdata() {

        bpa_goodproperties.clear();
        ArrayList<BPA_GOODPROPERTY> da = QueryDB.GetGoodsPropertyALL("0");
        for (BPA_GOODPROPERTY item : da) {
            ResGoodProperty re = new ResGoodProperty();
            re.id = item.id;
            re.name = item.name;

            ArrayList<BPA_GOODPROPERTY> zsx = QueryDB.GetGoodsPropertyALL(item.id);
            re.child = new ArrayList<>();


            ArrayList<ResGoodProperty> _chid = new ArrayList<>();
            for (BPA_GOODPROPERTY k : zsx) {
                ResGoodProperty m = new ResGoodProperty();
                m.id = k.id;
                m.name = k.name;
                m.isSelect = false;
                _chid.add(m);
            }
            re.child = _chid;
            re.GoodsTypeId=item.GoodsTypeId;
            re.sort= item.sort;
            bpa_goodproperties.add(re);
        }


        //1.商品类型
        goodstypes = QueryDB.GetGoodsTypeALL();

        Fdata.clear();

        int i = 0;
        for (BPA_GOODSTYPE item : goodstypes) {
            ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(item.id);
            Fdata.add(new LinkMode(item, Arrays.asList(goodsm.toArray()), i == 0 ? true : false));
            i++;
        }

        LinearLayoutManager manager = (LinearLayoutManager) rv_right.getLayoutManager();
        GoodLeftAdapter leftAdapter = new GoodLeftAdapter(R.layout.item_left_good, Fdata, getResources(), manager);
        GoodRightAdapter rightAdapter = new GoodRightAdapter(R.layout.item_right_lc, Fdata, getResources());
        rv_left.setAdapter(leftAdapter);
        rv_right.setAdapter(rightAdapter);


        //添加分组悬浮效果
        List<String> typeListener = new ArrayList<>();
        for (LinkMode item : Fdata) {
            typeListener.add(((BPA_GOODSTYPE) item.type).name);
        }

        if (rv_right.getItemDecorationCount() > 0) {
            rv_right.removeItemDecorationAt(0);
        }
        TopItemDecoration top = new TopItemDecoration(context, typeListener);
        rv_right.addItemDecoration(top);

        //左侧联动
        rv_right.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstItemPosition = manager.findFirstVisibleItemPosition();
                if (firstItemPosition != -1 && dy != 0) {
                    rv_left.smoothScrollToPosition(firstItemPosition);
                    leftAdapter.setChoose(firstItemPosition);
                }
            }
        });
    }


    @OnClick({R.id.add_sp, R.id.add_fl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add_fl://增加分类
                //1.弹窗 增加分类
                final QMUIDialog.EditTextDialogBuilder builder_add = new QMUIDialog.EditTextDialogBuilder(this);
                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.GetGoodsTypeIs(text.toString())) {
                                        ToastUtils.info("数据重复,请重新输入后重试!");
                                        return;
                                    }
                                    BPA_GOODSTYPE bpa_goodstype = new BPA_GOODSTYPE();
                                    bpa_goodstype.name = text.toString();
                                    bpa_goodstype.deviceID = ConfigName.getInstance().DeviceId;
                                    bpa_goodstype.userID = ConfigName.getInstance().user.userID;
                                    QueryDB.AddGoodsType(bpa_goodstype);
                                    ToastUtils.info("新增成功");
                                    Initdata();
                                    dialog.dismiss();
                                } else {
                                    //请填入昵称
                                    ToastUtils.info("输入不能为空！");
                                }
                            }
                        })
                        .show();
                break;
            case R.id.add_sp://增加商品
                add_good.setData("保存", null, goodstypes, activity);
                add_good.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onDestroy() {
        add_pf.destroy();
        add_good.destroy();
        super.onDestroy();
        rv_right.setAdapter(null);
        Glide.get(this).clearMemory();
        MessageManager.getInstance().unRegisterMessageReceiver(this);
    }

    @Override
    protected boolean canDragBack() {
        return false;
    }
}