import { ref, onBeforeMount, computed } from 'vue';
import { useRoute } from 'vue-router';
import * as API from '@/api';

/**获取题目列表 */
export const useSubjectList = (type: ExerciseType.ListType) => {
	const subjectList = ref<any[]>([]); //题目列表
	const subjectTotal = ref(0); //题目总数
	const pageNum = ref(1); //当前请求页码
	const pageSize = ref(100); //当前请求每页数据
	const query = useRoute().query; //路由query参数
	onBeforeMount(async () => {
		const res = await API.getTopicList(
			{
				...query,
				pageNum: pageNum.value,
				pageSize: pageSize.value,
			},
			type !== 'free'
		);
		subjectList.value = res.list;
		subjectTotal.value = res.total;
	});
	//加载下一页数据
	const loadNewSubject = async () => {
		if (subjectList.value.length == subjectTotal.value) return;
		pageNum.value++;
		const res = await API.getTopicList(
			{
				...query,
				pageNum: pageNum.value,
				pageSize: pageSize.value,
			},
			type !== 'free'
		);
		subjectList.value = subjectList.value.concat(res.list);
	};
	const currentSubjectIndex = ref(0); //当前题目下标
	//当前题目内容
	const currentSubject = computed(() => {
		return subjectList.value[currentSubjectIndex.value];
	});
	return {
		subjectList,
		subjectTotal,
		loadNewSubject,
		currentSubject,
		currentSubjectIndex,
	};
};
