package com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerFoodMenuComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.FoodMenuContract;
import com.gingersoft.gsa.cloud.main.mvp.presenter.FoodMenuPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.foodmenu.FoodMenuMangerLeftAdapter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.foodmenu.FoodMenuMangerRightAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.PinnedHeaderItemDecoration;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/03/2020 09:31
 * <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 FoodMenuFragment extends BaseFoodMenuFragment<FoodMenuPresenter> implements FoodMenuContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_food_menu)
    QMUITopBar topbarFoodMenu;
    @BindView(R2.id.btn_add_food_group)
    QMUIAlphaButton btnAddFoodGroup;
    @BindView(R2.id.rv_food_menu_food_classification)
    RecyclerView leftRv;
    @BindView(R2.id.rv_food_menu_all_food)
    RecyclerView rightRv;
    @BindView(R2.id.layout_food_menu_left)
    RelativeLayout leftLayout;

    private int fragmentType;
    /**
     * 右側滑動，會重複調用左側，這裡記錄一下上次的下標，判斷是否和上次一樣，是一樣的就不執行
     */
    private int lastPosition = -1;
    /**
     * 左側的分類index
     */
    private int sectionPosition = -1;
    /**
     * 左側分類recyclerview的高度的一半，避免每次計算
     */
    private int halfLeftRvHeight;

    public static FoodMenuFragment newInstance(int type) {
        FoodMenuFragment fragment = new FoodMenuFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        int screenWidth = ArmsUtils.getScreenWidth(mContext);
        ViewGroup.LayoutParams layoutParams = leftLayout.getLayoutParams();
        layoutParams.width = screenWidth / 3;
        leftLayout.setLayoutParams(layoutParams);

        ViewGroup.LayoutParams layoutParams1 = rightRv.getLayoutParams();
        layoutParams1.width = screenWidth - layoutParams.width;
        rightRv.setLayoutParams(layoutParams1);


        Bundle arguments = getArguments();
        if (arguments != null) {
            fragmentType = arguments.getInt(FRAGMENT_TYPE);
        }
        initAddGroupBtn();
        initTopBar();
        initRv();
    }

    private void initRv() {
        //查詢出食品組
        FoodDaoUtils foodDaoUtils = new FoodDaoUtils(mContext);

        //設置右側食品數據
        List<Food> foods = foodDaoUtils.queryAllFood();
        List<Food> foodGroups = new ArrayList<>();
        for (Food food : foods) {
            if (food.getParentId() == 0) {
                foodGroups.add(food);
            }
        }
        //設置左側category的數據
        LinearLayoutManager leftLayoutManager = new LinearLayoutManager(mContext);
        leftRv.setLayoutManager(leftLayoutManager);
        leftRv.setHasFixedSize(true);
        leftRv.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
        FoodMenuMangerLeftAdapter foodMenuMangerLeftAdapter = new FoodMenuMangerLeftAdapter(mContext, foodGroups);
        leftRv.setAdapter(foodMenuMangerLeftAdapter);

        LinearLayoutManager rightLayoutManager = new LinearLayoutManager(mContext);
        FoodMenuMangerRightAdapter foodMenuMangerRightAdapter = new FoodMenuMangerRightAdapter(foodGroups, foods);
        rightRv.setLayoutManager(rightLayoutManager);
        rightRv.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));

        PinnedHeaderItemDecoration pinnedHeaderItemDecoration = new PinnedHeaderItemDecoration(foodMenuMangerRightAdapter.TITLE);
        rightRv.addItemDecoration(pinnedHeaderItemDecoration);
        rightRv.setAdapter(foodMenuMangerRightAdapter);

        //左側category點擊時右側滾動到指定位置
        foodMenuMangerLeftAdapter.setOnItemClickListener((adapter, view, position) -> {
            int section = foodMenuMangerRightAdapter.getPositionForSection(position);
            foodMenuMangerLeftAdapter.setSelectIndex(position);
            rightLayoutManager.scrollToPositionWithOffset(section, 0);
            sectionPosition = position;

            moveToCenter(leftLayoutManager, sectionPosition);
        });
        pinnedHeaderItemDecoration.setOnSelectListener(position -> {
            if (lastPosition != position) {
                lastPosition = position;

                int sectionPosition = foodMenuMangerRightAdapter.getSectionForPosition(lastPosition);
                if (this.sectionPosition != sectionPosition) {
                    this.sectionPosition = sectionPosition;
                    leftRv.scrollToPosition(sectionPosition);
                    foodMenuMangerLeftAdapter.setSelectIndex(sectionPosition);

                    int firstPosition = leftLayoutManager.findFirstVisibleItemPosition();

                    if (sectionPosition - firstPosition >= 0) {
                        moveToCenter(leftLayoutManager, sectionPosition);
                    }
                }
            }
        });
    }

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

    private void initAddGroupBtn() {
        if (fragmentType == FOOD_MANGER) {
            btnAddFoodGroup.setText("+食品組");
        } else if (fragmentType == FOOD_ITEM_MANGER) {
            btnAddFoodGroup.setText("+細項組");
        } else if (fragmentType == FOOD_SET_MEAL_MANGER) {
            btnAddFoodGroup.setText("+套餐組");
        }
    }

    public void initTopBar() {
        if (fragmentType == FOOD_MANGER) {
            topbarFoodMenu.setTitle("餐牌管理");
        } else if (fragmentType == FOOD_ITEM_MANGER) {
            topbarFoodMenu.setTitle("細項管理");
        } else if (fragmentType == FOOD_SET_MEAL_MANGER) {
            topbarFoodMenu.setTitle("套餐管理");
        }
        topbarFoodMenu.addLeftBackImageButton().setOnClickListener(v -> {
            FragmentActivity activity = getActivity();
            if (activity != null) {
                activity.onBackPressed();
            }
        });
        QMUIAlphaImageButton rightButton = topbarFoodMenu.addRightImageButton(R.drawable.ic_add_have_border, R.id.topbar_right_add_button);
        rightButton.setOnClickListener(v -> {
            if (fragmentType == FOOD_MANGER) {
                toFragmentByFragmentType(FOOD_PROPERTIES);
            } else if (fragmentType == FOOD_ITEM_MANGER) {
                toFragmentByFragmentType(NEW_FOOD_ITEM);
            } else if (fragmentType == FOOD_SET_MEAL_MANGER) {
                toFragmentByFragmentType(NEW_FOOD_SET_MEAL);
            }
        });
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
    }

    @OnClick({R2.id.btn_add_food_group})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_add_food_group) {
            if (fragmentType == FOOD_MANGER) {
                toFragmentByFragmentType(NEW_FOOD_GROUP);
            } else if (fragmentType == FOOD_ITEM_MANGER) {
                toFragmentByFragmentType(ADD_FOOD_ITEM_GROUP);
            } else if (fragmentType == FOOD_SET_MEAL_MANGER) {
                toFragmentByFragmentType(NEW_FOOD_SET_MEAL_GROUP);
            }
        }
    }
}
