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.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.HBL.Dialog.AlertDialogButton;
import com.bonait.bnframework.HBL.Dialog.DialogManager;
import com.bonait.bnframework.HBL.Dialog.WaitDialog;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.HttpModel.APIService;
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.event.SynchronousCloudDataEvent;
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.GoodsAPositionBean;
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.GoodEditDialog;
import com.bonait.bnframework.databinding.ActivityGoodpeifangBinding;
import com.bonait.bnframework.modules.home.fragment.GongnengFragment;
import com.bonait.bnframework.modules.home.fragment.mode.AddGoodDialog;
import com.bonait.bnframework.modules.home.fragment.mode.GoodsEditView;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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 {

    private ActivityGoodpeifangBinding viewBinding;
    /**
     * 顶部标题
     */
    @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;

    private AddGoodDialog addGoodDialog;

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

    private Context context;

    private GoodPeiFangActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivityGoodpeifangBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        activity = this;
        context = getContext();
        initView();
        Initdata();
    }

    private int typePos = 0;
    private void initView() {
        viewBinding.btnSync.setOnClickListener(v->{
            DialogManager.showWarn(this,"同步云端商品会参数本地所有配方数据，\r\n请问是否继续？", AlertDialogButton.YesNo,(s)->{
                if(s){
                    WaitDialog.getInstance().Show("同步数据","请耐心等待，不要关闭应用",this,this);
                    ThreadManager.get().execute(new Runnable() {
                        @Override
                        public void run() {
                            APIService.MainInit();
                            EventBus.getDefault().post(new SynchronousCloudDataEvent());
                        }
                    });
                }
            });
        });
        mTopBar.setTitle("商品配方管理");
        mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        viewBinding.goodEditView.setChangeCallBack(new GoodsEditView.ChangeCallBack() {
            @Override
            public void onChangeGood() {
                BPA_GOODSTYPE bpaGoodstype = goodstypes.get(typePos);
                ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(bpaGoodstype.id);
                Fdata.set(typePos,new LinkMode(bpaGoodstype, Arrays.asList(goodsm.toArray()), false));
                rightAdapter.notifyItemChanged(typePos);
                ToastUtils.info("修改成功");
            }
        });

        MessageManager.getInstance().registerMessageReceiver(this, MessageName.UpdateGood, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    GoodsAPositionBean bean = (GoodsAPositionBean) msg;
                    typePos = bean.position;
                    viewBinding.goodEditView.setData(bean.goods,activity);
                    viewBinding.goodEditView.setVisibility(View.VISIBLE);
                }
            }
        });

        MessageManager.getInstance().registerMessageReceiver(this, MessageName.DeleteGood1, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    GoodsAPositionBean xx = (GoodsAPositionBean) msg;
                    rv_right.post(new Runnable() {
                        @Override
                        public void run() {
                            AlertDialogUtils.showDialog(rv_right.getContext(),
                                    "删除提示！",
                                    "客官确定要删除商品,[" + xx.goods.name + "]吗？",
                                    new QMUIDialogAction.ActionListener() {
                                        @Override
                                        public void onClick(QMUIDialog dialog, int index) {
                                            ArrayList<BPA_GOODSRECIPENAME>  name=QueryDB.GetGoodsRecipeNameGoodId(xx.goods.id);
                                            for (BPA_GOODSRECIPENAME item:name)
                                            {
                                                ArrayList<ResGoodsRecipe> re= QueryDB.GetGoodsSreciperecipeList(item.id);
                                                for(ResGoodsRecipe item1:re)
                                                {
                                                    QueryDB.DeleteGoodsSrecipe(item1);
                                                }
                                                QueryDB.DeleteGoodsRecipeName(item);
                                            }
//                    Fdata.clear();
                                            QueryDB.DeleteGoods(xx.goods);
//                    Initdata();
                                            BPA_GOODSTYPE bpaGoodstype = goodstypes.get(xx.position);
                                            ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(bpaGoodstype.id);
                                            Fdata.set(xx.position,new LinkMode(bpaGoodstype, Arrays.asList(goodsm.toArray()), false));
                                            rightAdapter.notifyItemChanged(xx.position);
                                            ToastUtils.info("删除成功!!!");
                                            dialog.dismiss();
                                        }
                                    });
                        }
                    });

                }
            }
        });

        //打开
        MessageManager.getInstance().registerMessageReceiver(this, MessageName.ClickGoodNew, new MessageLooper.OnMessageListener() {
            @Override
            public void onMessage(Object msg) {
                if (msg != null) {
                    GoodsAPositionBean bean = (GoodsAPositionBean) msg;
                    typePos = bean.position;
                    viewBinding.goodEditView.setData(bean.goods,activity);
                    viewBinding.goodEditView.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) {
                    BPA_GOODSTYPE bpaGoodstype = goodstypes.get(typePos);
                    ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(bpaGoodstype.id);
                    Fdata.set(typePos,new LinkMode(bpaGoodstype, Arrays.asList(goodsm.toArray()), false));
                    rightAdapter.notifyItemChanged(typePos);
                    ToastUtils.info("执行成功!!!");
                    add_good.setVisibility(View.GONE);
                } else if (k == 2) { //保存并新建配方
                    BPA_GOODSTYPE bpaGoodstype = goodstypes.get(typePos);
                    ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(bpaGoodstype.id);
                    Fdata.set(typePos,new LinkMode(bpaGoodstype, Arrays.asList(goodsm.toArray()), false));
                    rightAdapter.notifyItemChanged(typePos);
                    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("保存成功!!!");
                }
            }
        };*/
    }

    public List<LinkMode> Fdata = new ArrayList<>();
    private GoodLeftAdapter leftAdapter;
    private GoodRightAdapter rightAdapter;

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

        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();
        leftAdapter = new GoodLeftAdapter(R.layout.item_left_good, Fdata, getResources(), manager, new GoodLeftAdapter.CallBack() {
            @Override
            public void delete(int index) {
                Initdata();
            }
        });
        rightAdapter = new GoodRightAdapter(getContext(), Fdata);
        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://增加商品
                if(isFastClick()){
                    ToastUtils.info("请勿快速点击！");
                    return;
                }
                if(goodstypes.isEmpty()){
                    ToastUtils.info("请先创建至少一个分类");
                    return;
                }
                if(addGoodDialog == null){
                    addGoodDialog = new AddGoodDialog();
                }
                addGoodDialog.setSaveCallBack(new AddGoodDialog.SaveCallBack() {
                    @Override
                    public void onSave(String typeId) {
                        int pos = -1;
                        for(int i =0;i<Fdata.size();i++){
                            if(((BPA_GOODSTYPE)Fdata.get(i).type).id.equals(typeId)){
                                pos = i;
                            }
                        }
                        if(pos>=0){
                            BPA_GOODSTYPE bpaGoodstype = goodstypes.get(pos);
                            ArrayList<BPA_GOODS> goodsm = QueryDB.GetGoodsTypeId(bpaGoodstype.id);
                            Fdata.set(pos,new LinkMode(bpaGoodstype, Arrays.asList(goodsm.toArray()), false));
                            int lastPos = typePos;
                            typePos =  pos;
                            leftAdapter.setChoose(typePos);
                            rightAdapter.notifyItemChanged(lastPos);
                            rightAdapter.notifyItemChanged(typePos);
                            ((LinearLayoutManager) rv_right.getLayoutManager()).scrollToPositionWithOffset(typePos, 0);
                            ToastUtils.info("添加成功");
                        }else {
                            ToastUtils.info("刷新失败，请退出重进");
                        }

                    }
                });
                addGoodDialog.show(getSupportFragmentManager(),"添加商品名称");
                break;
        }
    }

    /**
     * 判断重复点击
     */
    private long lastTime;

    public boolean isFastClick(){
        long curTime = System.currentTimeMillis();
        if(curTime - lastTime < 1000){
            return true;
        }
        lastTime = curTime;
        return false;
    }

    @Override
    public void onDestroy() {
        viewBinding.goodEditView.destroy();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        goodstypes.clear();
        goodstypes = null;
        rv_right.setAdapter(null);
        rv_left.setAdapter(null);
        Glide.get(this).clearMemory();
        MessageManager.getInstance().unRegisterMessageReceiver(this);
        context = null;
        activity = null;
    }

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

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSynchronousCloudDataEvent(SynchronousCloudDataEvent event) {
        WaitDialog.getInstance().Dismiss();
        ToastUtils.info("同步完成");
        Initdata();
    }
}