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

import useLoading from '@/hooks/loading';

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

interface SelectConfigItem {
  url: string;
  transform?: (data: Array<Record<string, string>>) => OptionListItem[];
}

type SelectConfigValue = string | SelectConfigItem;

const selectConfig: Record<string, SelectConfigValue> = {
  // 卷型: subjectCode
  subjectPaperType: '/api/admin/subject/getPaperType',
  // 科目层次
  subjectLevel: '/api/admin/subject/level/list',
  // 专业类型
  subjectCategory: '/api/admin/subject/category/list',
  // 学院
  college: '/api/admin/student/college/list',
  // 班级
  className: '/api/admin/student/className/list',
  // 考点
  examSite: '/api/admin/student/examSite/list',
  // 仲裁类型
  arbitrationType: '/api/admin/exam/arbitrate/status',
  // 人工确认类型
  manualConfirmType: {
    url: '/api/admin/exam/check/student/types',
    transform: (data: { value: string; name: string }[]) =>
      data.map((item) => ({
        value: item.value,
        label: item.name,
      })),
  },
};

export type SelectType = keyof typeof selectConfig;

// 默认的转换函数，用于处理 string[] 格式的数据
const defaultTransform = (data: string[]): OptionListItem[] => {
  return data.map((item) => ({
    value: item,
    label: item,
  }));
};

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

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

    // 统一处理配置格式
    const config: SelectConfigItem =
      typeof configValue === 'string' ? { url: configValue } : configValue;

    try {
      setLoading(true);
      const res = await axios.post(config.url, params);

      if (config.transform) {
        optionList.value = config.transform(
          res as Array<Record<string, string>>
        );
      } else {
        optionList.value = defaultTransform(res as string[]);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  return {
    loading,
    optionList,
    search,
  };
}
