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

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.ui.adapter.BaseCategoryAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
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.DaggerFoodIngredientsComponent;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.FoodIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.FoodIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.FoodListAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OrderCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.fragment.order.ShoppingCatFragment;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaLinearLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.supply_chain.mvp.ui.fragment.food.NewFoodIngredientsFragment.EDIT_FOOD_RESULT_CODE;

/**
 * ================================================
 * Description: 食材管理
 */
public class FoodIngredientsFragment extends BaseSupplyChainFragment<FoodIngredientsPresenter> implements FoodIngredientsContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_food_ingredients)
    QMUITopBar topbarFoodIngredients;
    @BindView(R2.id.ed_food_ingredients_search)
    EditText edFoodIngredientsSearch;
    @BindView(R2.id.btn_food_ingredients_search)
    QMUIAlphaButton btnFoodIngredientsSearch;
    @BindView(R2.id.layout_food_ingredients_search)
    LinearLayout layoutFoodIngredientsSearch;
    @BindView(R2.id.rv_food_ingredients_category)
    RecyclerView rvLeftCategory;
    @BindView(R2.id.rv_food_ingredients)
    RecyclerView rvRightFoodIngredients;
    @BindView(R2.id.srl_supplier)
    LinearLayout srlSupplier;
    @BindView(R2.id.btn_new_food_ingredient)
    QMUIAlphaButton btnNewFoodIngredient;
    @BindView(R2.id.btn_food_ingredients_confirm)
    QMUIAlphaButton btnConfirm;
    @BindView(R2.id.btn_food_ingredients_cancel)
    QMUIAlphaButton btnCancel;
    @BindView(R2.id.rv_food_ingredients_second_category)
    RecyclerView rvSecondCategory;
    @BindView(R2.id.tv_switch_food_ingredients_show_type)
    TextView tvSwitchShowType;
    @BindView(R2.id.layout_switch_method)
    QMUIAlphaLinearLayout layoutSwitchMethod;
    /**
     * 左側分類recyclerview的高度的一半，用來自動滾動到中間，避免每次計算
     */
    private int halfLeftRvHeight;
    /**
     * 頁面類型
     * FOOD_INGREDIENTS 為編輯食材頁面
     * ADD_ORDER 為添加訂單頁面
     * GET_FOOD_BY_SUPPLIER 跟進供應商顯示食品列表
     */
    private int pageType = 1;
    public final static int FOOD_INGREDIENTS = 1;
    public final static int ADD_ORDER = 2;
    public final static int ORDER_TYPE = 3;
    public final static int GET_FOOD_BY_SUPPLIER = 4;
    private final static String pageTypeKey = "pageType";

    private final static String supplierIdKey = "supplierId";
    private final static String supplierNameKey = "supplierName";
    /**
     * 當前選中的供應商名字
     * 當前選中的分類名字
     */
    private String currentSupplierName;
    private String currentCategoryName;

    private FoodListAdapter foodListAdapter;
    /**
     * true：查看的是供應商的食材
     * false：查看分類下的食材
     */
    private boolean isSupplier = false;

    private final int EDIT_FOOD_REQUEST_CODE = 1050;
    /**
     * 分類id，查詢此分類下的食品
     */
    private int categoryId;
    /**
     * 供應商id，查詢此供應商下的食品
     */
    private int supplierId;

    private BaseCategoryAdapter listSelectAdapter;

    public static FoodIngredientsFragment newInstance(int pageType) {
        FoodIngredientsFragment fragment = new FoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(pageTypeKey, pageType);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static FoodIngredientsFragment newInstance(int supplierId, String supplierName) {
        FoodIngredientsFragment fragment = new FoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(pageTypeKey, GET_FOOD_BY_SUPPLIER);
        bundle.putInt(supplierIdKey, supplierId);
        bundle.putString(supplierNameKey, supplierName);
        fragment.setArguments(bundle);
        return fragment;
    }



    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerFoodIngredientsComponent //如找不到该类,请编译一下项目
                .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_food_ingredients, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            pageType = arguments.getInt(pageTypeKey);
        }
        loadService = LoadSir.getDefault().register(rvRightFoodIngredients, (Callback.OnReloadListener) v -> {});
        initTopBar();
        //初始化購物車數據
        SupplyShoppingCart.getInstance().getCartFoods();
        loadDataByType();
    }

    private void loadDataByType(){
        if(pageType == GET_FOOD_BY_SUPPLIER){
            Bundle arguments = getArguments();
            if (arguments != null) {
                int supplierId = arguments.getInt(supplierIdKey);
                String supplierName = arguments.getString(supplierNameKey);
                CategoryBean categoryBean = new CategoryBean(supplierId, supplierName);
                loadLeftSupplierInfo(Collections.singletonList(categoryBean));
                this.supplierId = supplierId;
                setCurrentSupplierName(supplierName);
                getFoodsBySupplierId();
            } else {
                killMyself();
            }
        } else {
            mPresenter.getCategoryTrees();
        }
    }

    private void getSuppliers() {
        mPresenter.loadFoodIngredientsData(-1);
    }

    private void getFoodsBySupplierId() {
        mPresenter.getFoodsBySupplierId(supplierId);
    }

    private void getFoodsByCategoryId() {
        mPresenter.getFoodByCategory(categoryId);
    }

    private void initTopBar() {
        if (pageType == FOOD_INGREDIENTS) {
            topbarFoodIngredients.setTitle("食材管理");
            btnNewFoodIngredient.setVisibility(View.VISIBLE);
            btnConfirm.setVisibility(View.GONE);
            btnCancel.setVisibility(View.GONE);
        } else if (pageType == ADD_ORDER) {
            topbarFoodIngredients.setTitle("採購單");
            btnNewFoodIngredient.setVisibility(View.GONE);
            btnConfirm.setVisibility(View.VISIBLE);
            btnCancel.setVisibility(View.VISIBLE);
            topbarFoodIngredients.addRightImageButton(R.drawable.ic_circle_new_food_ingredient, R.id.qmui_add_new_food_ingredients).setOnClickListener(v -> {
                //新增食材
                start(NewFoodIngredientsFragment.newInstance(currentSupplierName, currentCategoryName));
            });
        } else if(pageType == GET_FOOD_BY_SUPPLIER){
            //根據供應商顯示食材
            //隱藏切換按鈕
            topbarFoodIngredients.setTitle("採購單");
            layoutSwitchMethod.setVisibility(View.GONE);
            btnConfirm.setVisibility(View.VISIBLE);
            btnCancel.setVisibility(View.VISIBLE);topbarFoodIngredients.addRightImageButton(R.drawable.ic_circle_new_food_ingredient, R.id.qmui_add_new_food_ingredients).setOnClickListener(v -> {
                //新增食材
                start(NewFoodIngredientsFragment.newInstance(currentSupplierName, currentCategoryName));
            });
        }
        topbarFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

    private void moveToCenter(LinearLayoutManager leftLayoutManager, int sectionPosition) {
        View childAt = rvLeftCategory.getChildAt(sectionPosition - leftLayoutManager.findFirstVisibleItemPosition());
        if (halfLeftRvHeight == 0) {
            halfLeftRvHeight = rvLeftCategory.getHeight() / 2;
        }
        if (childAt != null) {
            int y = (childAt.getTop() - halfLeftRvHeight);
            rvLeftCategory.smoothScrollBy(0, y);
        }
    }

    @OnClick({R2.id.layout_switch_method, R2.id.btn_new_food_ingredient, R2.id.btn_food_ingredients_search, R2.id.btn_food_ingredients_confirm, R2.id.btn_food_ingredients_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.layout_switch_method) {
            //切換
            isSupplier = !isSupplier;
            showPrimaryCategory(View.GONE, View.VISIBLE);
            if (isSupplier) {
                tvSwitchShowType.setText("切換種類");
                //獲取供應商，並且會獲取到第一個供應商的食材
                getSuppliers();
            } else {
                //根據分類獲取食材
                tvSwitchShowType.setText("切換供應商");
                mPresenter.getCategoryTrees();
            }
        } else if (viewId == R.id.btn_new_food_ingredient) {
            //新增
            startForResult(NewFoodIngredientsFragment.newInstance(currentSupplierName, currentCategoryName), EDIT_FOOD_REQUEST_CODE);
        } else if (viewId == R.id.btn_food_ingredients_search) {
            //搜索

        } else if (viewId == R.id.btn_food_ingredients_confirm) {
            //選擇完食品後,完成
            //把選中的數據取出
            if (foodListAdapter != null) {
                mPresenter.getSelectFood(foodListAdapter.getIntegerMap());
            }
            start(ShoppingCatFragment.newInstance());
        } else if (viewId == R.id.btn_food_ingredients_cancel) {
            //取消
            killMyself();
        }
    }

    /**
     * 加載左側供應商列表
     */
    @Override
    public void loadLeftSupplierInfo(List<CategoryBean> categoryBeans) {
        if (listSelectAdapter == null) {
            listSelectAdapter = new BaseCategoryAdapter(categoryBeans, mContext);
            listSelectAdapter.setUnSelectColor(ContextCompat.getColor(mContext, R.color.color_3c))
                    .setSelectColor(ContextCompat.getColor(mContext, R.color.theme_color));
            listSelectAdapter.setOnItemClickListener((adapter, view, position) -> {
                listSelectAdapter.setSelectedIndex(position);
                moveToCenter((LinearLayoutManager) rvLeftCategory.getLayoutManager(), position);
                //獲取供應商的食品
                supplierId = categoryBeans.get(position).getId();
                setCurrentSupplierName(categoryBeans.get(position).getCategoryName());
                getFoodsBySupplierId();
            });
        } else {
            listSelectAdapter.setNewInstance(categoryBeans);
        }
        rvLeftCategory.setAdapter(listSelectAdapter);
    }

    /**
     * 加載右側食品數據
     */
    @Override
    public void loadRightFoodIngredients(List<PurchaseFoodBean> purchaseFoodListVos) {
        if (purchaseFoodListVos == null || purchaseFoodListVos.size() <= 0) {
            loadService.showCallback(EmptyCallback.class);
            return;
        } else {
            loadService.showSuccess();
        }
        if (foodListAdapter != null) {
            foodListAdapter.setList(purchaseFoodListVos);
        } else {
            foodListAdapter = new FoodListAdapter(mContext, purchaseFoodListVos, pageType);
            Map<Integer, PurchaseFoodBean> integerMap = foodListAdapter.getIntegerMap();
            for (PurchaseFoodBean purchaseFoodBean : SupplyShoppingCart.getInstance().getCartFoods()) {
                integerMap.put(purchaseFoodBean.getId(), purchaseFoodBean);
            }
            LinearLayoutManager rightLayoutManager = new LinearLayoutManager(mContext);
            rvRightFoodIngredients.setLayoutManager(rightLayoutManager);
            rvRightFoodIngredients.setAdapter(foodListAdapter);
            foodListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_supplier_edit) {
                    //編輯食材
                    startForResult(NewFoodIngredientsFragment.newInstance(foodListAdapter.getData().get(position)), EDIT_FOOD_REQUEST_CODE);
                } else if (view.getId() == R.id.iv_supplier_delete) {
                    //刪除食材
                    PurchaseFoodBean purchaseFoodBean = foodListAdapter.getData().get(position);
                    new AppDialog().showWaringDialog(mContext, "是否確認刪除" + purchaseFoodBean.getName(), (view1, dialog) -> {
                        mPresenter.deleteFood(purchaseFoodBean, position);
                        dialog.dismiss();
                    });
                }
            });
        }
    }

    @Override
    public void onDeleteFoodSuccess(int position) {
        foodListAdapter.notifyItemChanged(position);
    }

    private OrderCategoryAdapter orderCategoryAdapter;
    private OrderCategoryAdapter secondCategoryAdapter;

    @Override
    public void loadCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        initPrimaryAdapter(foodCategoryTrees);
        orderCategoryAdapter.setOnSecondCategoryClickListener((foodCategoryTrees1, position) -> {
            //點擊二級分類時，隱藏一級，顯示二級分類數據
            if (orderCategoryAdapter.getCurrentLevelCategory() == orderCategoryAdapter.PRIMARY_CATEGORY) {
                categoryId = foodCategoryTrees1.get(position).getId();
                setCurrentCategoryName(foodCategoryTrees1.get(position).getName());
                getFoodsByCategoryId();
                initSecondAdapter(foodCategoryTrees1, position);
            }
        });
    }

    @Override
    public void loadFail() {
        loadService.showCallback(ErrorCallback.class);
    }

    @Override
    public void setCurrentSupplierName(String name) {
        currentSupplierName = name;
    }

    @Override
    public void setCurrentCategoryName(String name) {
        currentCategoryName = name;
    }

    private void initSecondAdapter
            (List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees, int position) {
        //二級分類被點擊
        if (secondCategoryAdapter == null) {
            secondCategoryAdapter = new OrderCategoryAdapter(mContext, foodCategoryTrees);
            secondCategoryAdapter.setCurrentLevelCategory(orderCategoryAdapter.SECOND_CATEGORY);
            secondCategoryAdapter.setOnItemChildClickListener((a, v, p) -> {
                //點擊返回，隱藏二級分類，顯示一級分類
                if (v.getId() == R.id.layout_order_category_back) {
                    showPrimaryCategory(View.GONE, View.VISIBLE);
                }
            });
            secondCategoryAdapter.setOnItemClickListener((adapter1, view1, position1) -> secondCategoryAdapter.setSelectIndex(position1));
            secondCategoryAdapter.setOnSecondCategoryClickListener((foodCategoryTrees1, position12) -> {
                categoryId = foodCategoryTrees1.get(position12).getId();
                setCurrentCategoryName(foodCategoryTrees1.get(position).getName());
                getFoodsByCategoryId();
            });
            rvSecondCategory.setAdapter(secondCategoryAdapter);
        } else {
            secondCategoryAdapter.setNewInstance(foodCategoryTrees);
        }
        //設置選中
        secondCategoryAdapter.setSelectIndex(position);
        showPrimaryCategory(View.VISIBLE, View.GONE);
    }

    private void showPrimaryCategory(int gone, int visible) {
        rvSecondCategory.setVisibility(gone);
        rvLeftCategory.setVisibility(visible);
    }

    private void initPrimaryAdapter
            (List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (orderCategoryAdapter == null) {
            orderCategoryAdapter = new OrderCategoryAdapter(mContext, foodCategoryTrees);
        } else {
            orderCategoryAdapter.setNewInstance(foodCategoryTrees);
        }
        rvLeftCategory.setAdapter(orderCategoryAdapter);
        orderCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
            categoryId = foodCategoryTrees.get(position).getId();
            setCurrentCategoryName(foodCategoryTrees.get(position).getName());
            getFoodsByCategoryId();
            orderCategoryAdapter.setSelectIndex(position);
        });
        if (orderCategoryAdapter.getSelectIndex() != -1) {
            categoryId = foodCategoryTrees.get(orderCategoryAdapter.getSelectIndex()).getId();
            setCurrentCategoryName(foodCategoryTrees.get(orderCategoryAdapter.getSelectIndex()).getName());
            getFoodsByCategoryId();
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == EDIT_FOOD_REQUEST_CODE && resultCode == EDIT_FOOD_RESULT_CODE) {
            //編輯食材後，刷新
            if (isSupplier) {
                //根據供應商獲取食材
                getFoodsBySupplierId();
            } else {
                getFoodsByCategoryId();
            }
        }
    }
}
