package com.gingersoft.gsa.cloud.manager.mvp.ui.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.manager.R2;
import com.gingersoft.gsa.cloud.manager.di.component.DaggerTableListComponent;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.TableArea;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.TableItem;
import com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity;
import com.gingersoft.gsa.cloud.manager.mvp.ui.adapter.AreaManageAdapter;
import com.gingersoft.gsa.cloud.manager.mvp.ui.adapter.TableManageSectiontAdapter;
import com.gingersoft.gsa.cloud.ui.adapter.BasTextSectiontAdapter;
import com.gingersoft.gsa.cloud.ui.bean.mode.LoginBean;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionHeader;
import com.gingersoft.gsa.cloud.ui.utils.AnimateUtils;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.gingersoft.gsa.cloud.manager.mvp.contract.TableListContract;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.TableListPresenter;

import com.gingersoft.gsa.cloud.manager.R;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.base.common.bean.OrderDetail.DISCOUNT_TYPE;
import static com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity.ADD_AREA_RESULT_SUCCESS;
import static com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity.ADD_TABLE_RESULT_SUCCESS;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/20/2020 10:29
 * <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 TableListFragment extends BaseFragment<TableListPresenter> implements TableListContract.View {

    @BindView(R2.id.topbar)
    QMUITopBarLayout mTopBar;
    @BindView(R2.id.section_table)
    QMUIStickySectionLayout mSectionLayout;
    @BindView(R2.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;

    @BindView(R2.id.tv_add_table)
    QMUIAlphaTextView tv_add_table;
    @BindView(R2.id.tv_area)
    QMUIAlphaTextView tv_area;

    @BindView(R2.id.ll_bottom_operat)
    LinearLayout ll_bottom_operat;

    private TableManageActivity mActivity;

    private List<TableItem> mTableList = new ArrayList<>();
    private List<TableArea> mAreaList = new ArrayList<>();

    private TableManageSectiontAdapter mAdapter;
    private List<QMUISection<SectionHeader, TableItem>> mTableAreaSectionList;

    /**
     * 是否編輯
     */
    private boolean isRadioEdit = false;


    public static TableListFragment newInstance() {
        Bundle args = new Bundle();
        TableListFragment fragment = new TableListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerTableListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        BaseFragment firstFragment = findChildFragment(TableListFragment.class);
        if (firstFragment == null) {

        }
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_table_list, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mActivity = (TableManageActivity) _mActivity;

        initTopbar();
        initRefreshLayout();
        initStickyLayout();
        mActivity.queryAreas(null);
        mActivity.queryTables(null);
    }

    @Override
    public void onResume() {
        super.onResume();
        hideSoftInput();
    }

    private void initTopbar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.theme_color));
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> killMyself());
        mTopBar.setTitle("餐檯管理").setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));

        Button rightButton = mTopBar.addRightTextButton("編輯", R.id.qmui_dialog_edit_right_icon);
        rightButton.setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        rightButton.setOnClickListener(v -> {
            isRadioEdit = !isRadioEdit;
            if (isRadioEdit) {
                rightButton.setText("取消");
            } else {
                rightButton.setText("編輯");
            }
            showRadioEdit();
            mAdapter.setRadioEdit(isRadioEdit);
            mAdapter.notifyDataSetChanged();
        });
    }

    private void initRefreshLayout() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                mActivity.queryTables(refreshLayout);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {

            }
        });
    }

    private void initStickyLayout() {
        mSectionLayout.setLayoutManager(createLayoutManager());
        mAdapter = new TableManageSectiontAdapter();
        mAdapter.setCallback(new QMUIStickySectionAdapter.Callback<SectionHeader, TableItem>() {

            @Override
            public void loadMore(QMUISection<SectionHeader, TableItem> section, boolean loadMoreBefore) {

            }

            @Override
            public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                if (holder instanceof TableManageSectiontAdapter.ViewHolder) {
                    TableManageSectiontAdapter.ViewHolder viewHolder = (TableManageSectiontAdapter.ViewHolder) holder;
                    if (viewHolder.getTvName().getText() != null) {
                        TableItem item = viewHolder.getTableItem(position);
                        start(AddTableFragment.newInstance(item));
                    }
                } else {
                    //點擊的頭部，折疊
                }
            }

            @Override
            public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                return false;
            }
        });
        mSectionLayout.getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (view instanceof TextView) {
                    int margin = QMUIDisplayHelper.dp2px(getContext(), 10);
                    outRect.set(margin, margin, margin, margin);
                } else {
                    outRect.set(0, 0, 0, 0);
                }
            }
        });
        mSectionLayout.setAdapter(mAdapter, true);
        mAdapter.setData(mTableAreaSectionList);
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                return mAdapter.getItemIndex(i) < 0 ? layoutManager.getSpanCount() : 1;
            }
        });
        return layoutManager;
    }

    public void updateAreaData(List<TableArea> tableAreaList) {
        if (mAreaList.size() > 0) {
            mAreaList.clear();
        }
        mAreaList.addAll(tableAreaList);
    }

    public void updateTableData(List<TableItem> tableItemList) {

        initParms();

        mTableList.addAll(tableItemList);

        for (TableItem item : mTableList) {
            if (item.getRegionId() == 0) {
                item.setRegionId(-1);
            }
        }
        mTableAreaSectionList = mPresenter.tableAreaTransformToSection(mPresenter.assembleTableArea(mPresenter.assembleAreaList(mTableList), mTableList));
        mAdapter.setData(mTableAreaSectionList);
    }

    private void initParms() {
        if (mTableList.size() > 0) {
            mTableList.clear();
        }
        if (mAreaList.size() > 0) {
            mAreaList.clear();
        }
        if (mTableAreaSectionList != null) {
            mTableAreaSectionList.clear();
        }
    }

    public void deleteSuccess(){


    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @OnClick(R2.id.tv_area)
    void onClickToArea() {
        startForResult(AreaListFragment.newInstance(), ADD_AREA_RESULT_SUCCESS);
    }

    @OnClick(R2.id.tv_add_table)
    void onClickAddTable() {
        startForResult(AddTableFragment.newInstance(null), ADD_TABLE_RESULT_SUCCESS);
    }

    @OnClick(R2.id.btn_all_select)
    void onClickAddSelect() {
        for (int i = 0; i < mTableAreaSectionList.size(); i++) {
            for (int j = 0; j < mTableAreaSectionList.get(i).getItemCount(); j++) {
                mTableAreaSectionList.get(i).getItemAt(j).setChecked(true);
            }
        }
        mAdapter.setData(mTableAreaSectionList);
    }

    @OnClick(R2.id.btn_anti_select)
    void onClickAntiSelect() {
        for (int i = 0; i < mTableAreaSectionList.size(); i++) {
            for (int j = 0; j < mTableAreaSectionList.get(i).getItemCount(); j++) {
                TableItem tableItem = mTableAreaSectionList.get(i).getItemAt(j);
                tableItem.setChecked(!tableItem.isChecked());
            }
        }
        mAdapter.setData(mTableAreaSectionList);
    }

    @OnClick(R2.id.btn_sure)
    void onClickSure() {
        String ids = getDeleteIds();
        if (TextUtils.isEmpty(ids)) {
            showMessage("請選擇餐檯");
            return;
        }
        Class[] parameterTypes = {String.class};
        Object[] parameters = {ids};
        CommonTipDialog.showDoubtDialog(mActivity, "是否刪除所選餐檯", TableManageActivity.class, mActivity, "deleteTable", parameterTypes, parameters);
    }


    private String getDeleteIds() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < mTableAreaSectionList.size(); i++) {
            for (int j = 0; j < mTableAreaSectionList.get(i).getItemCount(); j++) {
                TableItem tableItem = mTableAreaSectionList.get(i).getItemAt(j);
                if (tableItem.isChecked()) {
                    builder.append(tableItem.getId());
                    builder.append(",");
                }
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }


    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(mContext, message, true);
        else
            LoadingDialog.showDialogForLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

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

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

    @Override
    public void killMyself() {
        _mActivity.finish();
    }

    private void showRadioEdit() {
        if (isRadioEdit) {
            tv_add_table.setVisibility(View.GONE);
            tv_area.setVisibility(View.GONE);
            ll_bottom_operat.setVisibility(View.VISIBLE);
        } else {
            tv_add_table.setVisibility(View.VISIBLE);
            tv_area.setVisibility(View.VISIBLE);
            ll_bottom_operat.setVisibility(View.GONE);
        }
    }
}
