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.annotation.Nullable;
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.constants.TeacherInfoConstants;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineLiveCourseAdapter;
import com.cooleshow.teacher.bean.MineLiveCourseListBean;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.contract.MineLiveCourseContract;
import com.cooleshow.teacher.databinding.FragmentMineLiveCourseBinding;
import com.cooleshow.teacher.presenter.course.MineLiveCoursePresenter;
import com.cooleshow.usercenter.helper.UserHelper;
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/19 15:38
 *
 * @author Ryan
 * 类说明：
 */
public class MineLiveCourseFragment extends BaseMVPFragment<FragmentMineLiveCourseBinding, MineLiveCoursePresenter> implements MineLiveCourseContract.MineLiveCourseView, 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_LIVE_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();
                } else if (mViewBinding.tvOpen.getText().toString().equals("立即开通")) {
                    ARouter.getInstance()
                            .build(RouterPath.WebCenter.ACTIVITY_HTML)
                            .withString(WebConstants.WEB_URL, WebConstants.TEACHER_OPEN_LIVE)
                            .navigation();
                }

                break;
        }
    }

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

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

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

    private String type = "";
    private MineLiveCourseAdapter mineLiveCourseAdapter;

    @Override
    protected void initView(View rootView) {
        type = getArguments().getString("type");
        RecyclerView rvAddress = mViewBinding.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvAddress.setLayoutManager(manager);
        mineLiveCourseAdapter = new MineLiveCourseAdapter();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View emptyLayout = inflater.inflate(R.layout.empty_mine_live_course, null);
        TextView tv_create = emptyLayout.findViewById(R.id.tv_create);
        TextView tv_empty_hint = emptyLayout.findViewById(R.id.tv_empty_hint);
        tv_empty_hint.setText(getEmptyText());
        tv_create.setOnClickListener(this);
        mineLiveCourseAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(mineLiveCourseAdapter);
        mViewBinding.tvOpen.setOnClickListener(this);
        mineLiveCourseAdapter.setOnItemClickListener((adapter, view, position) -> {
            MineLiveCourseListBean.RowsBean item = (MineLiveCourseListBean.RowsBean) adapter.getItem(position);
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.TEACHER_LIVE_DETAIL + "?groupId=" + item.courseGroupId)
                    .navigation();
        });

    }

    private int currentPage;

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

    }

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

    private boolean hasNext = true;

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

    private void queryCourse(boolean isLoading) {
        presenter.queryPageCourseGroup(isLoading, currentPage, type);

    }

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

    }

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

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        if (isVisibleToUser && presenter != null) {
//            presenter.getTeacherUserInfo();
//        }
    }

    @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)) {
            //入驻审核通过
            UserHelper.saveTeacherOpenLiveFlag(teacherUserInfo.liveFlag);
            if (teacherUserInfo.liveFlag == 0) {
                //是否有直播权限 0 否 1 是
                mViewBinding.refreshLayout.setVisibility(View.GONE);
                mViewBinding.clEmptyLiveFlag.setVisibility(View.VISIBLE);
                mViewBinding.tvEmptyHint.setText("您尚未开通直播服务\n开通后即可创建直播课程");
                mViewBinding.tvOpen.setVisibility(View.VISIBLE);
                mViewBinding.tvOpen.setText("立即开通");
            } else {
                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("去认证");
        }

    }


    private String getEmptyText() {
        if (TextUtils.equals(type, "ING")) {
            //进行中
            return "暂无进行中直播课程";
        }
        if (TextUtils.equals(type, "NOT_SALE")) {
            //未开始
            return "暂无未上架直播课程";
        }
        if (TextUtils.equals(type, "APPLY")) {
            //申请中
            return "暂无销售中直播课程";
        }
        if (TextUtils.equals(type, "COMPLETE")) {
            //已完成
            return "暂无已完成直播课程";
        }
        if (TextUtils.equals(type, "CANCEL")) {
            //已取消
            return "暂无已取消直播课程";
        }
        return "暂无内容";
    }
}
