package com.cooleshow.teacher.ui.course;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

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

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineVideoCourseAdapter;
import com.cooleshow.teacher.bean.MineVideoCourseListBean;
import com.cooleshow.teacher.bean.VideoCourseListBean;
import com.cooleshow.teacher.contract.MineVideoCourseContract;
import com.cooleshow.teacher.databinding.FragmentMineVideoCourseBinding;
import com.cooleshow.teacher.presenter.course.MineVideoCoursePresenter;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

/**
 * 创建日期：2022/5/20 13:57
 *
 * @author Ryan
 * 类说明：
 */
public class MineVideoCourseFragment extends BaseMVPFragment<FragmentMineVideoCourseBinding, MineVideoCoursePresenter> implements MineVideoCourseContract.MineVideoCourseView, View.OnClickListener {

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_create:
                ARouter.getInstance()
                        .build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, WebConstants.TEACHER_VIDEO_CREATE)
                        .navigation();

                break;
            case R.id.tv_open:
                if (mViewBinding.tvOpen.getText().toString().equals("去认证")) {
                    ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
                            .withString(WebConstants.WEB_URL, WebConstants.TEACHER_CERT)
                            .navigation();
                }

                break;
        }
    }

    public static MineVideoCourseFragment newInstance(String auditStatus) {
        Bundle args = new Bundle();
        MineVideoCourseFragment fragment = new MineVideoCourseFragment();
        args.putString("auditStatus", auditStatus);
        fragment.setArguments(args);
        return fragment;
    }

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

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

    private String auditStatus = "";
    private MineVideoCourseAdapter mineVideoCourseAdapter;

    @Override
    protected void initView(View rootView) {
        auditStatus = getArguments().getString("auditStatus");
        RecyclerView rvAddress = mViewBinding.recyclerView;
        LinearLayoutManager manager = new GridLayoutManager(getContext(), 2);
        rvAddress.setLayoutManager(manager);
        mineVideoCourseAdapter = new MineVideoCourseAdapter();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View emptyLayout = inflater.inflate(R.layout.empty_mine_video_course, null);
        TextView tv_create = emptyLayout.findViewById(R.id.tv_create);
        TextView tvEmptyHint = emptyLayout.findViewById(R.id.tv_empty_hint);
        if (TextUtils.equals(auditStatus, "PASS")) {
            tvEmptyHint.setText("您尚未创建视频课");
        } else if (TextUtils.equals(auditStatus, "DOING")) {
            tvEmptyHint.setText("暂无审核中视频课程");
        } else if (TextUtils.equals(auditStatus, "UNPASS")) {
            tvEmptyHint.setText("暂无审核失败视频课程");
        }
        tv_create.setOnClickListener(this);
        mineVideoCourseAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(mineVideoCourseAdapter);
        mViewBinding.tvOpen.setOnClickListener(this);
        mineVideoCourseAdapter.setOnItemClickListener((adapter, view, position) -> {
            VideoCourseListBean.RowsBean item = (VideoCourseListBean.RowsBean) adapter.getItem(position);
            if (TextUtils.equals(auditStatus, "UNPASS")) {
                //审核失败的跳转编辑页面
                ARouter.getInstance()
                        .build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, String.format(WebConstants.TEACHER_VIDEO_EDIT, item.id))
                        .navigation();
            } else {
                ARouter.getInstance()
                        .build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, WebConstants.TEACHER_VIDEO_DETAIL + "?groupId=" + item.id)
                        .navigation();
            }
        });
    }

    private int currentPage;

    @Override
    protected void initData() {
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryCourse(true);
        });
        mineVideoCourseAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                currentPage++;
                queryCourse(false);
            } else {
                mineVideoCourseAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
        currentPage = 1;
        queryCourse(true);
    }

    private boolean hasNext = true;

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

    private void queryCourse(boolean isLoading) {
        presenter.queryVideoCourseGroup(isLoading, currentPage, auditStatus);
    }

    @Override
    public void queryVideoCourseGroupSuccess(int page, VideoCourseListBean data) {
        if (isDetached()) {
            return;
        }
        if (data != null) {
            if (page == 1) {
                mViewBinding.refreshLayout.finishRefresh();
                mineVideoCourseAdapter.getData().clear();
                mineVideoCourseAdapter.notifyDataSetChanged();
                if (data.rows != null && data.rows.size() > 0) {
                    checkHasNext(data.rows.size());
                    mineVideoCourseAdapter.setNewInstance(data.rows);
                }
            } else {
                if (data.rows != null && data.rows.size() > 0) {
                    mineVideoCourseAdapter.getLoadMoreModule().loadMoreComplete();
                    mineVideoCourseAdapter.addData(data.rows);
                    checkHasNext(data.rows.size());
                } else {
                    mineVideoCourseAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }

        }
    }

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

    @Override
    public void queryVideoCourseGroupError(int page) {
        if (isDetached()) {
            return;
        }
        if (page == 1) {
            mViewBinding.refreshLayout.finishRefresh();
        } else {
            if (mineVideoCourseAdapter != null) {
                currentPage--;
                mineVideoCourseAdapter.getLoadMoreModule().loadMoreFail();
            }
        }
    }

    @Override
    public void getTeacherInfoSuccess(TeacherUserInfo teacherUserInfo) {
        if (TextUtils.equals(teacherUserInfo.entryStatus, TeacherInfoConstants.ENTRY_STATUS_DOING)) {
            //入驻审核中
            mViewBinding.refreshLayout.setVisibility(View.GONE);
            mViewBinding.clEmptyLiveFlag.setVisibility(View.VISIBLE);
            mViewBinding.tvEmptyHint.setText("达人认证审核中！");
            mViewBinding.tvOpen.setVisibility(View.GONE);
        } else if (TextUtils.equals(teacherUserInfo.entryStatus, TeacherInfoConstants.ENTRY_STATUS_PASS)) {
            //入驻审核通过
            mViewBinding.refreshLayout.setVisibility(View.VISIBLE);
            mViewBinding.clEmptyLiveFlag.setVisibility(View.GONE);
            currentPage = 1;
            queryCourse(true);
        } else {
            //未通过或者未申请
            mViewBinding.refreshLayout.setVisibility(View.GONE);
            mViewBinding.clEmptyLiveFlag.setVisibility(View.VISIBLE);
            mViewBinding.tvEmptyHint.setText("您还没有完成达人认证\n认证后才可创建视频课哦~");
            mViewBinding.tvOpen.setVisibility(View.VISIBLE);
            mViewBinding.tvOpen.setText("去认证");
        }

    }
}
