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.widget.EditText;
import android.widget.LinearLayout;

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.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.gingersoft.gsa.cloud.ui.adapter.BaseCategoryAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
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.FoodListInfoBean;
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.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description: 食材管理
 * <p>
 * Created by MVPArmsTemplate on 11/24/2020 15:28
 * <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>
 * ================================================
 */
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;
    /**
     * 左側分類recyclerview的高度的一半，用來自動滾動到中間，避免每次計算
     */
    private int halfLeftRvHeight;
    /**
     * 頁面類型
     * FOOD_INGREDIENTS 為編輯食材頁面
     * ADD_ORDER 為添加訂單頁面
     */
    private int pageType = 1;
    public final static int FOOD_INGREDIENTS = 1;
    public final static int ADD_ORDER = 2;
    private final static String pageTypeKey = "pageType";

    private FoodListAdapter foodListAdapter;


    public static FoodIngredientsFragment newInstance(int pageType) {
        FoodIngredientsFragment fragment = new FoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(pageTypeKey, pageType);
        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);
        }
        initTopBar();
        getFoodsBySupplierId();
    }

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

    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());
            });
        }
        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) {
            //切換

        } else if (viewId == R.id.btn_new_food_ingredient) {
            //新增
            start(NewFoodIngredientsFragment.newInstance());
        } else if (viewId == R.id.btn_food_ingredients_search) {
            //搜索

        } else if (viewId == R.id.btn_food_ingredients_confirm) {
            //選擇完食品後,完成

        } else if (viewId == R.id.btn_food_ingredients_cancel) {
            //取消
            killMyself();
        }
    }

    @Override
    public void loadLeftSupplierInfo(List<CategoryBean> categoryBeans) {
        rvLeftCategory.setHasFixedSize(true);
        BaseCategoryAdapter listSelectAdapter = new BaseCategoryAdapter(categoryBeans, mContext);
        listSelectAdapter.setUnSelectColor(ContextCompat.getColor(mContext, R.color.color_3c))
                .setSelectColor(ContextCompat.getColor(mContext, R.color.theme_color));
        rvLeftCategory.setAdapter(listSelectAdapter);
        listSelectAdapter.setOnItemClickListener((adapter, view, position) -> {
            listSelectAdapter.setSelectedIndex(position);
            moveToCenter((LinearLayoutManager) rvLeftCategory.getLayoutManager(), position);
            //獲取數據
            mPresenter.getFoodsBySupplierId(categoryBeans.get(position).getId());
        });
    }

    @Override
    public void loadRightFoodIngredients(List<FoodListInfoBean.DataBean.PurchaseFoodListVOSBean> purchaseFoodListVOS) {
        if (foodListAdapter != null) {
            foodListAdapter.setList(purchaseFoodListVOS);
        } else {
            foodListAdapter = new FoodListAdapter(mContext, purchaseFoodListVOS, pageType);
            LinearLayoutManager rightLayoutManager = new LinearLayoutManager(mContext);
            rvRightFoodIngredients.setLayoutManager(rightLayoutManager);
            rvRightFoodIngredients.setAdapter(foodListAdapter);
            foodListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    if (view.getId() == R.id.iv_supplier_edit) {
                        //編輯食材

                    } else if (view.getId() == R.id.iv_supplier_delete) {
                        //刪除食材

                    }
                }
            });
        }
    }
}
