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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.net.ParseException;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.common.bean.TableItem;
import com.gingersoft.gsa.cloud.manager.R2;
import com.gingersoft.gsa.cloud.manager.di.component.DaggerTableListComponent;
import com.gingersoft.gsa.cloud.base.common.bean.TableArea;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.TableRequest;
import com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity;
import com.gingersoft.gsa.cloud.manager.mvp.ui.adapter.TableManageSectiontAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionHeader;
import com.gingersoft.gsa.cloud.ui.recylcler.event.OnRecyclerItemClickListener;
import com.gingersoft.gsa.cloud.ui.recylcler.event.RecyItemTouchHelperCallback;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
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.QMUIAlphaFrameLayout;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
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 org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

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

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING;
import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_SETTLING;
import static com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity.ADD_AREA_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.fl_add_table)
    QMUIAlphaFrameLayout fl_add_table;

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

    private Button rightButton;

    private TableManageActivity mActivity;

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

    private TableManageSectiontAdapter mAdapter;
    private List<QMUISection<SectionHeader, TableItem>> mTableAreaSectionList = new ArrayList<>();

    private boolean initLoad = false;
    /**
     * 是否編輯
     */
    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();
        initRecycleScrollListener();
        mActivity.queryAreas(null);
        mActivity.queryTables(null);
        mActivity.initGetTableTimer();
        cb_all_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                for (int i = 0; i < mTableList.size(); i++) {
                    TableItem tableItem = mTableList.get(i);
                    if (tableItem.getStatus() == 0) {
                        mTableList.get(i).setChecked(isChecked);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        hideSoftInput();
        //開始刷新餐檯數據
        mActivity.onStartRefreshTableData();
    }

    @Override
    public void onPause() {
        super.onPause();
        //停止刷新餐檯數據
        mActivity.onPauseRefreshTableData();
    }

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

    }

    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));

        rightButton = mTopBar.addRightTextButton("編輯", R.id.qmui_dialog_edit_right_icon);
        rightButton.setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        rightButton.setOnClickListener(v -> {
            clickEdit(rightButton);
        });
    }

    private void clickEdit(Button rightButton) {
        isRadioEdit = !isRadioEdit;
        if (isRadioEdit) {
            initCheckedStatus();
            if (rightButton != null) {
                rightButton.setText("取消");
            }
            mActivity.onPauseRefreshTableData();
        } else {
            if (rightButton != null) {
                rightButton.setText("編輯");
            }
            mActivity.onStartRefreshTableData();
        }
        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);
                        if (item.getLayoutType() == 1) {
                            start(AddTableFragment.newInstance(item));
                        } else {
                            if (isRadioEdit) {
                                item.setChecked(!item.isChecked());
                                mAdapter.notifyDataSetChanged();
                            } else {
                                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(5, 5, 5, 5);
                }
            }
        });

        RecyItemTouchHelperCallback itemTouchHelperCallback = new RecyItemTouchHelperCallback(mAdapter);
        final ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchHelperCallback);
        itemTouchHelper.attachToRecyclerView(mSectionLayout.getRecyclerView());

        mSectionLayout.getRecyclerView().addOnItemTouchListener(new OnRecyclerItemClickListener(mSectionLayout.getRecyclerView()) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder) {
            }

            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder) {
//                QMUIStickySectionAdapter.ViewHolder viewHolder1 = (QMUIStickySectionAdapter.ViewHolder) viewHolder;
//                Toast.makeText(mActivity, "長按：" + viewHolder1.getAdapterPosition(), Toast.LENGTH_SHORT).show();
//                if (viewHolder.getLayoutPosition() != 0) {
//                    itemTouchHelper.startDrag(viewHolder);
//                }
            }
        });
        itemTouchHelperCallback.setOnMoveListener(new RecyItemTouchHelperCallback.onMoveListener() {

            @Override
            public void onMoveFinish(String ids) {
                mActivity.changeTableSort(ids);
            }
        });

        mSectionLayout.setAdapter(mAdapter, true);
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        final GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4, LinearLayoutManager.VERTICAL, false);
        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<TableArea> tableAreaList, List<TableItem> tableItemList) {

        initParms();

        mTableList.addAll(tableItemList);

        for (TableItem item : mTableList) {
            if (item.getRegionId() == 0) {
                item.setRegionId(-1);
            }
        }

        mTableAreaSectionList.addAll(mPresenter.tableAreaTransformToSection(mPresenter.assembleTableArea(mPresenter.assembleAreaList(tableAreaList, mTableList), mTableList)));

//        if (!initLoad) {
            mAdapter.setData(mTableAreaSectionList);
//        } else {
//            mAdapter.getCurrentData().clear();
//            mAdapter.getCurrentData().addAll(mTableAreaSectionList);
//            mAdapter.notifyDataSetChanged();
//        }

        mEmptyView.hide();
        mSectionLayout.setVisibility(View.VISIBLE);

        initLoad = true;
    }


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

    public void backEdit() {
        clickEdit(rightButton);
    }

    private void initCheckedStatus() {
        for (int i = 0; i < mTableAreaSectionList.size(); i++) {
            for (int j = 0; j < mTableAreaSectionList.get(i).getItemCount(); j++) {
                mTableAreaSectionList.get(i).getItemAt(j).setChecked(false);
            }
        }
        mAdapter.setData(mTableAreaSectionList);
    }


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

    @OnClick(R2.id.btn_modify_serviceCharge)
    void onClickModifyServiceCharge() {
        String ids = getSelectedIds();
        if (TextUtils.isEmpty(ids)) {
            showMessage("請選擇餐檯");
            return;
        }
        showEditTextDialog(mActivity, "批量修改服務費", "請輸入服務費");
    }

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

    private String getSelectedIds() {
        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;
    }

    private List<TableRequest.UpdateServiceCharge> getModifyServiceChargeList(double modifyServiceCharge) {
        List<TableRequest.UpdateServiceCharge> updateServiceCharges = new ArrayList<>();
        for (int i = 0; i < mTableList.size(); i++) {
            TableItem tableItem = mTableList.get(i);
            if (tableItem.isChecked()) {
                TableRequest.UpdateServiceCharge updateServiceCharge = new TableRequest.UpdateServiceCharge();
                updateServiceCharge.setId(tableItem.getId());
                updateServiceCharge.setServiceCharge(modifyServiceCharge);
                updateServiceCharges.add(updateServiceCharge);
            }
        }
        return updateServiceCharges;
    }

    public void showEditTextDialog(Activity context, String title, String placeholder) {
        final QMUIDialog.EditTextDialogBuilder dialogBuilder = new QMUIDialog.EditTextDialogBuilder(context);
        dialogBuilder.setTitle(title);
        dialogBuilder.setPlaceholder(placeholder);
        dialogBuilder.setInputType(InputType.TYPE_CLASS_NUMBER);
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            CharSequence text = dialogBuilder.getEditText().getText();
            if (text != null && text.length() > 0) {
                mActivity.updateTableServiceCharge(getModifyServiceChargeList(Double.parseDouble(text.toString())));
            } else {
                showMessage("請輸入服務費比例");
            }
        });
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    @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 View.OnClickListener onRetryClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //重新加載
            mActivity.queryAreas(null);
            mActivity.queryTables(null);
        }
    };

    @Override
    public void showEmptyView(boolean isSuccess, int size, Throwable t) {
        if (t != null) {
            if (t instanceof UnknownHostException) {
                //沒有網絡
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof SocketTimeoutException) {
                //請求超時
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
                //數據解析錯誤
                mEmptyView.show(false, getResources().getString(R.string.response_error_data_parsing_error), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            } else {
                //其他error
                mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            }
            mSectionLayout.setVisibility(View.INVISIBLE);
            return;
        }
        if (!isSuccess) {
            mEmptyView.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), null, getResources().getString(R.string.emptyView_mode_desc_retry), onRetryClickListener);
            mSectionLayout.setVisibility(View.INVISIBLE);
            return;
        }
        if (size == 0) {
            mEmptyView.show(getResources().getString(R.string.emptyView_mode_desc_double), null);
            mSectionLayout.setVisibility(View.INVISIBLE);
            return;
        }
        mEmptyView.hide();
        mSectionLayout.setVisibility(View.VISIBLE);
    }


    private void initRecycleScrollListener() {
        mSectionLayout.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if(isRadioEdit){
                    mActivity.onPauseRefreshTableData();
                    return;
                }
                switch (newState) {
                    case SCROLL_STATE_IDLE://停止滚动
                        if (mActivity != null ) {
                            mActivity.onStartRefreshTableData();
                        }
                        break;
                    case SCROLL_STATE_DRAGGING://正在被外部拖拽,一般为用户正在用手指滚动
                    case SCROLL_STATE_SETTLING://自动滚动开始
                        if (mActivity != null) {
                            mActivity.onPauseRefreshTableData();
                        }
                        break;
                }
            }
        });
        mSectionLayout.getRecyclerView().setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(isRadioEdit){
                    mActivity.onPauseRefreshTableData();
                    return false;
                }
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE: //用户滑动 先停止刷新餐台数据
                        if (mActivity != null) {
                            mActivity.onPauseRefreshTableData();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (mActivity != null) {
                            mActivity.onStartRefreshTableData();
                        }
                        //用户手抬起是 继续刷新餐台数据
                        break;
                }
                return false;
            }
        });
    }

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

    public boolean isRadioEdit() {
        return isRadioEdit;
    }

    @Override
    public List<TableItem> getTableList() {
        return mTableList;
    }
}
