package com.cooleshow.teacher.ui.homepage;

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

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.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.helper.WebStartHelper;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.cooleshow.base.widgets.poplist.PopMenuBean;
import com.cooleshow.base.widgets.poplist.PopupListWindow;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.HomePageSheetMusicAdapter;
import com.cooleshow.teacher.bean.HomePageSheetMusicListBean;
import com.cooleshow.teacher.bean.QuerySubjectBean;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.teacher.contract.SheetMusicPageContract;
import com.cooleshow.teacher.databinding.FragmentSheetMusicPageLayoutBinding;
import com.cooleshow.teacher.presenter.homePage.SheetMusicPagePresenter;
import com.cooleshow.usercenter.helper.UserHelper;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

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

/**
 * Author by pq, Date on 2022/5/9.
 * 老师个人主页->曲谱列表
 */
public class SheetMusicPageFragment extends BaseMVPFragment<FragmentSheetMusicPageLayoutBinding, SheetMusicPagePresenter> implements SheetMusicPageContract.SheetMusicPageView, View.OnClickListener {

    private HomePageSheetMusicAdapter mAdapter;
    private int currentPage = 1;
    private boolean hasNext = true;
    private EmptyViewLayout mEmptyView;
    private View mCertTipView;
    private List<QuerySubjectBean> subjectBeanList = new ArrayList<>();
    private int currentSubjectId = 0;
    private String mIdNames;
    private String teacherCertStatus = TeacherInfoConstants.ENTRY_STATUS_UNPAALY;

    @Override
    protected void initView(View rootView) {
        mViewBinding.viewUploadBg.setOnClickListener(this);
        presenter.querySubjectItem();
    }

    @Override
    protected void initData() {
        mAdapter = new HomePageSheetMusicAdapter(R.layout.item_home_page_sheet_music_layout);
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            queryList(true);
        });

        mAdapter.getLoadMoreModule().setOnLoadMoreListener(() -> {
            //上拉加载
            if (hasNext) {
                currentPage++;
                queryList(false);
            } else {
                mAdapter.getLoadMoreModule().loadMoreEnd();
            }
        });
        mViewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mViewBinding.recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                HomePageSheetMusicListBean.RowsBean rowsBean = mAdapter.getData().get(position);
                if (rowsBean != null) {
                    ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_ACCOMPANY_HTML)
                            .withString("url", String.format(WebConstants.SCORE_DETAIL_PAGE, rowsBean.id))
                            .withBoolean("isHideTitle", true)
                            .withBoolean("statusBarTextColor", true)
                            .withBoolean("isOpenLight", true)
                            .withInt("orientation", 0)
                            .navigation();
                }
            }
        });
    }

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

    private void checkCertStatus() {
        if (mViewBinding == null) {
            return;
        }
        String teacherCertificationStatus = UserHelper.getTeacherCertificationStatus();
        if (TextUtils.equals(teacherCertificationStatus, TeacherInfoConstants.ENTRY_STATUS_PASS)) {
            mViewBinding.groupContent.setVisibility(View.VISIBLE);
            mViewBinding.searchView.setOnLeftClickListener(v -> {
                selectVocalPart();
            });
            mViewBinding.searchView.setOnSearchListener(v -> {
                musicSearch();
            });
            queryList(true);
            if (mCertTipView != null) {
                mCertTipView.setVisibility(View.GONE);
            }
        } else {
            mViewBinding.groupContent.setVisibility(View.GONE);
            if (mCertTipView == null) {
                mCertTipView = mViewBinding.vsNoCert.inflate();
                mCertTipView.findViewById(R.id.tv_go_cert).setOnClickListener(this);
            } else {
                mCertTipView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 乐谱搜索
     */
    private void musicSearch() {
        mIdNames = mViewBinding.searchView.getSearchEdit().getText().toString();
        currentPage = 1;
        queryList(true);
    }

    /**
     * 选择声部
     */
    private void selectVocalPart() {
        if (subjectBeanList.size() == 0) {
            subjectBeanList.add(new QuerySubjectBean("声部", 0));
        }
        List<PopMenuBean> popList = new ArrayList<>();
        for (QuerySubjectBean bean : subjectBeanList) {
            PopMenuBean popMenuBean = new PopMenuBean();
            popMenuBean.setActionName(bean.name);
            popList.add(popMenuBean);
        }
        initCoursePop(mViewBinding.searchView, popList, position -> {
            QuerySubjectBean bean = subjectBeanList.get(position);
            currentSubjectId = bean.id;
            currentPage = 1;
            mViewBinding.searchView.getLeftText().setText(bean.name);
            queryList(true);
        });
    }

    /**
     * 选择声部pop
     *
     * @param targetView
     * @param popList
     * @param listener
     */
    private void initCoursePop(View targetView, List<PopMenuBean> popList, PopupListWindow.PopupListListener listener) {
        PopupListWindow popWindow = new PopupListWindow(getContext());
        popWindow.showListPop(targetView, popList, position -> listener.onPopupListClick(position));
    }

    private void queryList(boolean isShowLoading) {
        presenter.getSheetMusicList(isShowLoading, currentPage, mIdNames, String.valueOf(currentSubjectId));
    }

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

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

    /**
     * 获取乐谱列表
     *
     * @param page
     * @param sheetMusicListBean
     */
    @Override
    public void getSheetMusicListSuccess(int page, HomePageSheetMusicListBean sheetMusicListBean) {
        if (isDetached()) {
            return;
        }
        if (sheetMusicListBean != null) {
            if (page == 1) {
                //第一页
                mViewBinding.refreshLayout.finishRefresh();
                if (mAdapter != null) {
                    mAdapter.getData().clear();
                    mAdapter.notifyDataSetChanged();
                    if (sheetMusicListBean.rows != null && sheetMusicListBean.rows.size() > 0) {
                        checkHasNext(sheetMusicListBean.rows.size());
                        mAdapter.setNewInstance(sheetMusicListBean.rows);
                    } else {
                        showEmptyView();
                    }
                }
            } else {
                //加载更多
                if (mAdapter != null) {
                    if (sheetMusicListBean.rows != null && sheetMusicListBean.rows.size() > 0) {
                        mAdapter.getLoadMoreModule().loadMoreComplete();
                        checkHasNext(sheetMusicListBean.rows.size());
                        mAdapter.addData(sheetMusicListBean.rows);
                    } else {
                        mAdapter.getLoadMoreModule().loadMoreEnd();
                    }
                }
            }
        }
    }

    private void showEmptyView() {
        if (mEmptyView == null) {
            mEmptyView = new EmptyViewLayout(getContext());
        }
        mEmptyView.setContent(com.cooleshow.base.R.drawable.icon_empty_content, "暂无曲谱~");
        mAdapter.setEmptyView(mEmptyView);
    }


    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }


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

    @Override
    public void querySubjectItemSuccess(List<QuerySubjectBean> data) {
        subjectBeanList.clear();
        subjectBeanList.add(new QuerySubjectBean("声部", 0));
        subjectBeanList.addAll(data);
    }

    /**
     * 设置音乐人认证状态
     *
     * @param
     */
    public void setMusicPersonCertStatus(String entryStatus) {
        if (!TextUtils.equals(this.teacherCertStatus, entryStatus)) {
            this.teacherCertStatus = entryStatus;
            checkCertStatus();
            return;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_go_cert) {
            //去认证音乐人
            WebStartHelper.startCertPage();
            return;
        }
        if (v.getId() == R.id.view_upload_bg) {
            //上传乐谱
            WebStartHelper.startUploadSheetMusicPage();
        }
    }
}
