package com.cooleshow.teacher.ui.live;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.ui.fragment.BaseFragment;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.LiveListAdapter;
import com.cooleshow.teacher.bean.LiveListBean;
import com.cooleshow.teacher.bean.LivePlayBackDataBean;
import com.cooleshow.teacher.contract.LiveListContract;
import com.cooleshow.teacher.databinding.FragmentLiveListOnLayoutBinding;
import com.cooleshow.teacher.presenter.live.LiveListPresenter;
import com.cooleshow.teacher.ui.work.HomeWorkFragment;
import com.cooleshow.teacher.widgets.dialog.LivePlaybackDialog;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * Author by pq, Date on 2022/7/7.
 * 直播中
 */
public class LiveListFragment extends BaseMVPFragment<FragmentLiveListOnLayoutBinding, LiveListPresenter> implements LiveListContract.LiveListView {
    public static final String LIVE_STATUS_TAG_KEY = "live_status_tag_key";
    private String mLiveTag;
    private int currentPage = 1;
    private LiveListAdapter mLiveListAdapter;
    private boolean hasNext = true;
    private EmptyViewLayout mEmptyView;
    private LivePlaybackDialog mLivePlaybackDialog;
    private Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            getData(true);
        }
    };

    public static LiveListFragment newInstance(String liveStatusTag) {
        Bundle args = new Bundle();
        LiveListFragment liveListFragment = new LiveListFragment();
        args.putString(LIVE_STATUS_TAG_KEY, liveStatusTag);
        liveListFragment.setArguments(args);
        return liveListFragment;
    }

    @Override
    protected FragmentLiveListOnLayoutBinding getLayoutView() {
        return FragmentLiveListOnLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected LiveListPresenter createPresenter() {
        return new LiveListPresenter();
    }

    @Override
    protected void initView(View rootView) {
        if (getArguments() != null) {
            mLiveTag = getArguments().getString(LIVE_STATUS_TAG_KEY);
        }

    }

    @Override
    protected void initData() {
        mLiveListAdapter = new LiveListAdapter();
        setEmptyView();
        mViewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mViewBinding.recyclerView.setAdapter(mLiveListAdapter);


        mLiveListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (position < mLiveListAdapter.getData().size()) {
                    LiveListBean.RowsBean rowsBean = mLiveListAdapter.getData().get(position);
                    if (view.getId() == R.id.ll_enter_live) {
                        //进入直播间
                        TeacherLiveRoomActivity.start(getContext(), rowsBean.roomUid);
                        return;
                    }
                    if (view.getId() == R.id.tv_look_playback) {
                        //查看回放
                        getLivePlaybackData(rowsBean.roomUid);
                        return;
                    }
                }
            }
        });

        mViewBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                getData(true);
            }
        });
        mLiveListAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    getData(false);
                } else {
                    mLiveListAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mViewBinding.recyclerView != null) {
            //直播结束接口可能存在处理延时的问题,导致直播中的状态未刷新,先延时请求这个接口
            mViewBinding.recyclerView.postDelayed(refreshRunnable, 100);
        }
    }

    private void showPlayBackDialog(ArrayList<LivePlayBackDataBean> datas) {
        if (mLivePlaybackDialog == null) {
            mLivePlaybackDialog = new LivePlaybackDialog(getContext());
        }
        if (!mLivePlaybackDialog.isShowing()) {
            mLivePlaybackDialog.show();
            mLivePlaybackDialog.setData(datas);
        }
    }

    private void getData(boolean isShowLoading) {
        if (presenter != null) {
            presenter.getLiveListData(isShowLoading, mLiveTag, currentPage);
        }
    }

    private void getLivePlaybackData(String roomId) {
        if (TextUtils.isEmpty(roomId)) {
            return;
        }
        if (presenter != null) {
            presenter.getLivePlaybackData(roomId);
        }
    }

    @Override
    public void getListDataSuccess(int page, LiveListBean liveListBean) {
        if (isDetached()) {
            return;
        }
        if (liveListBean != null) {
            if (page == 1) {
                //第一页
                mViewBinding.refreshLayout.finishRefresh();
                if (mLiveListAdapter != null) {
                    mLiveListAdapter.getData().clear();
                    mLiveListAdapter.notifyDataSetChanged();
                    if (liveListBean.rows != null && liveListBean.rows.size() > 0) {
                        checkHasNext(liveListBean.rows.size());
                        mLiveListAdapter.setNewInstance(liveListBean.rows);
                    }
                }
            } else {
                //加载更多
                if (mLiveListAdapter != null) {
                    if (liveListBean.rows != null && liveListBean.rows.size() > 0) {
                        mLiveListAdapter.getLoadMoreModule().loadMoreComplete();
                        checkHasNext(liveListBean.rows.size());
                        mLiveListAdapter.addData(liveListBean.rows);
                    } else {
                        mLiveListAdapter.getLoadMoreModule().loadMoreEnd();
                    }
                }
            }
        }
    }

    @Override
    public void getPlaybackDataSuccess(ArrayList<LivePlayBackDataBean> datas) {
        if (isDetached()) {
            return;
        }
        if (datas != null && datas.size() > 0) {
            showPlayBackDialog(datas);
        } else {
            ToastUtil.getInstance().showShort("暂无回放");
        }
    }


    /**
     * 显示空视图
     */
    private void setEmptyView() {
        if (mEmptyView == null) {
            mEmptyView = new EmptyViewLayout(getContext());
        }
        mEmptyView.setContent(com.cooleshow.base.R.drawable.icon_empty_content, "暂无内容~");
        mLiveListAdapter.setEmptyView(mEmptyView);
    }


    /**
     * 检查是否还有下一页
     *
     * @param dataSize
     */
    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }

    @Override
    public void onDestroy() {
        if (mViewBinding.recyclerView != null && refreshRunnable != null) {
            mViewBinding.recyclerView.removeCallbacks(refreshRunnable);
        }
        super.onDestroy();
    }
}
