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 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.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
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.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.DishDetailBean;
import com.gingersoft.supply_chain.mvp.bean.DishDetailResultBean;
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.DishesTreeAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.food.OtherFunctionFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.ChooseUnitPopup;
import com.jess.arms.di.component.AppComponent;
import com.lxj.xpopup.XPopup;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

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;
    @BindView(R2.id.dish_refreshLayout)
    SmartRefreshLayout refresh;

    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));
        refresh.setOnRefreshListener(refreshLayout -> {
            if (curSelectDishNode != null) {
                mPresenter.getDishesDetailData(curSelectDishNode);
            }
        });
        refresh.setEnableLoadMore(false);

        mPresenter.getDishGroupData();
    }
    private void initDishDetail(DishDetailResultBean dishesResultBean){
        List<DishDetailBean> foods=dishesResultBean.getData();
        if (dishDetailAdapter == null) {
            dishDetailAdapter = new DishDetailAdapter(new ArrayList<>());
            dishDetailAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (curSelectDishNode != null) {
                    DishDetailBean detailBean=dishDetailAdapter.getItem(position);
                    int id = view.getId();
                    if (id == R.id.tv_dishes_del) {
                        AppDialog.getInstance().showWaringDialog(mContext, "確定移除食材?", () ->{
                            if (detailBean.getId() == null) {//刚加 为提交直接删
                                dishDetailAdapter.removeAt(position);
                            }else {
                                detailBean.setDeletes(true);
                                dishDetailAdapter.addDel(detailBean);
                                dishDetailAdapter.removeAt(position);
                            }
                        });
                    } else if (id == R.id.tv_dishes_unit) {
                        List<DeputyUnitBean> foodUnits= detailBean.getFoodUnits();
                        if (CollectionUtils.isNotNullOrEmpty(foodUnits)) {
                            List<String> units = new ArrayList<>();
                            for (int i = 0; i < foodUnits.size(); i++) {
                                String name=foodUnits.get(i).getDeputyUnit();
                                units.add(name);
                            }
                            if (units.size() > 0) {
                                ChooseUnitPopup popup = new ChooseUnitPopup(requireContext()).setStringData(units).setOnSelectListener((pos, text) -> {
                                    //將用戶之前輸入的值，修改到新選擇的單位匯中
                                    String mainUnit= detailBean.getFoodBasicUnit();
                                    DeputyUnitBean deputyUnitBean = foodUnits.get(pos);
                                    String selectUnitName=deputyUnitBean.getDeputyUnit();
                                    if (!mainUnit.equals(selectUnitName)) {//选中的不是主单位那么需要切换倍率
                                        detailBean.setBasicUnitName(selectUnitName);
                                        detailBean.setConversionMultiple(deputyUnitBean.getConversionMultiple());
                                        dishDetailAdapter.notifyItemChanged(position);
                                    }else {
                                        detailBean.setBasicUnitName(mainUnit);
                                        detailBean.setConversionMultiple(1.0);
                                        dishDetailAdapter.notifyItemChanged(position);
                                    }

                                });
                                new XPopup.Builder(getContext())
                                        .hasShadowBg(false)
                                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                                        .asCustom(popup)
                                        .show();
                            }
                        }
                    }
                }
            });
            rvDishes.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
            dishDetailAdapter.addFooterView(getFooterView(CollectionUtils.isNotNullOrEmpty(foods)));
            rvDishes.setAdapter(dishDetailAdapter);
        }
        if (CollectionUtils.isNotNullOrEmpty(foods)) {
            dishDetailAdapter.setList(foods);
        }else {
            dishDetailAdapter.setList(new ArrayList<>());
        }
        int size=dishDetailAdapter.getData().size();
        dishDetailAdapter.clearDel();
        getFooterView(size>0);
    }

    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> allBeans=dishDetailAdapter.getDels();
                    List<DishDetailBean> detailBeans=  dishDetailAdapter.getData();
                    if (CollectionUtils.isNotNullOrEmpty(detailBeans)) {
                        allBeans.addAll(detailBeans);
                    }
                    if (CollectionUtils.isNotNullOrEmpty(allBeans)) {
                        mPresenter.bindDishFoods(curSelectDishNode ,allBeans);
                    }
                }
            });
        }
        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.i("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();
                        if (detailBean == null) {
                            mPresenter.getDishesDetailData(curDishNode);
                        } else {
                            loadDishesInfo(curDishNode, detailBean);
                        }

                    }
            }

            }

        });
        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) {
        refresh.finishRefresh();
        curSelectDishNode=dishNode;
        initDishDetail(dishesDetail);
    }

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

    @Override
    public void loadDishesFail() {
        refresh.finishRefresh();
    }

    @Override
    public void bindDishFoods(DishNode dishNode) {
       dishDetailAdapter.clearDel();
       mPresenter.getDishesDetailData(dishNode);
    }

    @Override
    public void selectDishGroupByIndex(int position) {

    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        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();
                        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.i("zjs"," oldBean="+oldBean.toString()+" newBean="+newBean.toString());
                                    if (newBean.getId()==oldBean.getPurchaseFoodId()) {//选择了同一个食材
                                        oldBean.setFoodNumber(oldBean.getFoodNumber()+newBean.getFoodQuantity());
                                        isNew=false;
                                        dishDetailAdapter.removeDel(oldBean);
                                        dishDetailAdapter.notifyItemChanged(j);
                                        continue;
                                    }
                                }
                                if (isNew) {
                                    DishDetailBean addNewBean=new DishDetailBean(newBean,curSelectDishNode);
                                    foodsNew.add(addNewBean);
                                }
                            }
                        }else { //全新 conversionMultiple 一定是1
                            for (int i = 0; i < len; i++) {
                                PurchaseFoodBean newBean= purchaseFood.get(i);
//                                LogUtil.i("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);
                    }
                }
            }
        }
    }
}