package com.tenlionsoft.oamodule.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hjq.toast.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.tenlionsoft.baselib.constant.LionActions;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.conver.RxTransformer;
import com.tenlionsoft.baselib.core.widget.base.BaseFragment;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
import com.tenlionsoft.baselib.utils.UserLgUtils;
import com.tenlionsoft.oamodule.R;
import com.tenlionsoft.oamodule.R2;
import com.tenlionsoft.oamodule.activity.meeting.MeetingDetailActivity;
import com.tenlionsoft.oamodule.adapter.MeetingMineApplyAdapter;
import com.tenlionsoft.oamodule.beans.MeetingRecordListBean;
import com.tenlionsoft.oamodule.beans.MeetingRoomRecordBean;
import com.tenlionsoft.oamodule.net.OAApi;

import org.jetbrains.annotations.NotNull;

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

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 作者: adam
 * 日期: 2022/4/14 - 17:27
 * 邮箱: itgaojian@163.com
 * 描述: 我发起的会议
 */
@Route(path = PathConfig.PATH_MODULE_OA_FRAGMENT_MINE_APPLY_MEETING)
public class MineApplyMeetingFragment extends BaseFragment {
    @BindView(R2.id.rlv_meeting)
    RecyclerView mRlvMeeting;
    @BindView(R2.id.pb_loading)
    ProgressBar mPbLoading;
    @BindView(R2.id.iv_empty_data)
    ImageView mIvEmptyData;
    @BindView(R2.id.tv_error_hint)
    TextView mTvErrorHint;
    @BindView(R2.id.ll_hint)
    LinearLayout mLlHint;
    @BindView(R2.id.srl_meeting)
    SmartRefreshLayout mSrlMeeting;
    private MeetingMineApplyAdapter mAdapter;
    private List<MeetingRoomRecordBean> mDatas;
    private int mCurrentPage = 1;
    private String mKeywords = "";
    private ActivityResultLauncher<Intent> mLauncher;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_mine_apply_meeting;
    }

    @Override
    protected void setDataToView(View dataView) {
        ButterKnife.bind(this, dataView);
        setStateView(STATE_SUCCESS);
        mSrlView.setEnableRefresh(false);
        mSrlView.setEnableLoadMore(false);
        refreshStateView(LionActions.STATE_LOAD);

        mSrlMeeting.setOnLoadMoreListener(v -> doLoadMore());
        mSrlMeeting.setOnRefreshListener(v -> doRefresh());
        mDatas = new ArrayList<>();
        mAdapter = new MeetingMineApplyAdapter(mActivity, mDatas);
        mRlvMeeting.setLayoutManager(new LinearLayoutManager(mActivity));
        mRlvMeeting.setAdapter(mAdapter);
        mAdapter.addOnItemClickListener(rowsBean -> {
            Intent intent = new Intent(mActivity, MeetingDetailActivity.class);
            intent.putExtra("id", rowsBean.getMeetingId());
            mLauncher.launch(intent);
        });
        doRefresh();
    }

    @Override
    public void onAttach(@androidx.annotation.NonNull @NotNull Context context) {
        super.onAttach(context);
        mLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (Activity.RESULT_OK == result.getResultCode()) {
                doRefresh();
            }
        });
    }

    /**
     * 加载更多
     */
    private void doLoadMore() {
        getDocumentList(mCurrentPage);
    }

    /**
     * 刷新
     */
    private void doRefresh() {
        mDatas.clear();
        mAdapter.setData(mDatas);
        getDocumentList(1);
    }

    /**
     * 获取文档列表
     */
    private void getDocumentList(int currentPage) {
        mCurrentPage = currentPage;
        RetrofitManager.getInstance()
            .create(OAApi.class)
            .getMineApplyMeetingList(mKeywords, mCurrentPage + "", UserLgUtils.getToken())
            .compose(RxTransformer.getTransformer())
            .subscribe(new Observer<MeetingRecordListBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull MeetingRecordListBean listBean) {
                    if (listBean.getRows() != null && listBean.getRows().size() > 0) {
                        ++mCurrentPage;
                        if (currentPage == 1) {
                            mDatas.clear();
                            mDatas.addAll(listBean.getRows());
                        } else {
                            mDatas.addAll(listBean.getRows());
                        }
                        refreshStateView(LionActions.STATE_SUCCESS);
                        mAdapter.notifyDataSetChanged();
                        mSrlMeeting.finishRefresh();
                        if (mDatas.size() >= listBean.getTotal()) {
                            mSrlMeeting.finishLoadMore();
                            mSrlMeeting.setNoMoreData(true);
                        } else {
                            mSrlMeeting.finishLoadMore();
                            mSrlMeeting.setNoMoreData(false);
                        }
                    } else {
                        if (currentPage > 1) {
                            mSrlMeeting.finishLoadMore();
                            mSrlMeeting.setNoMoreData(true);
                        } else {
                            if (TextUtils.isEmpty(mKeywords)) {
                                //无数据
                                refreshStateView(LionActions.STATE_EMPTY);
                            } else {
                                refreshStateView(LionActions.STATE_EMPTY);
                                ToastUtils.show("未查询到相关内容");
                            }
                        }
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    mSrlMeeting.finishLoadMore();
                    mSrlMeeting.finishRefresh();
                    ExceptionHandler.handleException(e);
                    refreshStateView(LionActions.STATE_ERROR);
                }

                @Override
                public void onComplete() {

                }
            });
    }

    private void refreshStateView(int state) {
        switch (state) {
            case LionActions.STATE_LOAD:
                mRlvMeeting.setVisibility(View.GONE);
                mLlHint.setVisibility(View.VISIBLE);
                mPbLoading.setVisibility(View.VISIBLE);
                mIvEmptyData.setVisibility(View.GONE);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("加载中...");
                break;
            case LionActions.STATE_EMPTY:
                mRlvMeeting.setVisibility(View.GONE);
                mLlHint.setVisibility(View.VISIBLE);
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mIvEmptyData.setImageResource(R.drawable.ic_empty_data);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("暂无数据");
                break;
            case LionActions.STATE_ERROR:
                mRlvMeeting.setVisibility(View.GONE);
                mLlHint.setVisibility(View.VISIBLE);
                mPbLoading.setVisibility(View.GONE);
                mIvEmptyData.setVisibility(View.VISIBLE);
                mIvEmptyData.setImageResource(R.drawable.ic_load_error);
                mTvErrorHint.setVisibility(View.VISIBLE);
                mTvErrorHint.setText("加载失败,请稍后重试");
                break;
            case LionActions.STATE_SUCCESS:
                mRlvMeeting.setVisibility(View.VISIBLE);
                mLlHint.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void loadMoreData() {

    }
}
