package com.gingersoft.supply_chain.mvp.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.LinearLayout;

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

import com.chad.library.adapter.base.entity.node.BaseNode;
import com.gingersoft.gsa.cloud.common.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerDishesComponent;
import com.gingersoft.supply_chain.mvp.bean.BuyIngredientsBean;
import com.gingersoft.supply_chain.mvp.bean.DishDetailBean;
import com.gingersoft.supply_chain.mvp.bean.DishDetailResultBean;
import com.gingersoft.supply_chain.mvp.bean.DishesResultBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.contract.DishesContract;
import com.gingersoft.supply_chain.mvp.presenter.DishesPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishDetailAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishNode;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishesGroupNode;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishesGroupProvider;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishesTreeAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.OtherFunctionFragment;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created on 2021/07/21 14:28
 *
 * @author zjs
 * module name is DishesFragment
 */
public class DishesFragment extends BaseSupplyChainFragment<DishesPresenter> implements DishesContract.View {


    @BindView(R2.id.topbar_food_ingredients)
    QMUITopBar topbarFoodIngredients;
    @BindView(R2.id.rv_dishes)
    RecyclerView rvDishesGroup;
    @BindView(R2.id.rv_dishes_food)
    RecyclerView rvDishes;
    private View footView;
    private DishesTreeAdapter dishesTreeAdapter;
    private DishDetailAdapter dishDetailAdapter;
    public static final int DISHES_ADD=123;
    private  DishNode curSelectDishNode;


    public static DishesFragment newInstance() {
        DishesFragment fragment = new DishesFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDishesComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dishes, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //setToolBarNoBack(toolbar, "Dishes");
        initTopBar(topbarFoodIngredients, getString(R.string.str_dishes));
        mPresenter.getDishGroupData();
    }
    private void initDishDetail(DishDetailResultBean dishesResultBean){
        List<DishDetailBean> foods=dishesResultBean.getData();
        View footer;
        if (CollectionUtils.isNullOrEmpty(foods)) {
            dishDetailAdapter=new DishDetailAdapter(requireContext(),new ArrayList<>());
            footer=getFooterView(false);
        }else {
            dishDetailAdapter=new DishDetailAdapter(requireContext(),foods);
            footer=getFooterView(true);
        }
       LinearLayout parent = dishDetailAdapter.getFooterLayout();
        if (parent==null) {
            dishDetailAdapter.removeAllFooterView();
            dishDetailAdapter.addFooterView(footer);
        }else {
            parent.removeAllViews();
            dishDetailAdapter.addFooterView(footer);
        }

        rvDishes.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        rvDishes.setAdapter(dishDetailAdapter);
    }

    private View getFooterView(boolean showDone) {
        if (footView == null) {
            footView = getLayoutInflater().inflate(R.layout.item_dishes_foot, rvDishes, false);
            footView.findViewById(R.id.tv_dish_add).setOnClickListener(v -> {
                startForResult(OtherFunctionFragment.newInstance(),DISHES_ADD);
            });
            footView.findViewById(R.id.tv_dish_done).setOnClickListener(v -> {
                if (curSelectDishNode != null) {
                    List<DishDetailBean> detailBeans=  dishDetailAdapter.getData();
                    if (CollectionUtils.isNotNullOrEmpty(detailBeans)) {
                        mPresenter.bindDishFoods(detailBeans);
                    }

                }
                LogUtil.e("zjs"," 完成 tv_dish_done");

            });
        }
        if (showDone) {
            footView.findViewById(R.id.tv_dish_done).setVisibility(View.VISIBLE);
        }else {
            footView.findViewById(R.id.tv_dish_done).setVisibility(View.GONE);
        }
        return footView;
    }



    private void initDishGroup(List<DishesGroupNode> dishesGroupNodes){
        dishesTreeAdapter = new DishesTreeAdapter(dishNode -> mPresenter.getDishesDetailData(dishNode));
        dishesTreeAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            BaseNode baseNode= dishesTreeAdapter.getItem(position);
            if (baseNode instanceof  DishNode) {
                DishNode curDishNode= (DishNode) baseNode;
                int ppos=  dishesTreeAdapter.findParentNode(position);
                DishesGroupNode pNode = (DishesGroupNode) dishesTreeAdapter.getItem(ppos);
                if (pNode != null) {
                    int lastPost = pNode.getPos()+ppos;
                    int myPostion=position-ppos;
                    boolean isCur=position ==lastPost;
                    LogUtil.e("ZJS"," lastPost="+lastPost+" myPostion="+myPostion+" isCur="+isCur );
                    if (!isCur) {//当前点击的不是上次点击的项目
                        DishNode lastDishNode= (DishNode) dishesTreeAdapter.getItem(lastPost);
                        lastDishNode.setSelect(false);
                        curDishNode.setSelect(true);
                        pNode.setPos(myPostion);
                        dishesTreeAdapter.notifyItemChanged(lastPost);
                        dishesTreeAdapter.notifyItemChanged(position);
                        DishDetailResultBean detailBean= curDishNode.getDetailBean();
                        LogUtil.e("ZJS"," detailBean="+(detailBean==null));
                        mPresenter.getDishesDetailData(curDishNode);
                    }
            }

                LogUtil.e("ZJS","  onItemChildClick position="+position+" 父节点="+ppos +"  getFoodName"+ curDishNode.getFoodName());
            }

        });
        dishesTreeAdapter.setList(dishesGroupNodes);
        rvDishesGroup.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        rvDishesGroup.setAdapter(dishesTreeAdapter);
    }

    @Override
    public void loadDishGroupInfo( List<DishesGroupNode>   dishGroup) {
        initDishGroup(dishGroup);
    }

    @Override
    public void loadDishesInfo(DishNode dishNode,DishDetailResultBean dishesDetail) {
        curSelectDishNode=dishNode;
        initDishDetail(dishesDetail);
    }

    @Override
    public void loadDishGroupFail() {
        killMyself();
    }

    @Override
    public void loadDishesFail() {

    }

    @Override
    public void loadFood(List<BuyIngredientsBean> buyIngredientsBeans) {

    }

    @Override
    public void selectDishGroupByIndex(int position) {

    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        LogUtil.e("zjs","  onFragmentResult ="+requestCode + "  resultCode="+resultCode);
        if (requestCode == DISHES_ADD) {
            if (data != null) {
                if (dishDetailAdapter != null && curSelectDishNode != null ) {
                    List<DishDetailBean> foodsOld = dishDetailAdapter.getData();
                    ArrayList<PurchaseFoodBean> purchaseFood = (ArrayList<PurchaseFoodBean>) data.getSerializable("zjs");
                    if (purchaseFood != null) {
                        List<DishDetailBean> foodsNew = new ArrayList<>();
                        int len=purchaseFood.size();
                        LogUtil.e("zjs", "  purchaseFood =" + purchaseFood.size()+" foodsOld="+foodsOld.size());
                        if (CollectionUtils.isNotNullOrEmpty(foodsOld)) {
                            int old=foodsOld.size();
                            boolean isNew=true;
                            for (int i = 0; i < len; i++) {
                                PurchaseFoodBean newBean= purchaseFood.get(i);
                                for (int j = 0; j < old; j++) {
                                    DishDetailBean oldBean=foodsOld.get(j);
                                    LogUtil.e("zjs"," oldBean="+oldBean.toString()+" newBean="+newBean.toString());
                                    if (newBean.getId()==oldBean.getPurchaseFoodId()) {
                                        oldBean.setConsumeQuantity(oldBean.getConsumeQuantity()+newBean.getFoodQuantity());
                                        isNew=false;
                                        dishDetailAdapter.notifyItemChanged(j);
                                        continue;
                                    }
                                }
                                if (isNew) {
                                    DishDetailBean addNewBean=new DishDetailBean(newBean,curSelectDishNode);
                                    foodsNew.add(addNewBean);
                                }

                            }
                        }else { //全新
                            for (int i = 0; i < len; i++) {
                                PurchaseFoodBean newBean= purchaseFood.get(i);
                                LogUtil.e("zjs","  全新  newBean="+newBean.toString());
                                DishDetailBean addNewBean=new DishDetailBean(newBean,curSelectDishNode);
                                foodsNew.add(addNewBean);
                            }
                        }
                        dishDetailAdapter.addData(foodsNew);
                        DishDetailResultBean detailResultBean=curSelectDishNode.getDetailBean();
                        if (detailResultBean == null) {
                            detailResultBean=new DishDetailResultBean();
                        }
                        detailResultBean.setData(dishDetailAdapter.getData());
                        curSelectDishNode.setDetailBean(detailResultBean);
                        getFooterView(true);
                    }
                }
            }
        }

    }
}