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 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.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerEditFoodComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.EditFoodContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.FoodGroupBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SummaryBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.TimePeriodBean;
import com.gingersoft.gsa.cloud.main.mvp.presenter.EditFoodPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.foodmenu.FoodGroupEditAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.List;

import butterknife.BindView;
import me.yokeyword.fragmentation.ISupportFragment;

import static com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu.NewlyAddedFragment.SUMMARY_INFO;
import static com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu.NewlyAddedFragment.TIME_PERIOD_INFO;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * 餐牌 -- 編輯共用fragment
 */
public class EditFoodFragment extends BaseFoodMenuFragment<EditFoodPresenter> implements EditFoodContract.View, View.OnClickListener {

    public static EditFoodFragment newInstance(int fragmentType, String title) {
        return newInstance(fragmentType, title, false);
    }

    public static EditFoodFragment newInstance(int fragmentType, String title, boolean isToShellActivity) {
        EditFoodFragment fragment = new EditFoodFragment();
        fragment.setArguments(getBundle(fragmentType, title, isToShellActivity));
        return fragment;
    }

    private static Bundle getBundle(int fragmentType, String title, boolean isToShellActivity) {
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_TYPE, fragmentType);
        bundle.putString(TITLE_KEY, title);
        bundle.putBoolean(TO_SHELL_ACTIVITY, isToShellActivity);
        return bundle;
    }

    @BindView(R2.id.topbar_list)
    QMUITopBar topbarList;
    @BindView(R2.id.rv_content)
    RecyclerView rvContent;
    private int fragmentType;
    private String title;
    private boolean toShellActivity;

    private FoodGroupEditAdapter foodGroupEditAdapter;

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            fragmentType = arguments.getInt(FRAGMENT_TYPE);
            title = arguments.getString(TITLE_KEY);
            toShellActivity = arguments.getBoolean(TO_SHELL_ACTIVITY);
        }
        initTopBar(title);
        getInfo();
    }

    private void getInfo() {
        mPresenter.loadInfo(fragmentType);
    }

    @Override
    public void loadInfoList(List<FoodGroupBean> foodGroupBeans) {
        rvContent.addItemDecoration(new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL));
        rvContent.setLayoutManager(new LinearLayoutManager(mContext));
        foodGroupEditAdapter = new FoodGroupEditAdapter(foodGroupBeans);
        rvContent.setAdapter(foodGroupEditAdapter);
    }

    @Override
    public void setTimePeriodClick(List<TimePeriodBean> timePeriodBeans) {
        foodGroupEditAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable(TIME_PERIOD_INFO, timePeriodBeans.get(position));
            itemClick(bundle);
        });

        foodGroupEditAdapter.setOnItemChildClickListener((adapter, view, position) -> {
//            if (view.getId() == R.id.iv_food_group_delete) {
//                new AppDialog().showWaringDialog(mContext, "是否確認刪除？", (view1, dialog) -> {
//                    mPresenter.deleteInfoById(fragmentType, timePeriodBeans.get(position).getId(), position);
//                    dialog.dismiss();
//                });
//            } else if (view.getId() == R.id.iv_food_group_edit) {
//                NewlyAddedFragment newlyAddedFragment = NewlyAddedFragment.newInstance(NEW_TIME_PERIOD, "編輯時段");
//                Bundle arguments = newlyAddedFragment.getArguments();
//                arguments.putSerializable(TIME_PERIOD_INFO, timePeriodBeans.get(position));
//                newlyAddedFragment.putNewBundle(arguments);
//                startForResult(newlyAddedFragment, fragmentType);
//            }
            NewlyAddedFragment newlyAddedFragment = NewlyAddedFragment.newInstance(NEW_TIME_PERIOD, "編輯時段");
            Bundle arguments = newlyAddedFragment.getArguments();
            arguments.putSerializable(TIME_PERIOD_INFO, timePeriodBeans.get(position));
            newlyAddedFragment.putNewBundle(arguments);
            itemChildChick(view.getId(), timePeriodBeans.get(position).getId(), position, newlyAddedFragment);
        });
    }

    @Override
    public void setSummaryClick(List<SummaryBean> summaryBeans) {
        foodGroupEditAdapter.setOnItemClickListener((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable(SUMMARY_INFO, summaryBeans.get(position));
            itemClick(bundle);
        });

        foodGroupEditAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            NewlyAddedFragment newlyAddedFragment = NewlyAddedFragment.newInstance(NEW_FOOD_TYPE, "編輯餐種");
            Bundle arguments = newlyAddedFragment.getArguments();
            arguments.putSerializable(SUMMARY_INFO, summaryBeans.get(position));
            newlyAddedFragment.putNewBundle(arguments);
            itemChildChick(view.getId(), summaryBeans.get(position).getId(), position, newlyAddedFragment);
        });
    }

    private void itemClick(Bundle bundle) {
        setFragmentResult(fragmentType, bundle);
        killMyself();
    }

    private void itemChildChick(int viewId, int id, int position, ISupportFragment toFragment) {
        if (viewId == R.id.iv_food_group_delete) {
            new AppDialog().showWaringDialog(mContext, "是否確認刪除？", (view1, dialog) -> {
                mPresenter.deleteInfoById(fragmentType, id, position);
                dialog.dismiss();
            });
        } else if (viewId == R.id.iv_food_group_edit) {
            startForResult(toFragment, fragmentType);
        }
    }

    @Override
    public void deleteByPosition(int position) {
        foodGroupEditAdapter.removeAt(position);
    }


    public void initTopBar(String title) {
        topbarList.setTitle(title);
        topbarList.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> {
            killMyself();
        });
        topbarList.addRightImageButton(R.drawable.ic_white_add, R.id.topbar_right_add_button).setOnClickListener(this);
        topbarList.addRightImageButton(R.drawable.ic_white_edit, R.id.topbar_right_edit_button).setOnClickListener(this);
    }

    @Override
    public boolean onBackPressedSupport() {
        if (foodGroupEditAdapter.isShowEdit()) {
            foodGroupEditAdapter.setShowEdit();
            return true;
        }
        return super.onBackPressedSupport();
    }

    /**
     * 通过此方法可以使 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() {
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activity.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.topbar_right_add_button) {
            int toFragmentType = 0;
            switch (fragmentType) {
                case SELECT_FOOD_GROUP:
                    toFragmentType = NEW_FOOD_GROUP;
                    break;
                case SELECT_FOOD_TYPE:
                    toFragmentType = NEW_FOOD_TYPE;
                    break;
                case SELECT_TIME_PERIOD:
                    toFragmentType = NEW_TIME_PERIOD;
                    break;
                case SELECT_FOOD_ITEM_GROUP:
                    toFragmentType = ADD_FOOD_ITEM_GROUP;
                    break;
                default:
                    break;
            }
            startForResult(getFragmentByType(toFragmentType), fragmentType);
        } else if (viewId == R.id.topbar_right_edit_button) {
            if (foodGroupEditAdapter != null) {
                foodGroupEditAdapter.setShowEdit();
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        getInfo();
    }
}
