package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.bean.SectionCheckItem;
import com.gingersoft.supply_chain.mvp.bean.FoodCategoryResultBean;
import com.gingersoft.supply_chain.mvp.contract.CategorySelectContract;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.section.QMUISection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.gingersoft.gsa.cloud.ui.adapter.BaseRadioSectionAdapter.SEPARATOR;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/26/2020 14:39
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class CategorySelectPresenter extends BasePresenter<CategorySelectContract.Model, CategorySelectContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<FoodCategoryResultBean.DataBean.FoodCategoryBean> list;


    @Inject
    public CategorySelectPresenter(CategorySelectContract.Model model, CategorySelectContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void getFoodCategoryList(String name, int parentId, String position) {
        Map<String, Object> map = new HashMap<>(6);
        map.put("pageSize", 1000);
        map.put("pageIndex", 0);
        map.put("parentId", parentId);
        map.put("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId());
        map.put("brandId", RestaurantInfoManager.newInstance().getBrandId());
        if (!TextUtil.isEmptyOrNullOrUndefined(name)) {
            map.put("name", name);
        }
        mModel.getFoodCategoryList(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodCategoryResultBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull FoodCategoryResultBean info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                if (list == null) {
                                    list = new ArrayList<>();
                                }
                                if (info.getData().getCount() > 0) {
                                    if (list.size() > 0) {
                                        //list數量大於0時，最外一層已經獲取，這次獲取的是裡面某一層，然後通過遞歸返回的下標位置精確插入數據
                                        String[] split = position.split(SEPARATOR);
                                        getTheDeepest(list, split, 0).setList(info.getData().getList());
                                    } else {
                                        list.addAll(info.getData().getList());
                                    }

                                    List<QMUISection<SectionCheckItem, SectionCheckItem>> sections = new ArrayList<>();
                                    for (int i = 0; i < list.size(); i++) {
                                        if (list.get(i).getParentId() == 0) {
                                            SectionCheckItem sectionCheckItem = new SectionCheckItem(list.get(i).getId(), list.get(i).getName(), i);
                                            sections.add(new QMUISection<>(sectionCheckItem, genList(list.get(i).getList(), i), false));
                                        }
                                    }
                                    mRootView.loadFoodCategory(sections);
                                }
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            }
                        }
                    }

                    public FoodCategoryResultBean.DataBean.FoodCategoryBean getTheDeepest(List<FoodCategoryResultBean.DataBean.FoodCategoryBean> list, String[] split, int i) {
                        if (i + 1 < split.length) {
                            return getTheDeepest(list.get(Integer.parseInt(split[i])).getList(), split, i + 1);
                        } else {
                            return list.get(Integer.parseInt(split[i]));
                        }
                    }


                    public List<SectionCheckItem> genList(List<FoodCategoryResultBean.DataBean.FoodCategoryBean> list, int parentIndex) {
                        if (list != null && list.size() > 0) {
                            List<SectionCheckItem> sectionCheckItems = new ArrayList<>();
                            for (int i = 0; i < list.size(); i++) {
                                SectionCheckItem sectionCheckItem = new SectionCheckItem(list.get(i).getId(), list.get(i).getName(), parentIndex);
                                if (list.get(i).getList() != null && list.get(i).getList().size() > 0) {
                                    sectionCheckItem.setSectionCheckItems(genList(list.get(i).getList(), i));
                                }
                                sectionCheckItems.add(sectionCheckItem);
                            }
                            return sectionCheckItems;
                        } else {
                            return null;
                        }
                    }


                    public void addList(FoodCategoryResultBean.DataBean.FoodCategoryBean categoryBean, int parentId, List<FoodCategoryResultBean.DataBean.FoodCategoryBean> childList) {
                        if (categoryBean.getId() == parentId) {
                            if (categoryBean.getList() == null) {
                                categoryBean.setList(childList);
                            }
                            //如果有數據了，就是已經請求過了，不需要再次請求
                        } else {
                            List<FoodCategoryResultBean.DataBean.FoodCategoryBean> list = categoryBean.getList();
                            if (list != null && list.size() > 0) {
                                for (int i = 0; i < list.size(); i++) {
                                    if (list.get(i).getId() == parentId) {
                                        if (list.get(i).getList() == null) {
                                            list.get(i).setList(childList);
                                        } else {
                                            list.get(i).getList().addAll(childList);
                                        }
                                        return;
                                    } else {
                                        addList(list.get(i), parentId, childList);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });

    }

}
