import axios from 'axios';
import { ref } from 'vue';

import useLoading from '@/hooks/loading';

const selectConfig = {
  // 卷型: subjectCode
  subjectPaperType: '/api/admin/subject/getPaperType',
  // 科目层次
  subjectLevel: '/api/admin/subject/level/list',
  // 学院
  college: '/api/admin/student/college/list',
  // 班级
  className: '/api/admin/student/className/list',
  // 考点
  examPoint: '/api/admin/student/examSite/list',
  // 专业类型
  subjectCategory: '/api/admin/student/category/list',
};

export type SelectType = keyof typeof selectConfig;

export interface OptionListItem {
  value: number;
  label: string;
}

export default function useSearch(type: SelectType) {
  const { loading, setLoading } = useLoading();
  const optionList = ref<OptionListItem[]>([]);

  async function search(params?: Record<string, any>) {
    if (!selectConfig[type]) {
      console.error('下拉列表类型错误！');
      return;
    }

    try {
      setLoading(true);
      const res = (await axios.post(
        selectConfig[type],
        {},
        { params }
      )) as string[];

      optionList.value = res.map((item) => ({
        value: item,
        label: item,
      }));
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  return {
    loading,
    optionList,
    search,
  };
}
