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

import android.content.Intent;
import android.graphics.Color;
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.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;

import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.manager.R2;
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.model.bean.request.AreaRequest;
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.ui.recylcler.decorator.DividerItemDecoration;
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.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.gingersoft.gsa.cloud.manager.di.component.DaggerAreaListComponent;
import com.gingersoft.gsa.cloud.manager.mvp.contract.AreaListContract;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.AreaListPresenter;

import com.gingersoft.gsa.cloud.manager.R;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;
import com.yanzhenjie.recyclerview.touch.OnItemStateChangedListener;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

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

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

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/19/2020 12:26
 * <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 AreaListFragment extends BaseFragment<AreaListPresenter> implements AreaListContract.View {

    @BindView(R2.id.topbar)
    QMUITopBarLayout mTopBar;
    @BindView(R2.id.recycler_area)
    RecyclerView recycler_area;
    @BindView(R2.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R2.id.emptyView)
    QMUIEmptyView mEmptyView;

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

    private TableManageActivity mActivity;

    private AreaManageAdapter mAreaManageAdapter;
    private List<TableArea> mTableAreaList = new ArrayList<>();

    private boolean isRadioEdit;

    public static AreaListFragment newInstance() {
        AreaListFragment fragment = new AreaListFragment();
        return fragment;
    }

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

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

        initTopbar();
        initAdapter();
        initRefreshLayout();
        mActivity.queryAreas(null);
    }

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

    private void initTopbar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> killMyself());
        mTopBar.setBackgroundResource(R.color.theme_color);
        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();
            mAreaManageAdapter.setRadioEdit(isRadioEdit);
            mAreaManageAdapter.notifyDataSetChanged();
        });
    }

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

            }
        });
    }

    private void initAdapter() {
        mAreaManageAdapter = new AreaManageAdapter(mContext, mTableAreaList);
        recycler_area.setAdapter(mAreaManageAdapter);
        recycler_area.addItemDecoration(new DividerItemDecoration(_mActivity, LinearLayoutManager.VERTICAL));
        mAreaManageAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {
                start(AddAreaFragment.newInstance((TableArea) data));
            }
        });
    }

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

    public void deleteSuccess(){

    }

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

    @OnClick(R2.id.tv_add_area)
    void onClickAddArea() {
        startForResult(AddAreaFragment.newInstance(null), ADD_AREA_RESULT_SUCCESS);
    }

    @OnClick(R2.id.btn_all_select)
    void onClickAddSelect() {
        for (int i = 0; i < mTableAreaList.size(); i++) {
            mTableAreaList.get(i).setChecked(true);
        }
        mAreaManageAdapter.notifyDataSetChanged();
    }

    @OnClick(R2.id.btn_anti_select)
    void onClickAntiSelect() {
        for (int i = 0; i < mTableAreaList.size(); i++) {
            TableArea tableArea = mTableAreaList.get(i);
            tableArea.setChecked(!tableArea.isChecked());
        }
        mAreaManageAdapter.notifyDataSetChanged();
    }

    @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, "deleteArea", parameterTypes, parameters);
    }

    private String getDeleteIds() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < mTableAreaList.size(); i++) {
            TableArea tableArea = mTableAreaList.get(i);
            if (tableArea.isChecked()) {
                builder.append(tableArea.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.onBackPressed();
    }

    @Override
    public void setAdapter(DefaultAdapter adapter) {
        recycler_area.setAdapter(adapter);
    }


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