package com.cooleshow.teacher.ui.score;

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

import androidx.annotation.NonNull;
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.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.helper.WebStartHelper;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineScoreAdapter;
import com.cooleshow.teacher.bean.MusicSheetListBean;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.teacher.contract.MineScoreContract;
import com.cooleshow.teacher.databinding.FragmentMineScoreBinding;
import com.cooleshow.teacher.presenter.score.MineScorePresenter;
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/20 17:00
 *
 * @author Ryan
 * 类说明：
 */
public class MineScoreFragment extends BaseMVPFragment<FragmentMineScoreBinding, MineScorePresenter> implements MineScoreContract.MineScoreView, View.OnClickListener {
    private String auditStatus = "";
    private String currentSubjectId = "";
    private String currentSearchStr = "";
//    private String musicianAuthStatus = TeacherInfoConstants.MUSICIAN_STATUS_UNPAALY;
    private MineScoreAdapter mineScoreAdapter;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_upload_score:
                WebStartHelper.startUploadSheetMusicPage();
                break;
        }
    }

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

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

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

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

    @Override
    protected void initView(View rootView) {
        auditStatus = getArguments().getString("auditStatus");
        if (TextUtils.isEmpty(auditStatus)) {
            auditStatus = "PASS";
        }
        RecyclerView rvAddress = mViewBinding.recyclerView;
        mViewBinding.llUploadScore.setOnClickListener(this);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvAddress.setLayoutManager(manager);
        mineScoreAdapter = new MineScoreAdapter();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View emptyLayout = inflater.inflate(R.layout.layout_empty_conent, null);
        ImageView im_empty_logo = emptyLayout.findViewById(R.id.im_empty_logo);
        im_empty_logo.setBackgroundResource(R.drawable.icon_empty_content);
        TextView tv_empty_hint = emptyLayout.findViewById(R.id.tv_empty_hint);
        tv_empty_hint.setText("暂无曲谱~");
        mineScoreAdapter.setEmptyView(emptyLayout);
        rvAddress.setAdapter(mineScoreAdapter);
        String teacherCertificationStatus = UserHelper.getTeacherCertificationStatus();
        switch (teacherCertificationStatus) {
            case TeacherInfoConstants.ENTRY_STATUS_PASS:
                //达人认证通过
                mViewBinding.llContent.setVisibility(View.VISIBLE);
                mViewBinding.clEmpty.setVisibility(View.GONE);
                break;
            case TeacherInfoConstants.ENTRY_STATUS_DOING:
                mViewBinding.llContent.setVisibility(View.GONE);
                mViewBinding.clEmpty.setVisibility(View.VISIBLE);
                mViewBinding.tvEmptyHint.setText("您已提交认证申请\n请耐心等待审核结果~");
                mViewBinding.gotoVerifyBtn.setVisibility(View.GONE);
                break;
            case TeacherInfoConstants.ENTRY_STATUS_UNPAALY:
                mViewBinding.llContent.setVisibility(View.GONE);
                mViewBinding.clEmpty.setVisibility(View.VISIBLE);
                mViewBinding.tvEmptyHint.setText(getString(R.string.go_cert_music_person_tip));
                mViewBinding.gotoVerifyBtn.setVisibility(View.VISIBLE);
                break;
            case TeacherInfoConstants.ENTRY_STATUS_UNPASS:
                mViewBinding.llContent.setVisibility(View.GONE);
                mViewBinding.clEmpty.setVisibility(View.VISIBLE);
                mViewBinding.tvEmptyHint.setText("您已提交认证申请未通过\n请重新提交~");
                mViewBinding.gotoVerifyBtn.setVisibility(View.VISIBLE);
                break;
        }
        mViewBinding.gotoVerifyBtn.setOnClickListener(v -> {
            WebStartHelper.startCertPage();
        });
        mineScoreAdapter.setOnItemClickListener((adapter, view, position) -> {
            List<MusicSheetListBean.RowsBean> data = mineScoreAdapter.getData();
            MusicSheetListBean.RowsBean rowsBean = data.get(position);
            if (TextUtils.equals(rowsBean.auditStatus, "UNPASS")) {
                ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, String.format(WebConstants.EDIT_SCORE_PAGE, rowsBean.id))
                        .navigation();
                return;
            }
            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();
        });

    }

    private int currentPage;

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

    private boolean hasNext = true;

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

    private void queryScore(boolean isLoading) {
        presenter.queryPageCourseGroup(isLoading, currentSubjectId, currentSearchStr, currentPage, auditStatus);
    }

    public void goSearch(String searchStr, String subjectId) {
        this.currentSubjectId = subjectId;
        this.currentSearchStr = searchStr;
        currentPage = 1;
        queryScore(true);
    }

    public void updateFilter(String searchStr, String subjectId) {
        this.currentSubjectId = subjectId;
        this.currentSearchStr = searchStr;
    }

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

    }

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