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.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerNewlyAddedComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.NewlyAddedContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.FoodMenuEditBean;
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.NewlyAddedPresenter;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.menu.ShellActivity;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.foodmenu.FoodMenuAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.utils.TimePickerUtils;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration.VERTICAL_LIST;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/03/2020 09:53
 * <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 NewlyAddedFragment extends BaseFoodMenuFragment<NewlyAddedPresenter> implements NewlyAddedContract.View, View.OnClickListener {
    public final static String TIME_PERIOD_INFO = "timePeriodInfo";
    public final static String SUMMARY_INFO = "summaryInfo";

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

    /**
     * @param fragmentType      fragment類型
     * @param title             標題
     * @param isToShellActivity 是否打開帶activity的fragment
     */
    public static NewlyAddedFragment newInstance(int fragmentType, String title, boolean isToShellActivity) {
        NewlyAddedFragment fragment = new NewlyAddedFragment();
        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;
    }

    private int fragmentType;
    private String title;
    private boolean toShellActivity;
    @BindView(R2.id.topbar_list)
    QMUITopBar topbarList;
    @BindView(R2.id.rv_content)
    RecyclerView rvContent;
    @BindView(R2.id.btn_save)
    QMUIAlphaButton btnSave;
    /**
     * 是新增還是修改，調用接口不同
     */
    private boolean isUpdate = false;

    private FoodMenuAdapter foodMenuAdapter;

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            fragmentType = arguments.getInt(FRAGMENT_TYPE);
            setFragmentResult(fragmentType, null);
            title = arguments.getString(TITLE_KEY);
            toShellActivity = arguments.getBoolean(TO_SHELL_ACTIVITY);
            List<FoodMenuEditBean> foodMenuEditBeans = FoodMenuAdapter.getFoodMenuEditBean(fragmentType);

            if (fragmentType == NEW_TIME_PERIOD) {
                //新增時段，如果有傳數據，則是編輯時段
                TimePeriodBean timePeriodBean = (TimePeriodBean) arguments.getSerializable(TIME_PERIOD_INFO);
                loadTimePeriodInfo(foodMenuEditBeans, timePeriodBean);
            } else if (fragmentType == NEW_FOOD_TYPE) {
                SummaryBean summaryBean = (SummaryBean) arguments.getSerializable(SUMMARY_INFO);
                loadSummaryInfo(foodMenuEditBeans, summaryBean);
            }
            initTopBar(title);
            //添加自定义分割线
            rvContent.addItemDecoration(new DividerItemDecoration(mContext, VERTICAL_LIST));
            rvContent.setLayoutManager(new LinearLayoutManager(mContext));
            foodMenuAdapter = FoodMenuAdapter.getFoodMenuAdapter(mContext, foodMenuEditBeans);

            foodMenuAdapter.setOnItemClickListener((adapter, view, position) -> {
                if (adapter.getItemViewType(position) == FoodMenuEditBean.EDIT_FOOD_ITEM_SELECT) {
                    List<FoodMenuEditBean> data = foodMenuAdapter.getData();
                    if (data.get(position).getSelectType() == FoodMenuEditBean.SELECT_TIME) {
                        //選擇時間
                        TimePickerUtils.init(mContext, (date, v) -> {
                            data.get(position).setShowValue(TimeUtils.DATE_FORMAT_HMS.format(date));
                            adapter.notifyItemChanged(position);
                        }).setType(new boolean[]{false, false, false, true, true, true})
                                .build()
                                .show();
                    } else if (data.get(position).getSelectType() == FoodMenuEditBean.SELECT_DATE) {
                        //選擇日期
                        TimePickerUtils.init(mContext, (date, v) -> {
                            data.get(position).setShowValue(TimeUtils.DATE_FORMAT_DATE.format(date));
                            adapter.notifyItemChanged(position);
                        }).setType(new boolean[]{true, true, true, false, false, false})
                                .build()
                                .show();
                    } else {
                        if (toShellActivity) {
                            Intent intent = new Intent(mContext, ShellActivity.class);
                            intent.putExtra(FRAGMENT_TYPE, foodMenuAdapter.getData().get(position).getFragmentType());
                            startActivity(intent);
                        } else {
                            toFragmentByFragmentType(foodMenuAdapter.getData().get(position).getFragmentType());
                        }
                    }
                } else {

                }
            });
            rvContent.setAdapter(foodMenuAdapter);
        } else {
            showMessage("類型錯誤");
            killMyself();
        }
    }

    private void loadTimePeriodInfo(List<FoodMenuEditBean> foodMenuEditBeans, TimePeriodBean timePeriodBean) {
        if (timePeriodBean != null) {
            isUpdate = true;
            foodMenuEditBeans.get(0).setTimePeriodBean(timePeriodBean);
            foodMenuEditBeans.get(0).setId(timePeriodBean.getId());
            foodMenuEditBeans.get(0).setShowValue(timePeriodBean.getPeriodName1());
            foodMenuEditBeans.get(1).setShowValue(timePeriodBean.getPeriodName2());
            foodMenuEditBeans.get(2).setShowValue(timePeriodBean.getPeriodName3());
            foodMenuEditBeans.get(3).setShowValue(timePeriodBean.getBeginDate());
            foodMenuEditBeans.get(4).setShowValue(timePeriodBean.getEndDate());
            foodMenuEditBeans.get(5).setShowValue(timePeriodBean.getBeginTime());
            foodMenuEditBeans.get(6).setShowValue(timePeriodBean.getEndTime());
            List<FoodMenuEditBean.ShowClient> checkBoxList = foodMenuEditBeans.get(9).getCheckBoxList();
            checkBoxList.get(0).setChecked(timePeriodBean.getDayH() == 1);
            checkBoxList.get(1).setChecked(timePeriodBean.getDay1() == 1);
            checkBoxList.get(2).setChecked(timePeriodBean.getDay2() == 1);
            checkBoxList.get(3).setChecked(timePeriodBean.getDay3() == 1);
            checkBoxList.get(4).setChecked(timePeriodBean.getDay4() == 1);
            checkBoxList.get(5).setChecked(timePeriodBean.getDay5() == 1);
            checkBoxList.get(6).setChecked(timePeriodBean.getDay6() == 1);
            checkBoxList.get(7).setChecked(timePeriodBean.getDay7() == 1);
        }
    }

    private void loadSummaryInfo(List<FoodMenuEditBean> foodMenuEditBeans, SummaryBean summaryBean) {
        if (summaryBean != null) {
            isUpdate = true;
            foodMenuEditBeans.get(0).setSummaryBean(summaryBean);
            foodMenuEditBeans.get(0).setShowValue(summaryBean.getName());
            foodMenuEditBeans.get(1).setShowState(summaryBean.getValid() == 1);
        }
    }

    public void initTopBar(String title) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(title)) {
            topbarList.setTitle(title);
            topbarList.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> {
                killMyself();
            });
        } else {
            topbarList.setVisibility(View.GONE);
        }
    }

    /**
     * 通过此方法可以使 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 boolean onBackPressedSupport() {
        return super.onBackPressedSupport();
    }

    @Override
    public void killMyself() {
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activity.onBackPressed();
        }
    }

    @OnClick({R2.id.btn_save})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_save) {
            mPresenter.saveInfoByType(fragmentType, foodMenuAdapter, isUpdate);
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if(data != null){
            List<FoodMenuEditBean> data1 = foodMenuAdapter.getData();
            if (requestCode == SELECT_TIME_PERIOD) {
                TimePeriodBean timePeriodBean = (TimePeriodBean) data.getSerializable(TIME_PERIOD_INFO);
                data1.get(3).setShowValue(timePeriodBean.getPeriodName1());
                foodMenuAdapter.notifyItemChanged(3);
            } else if(requestCode == SELECT_FOOD_TYPE){
                SummaryBean summaryBean = (SummaryBean) data.getSerializable(SUMMARY_INFO);
                data1.get(4).setShowValue(summaryBean.getName());
                foodMenuAdapter.notifyItemChanged(4);
            }
        }

    }
}
