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

import useLoading from '@/hooks/loading';

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

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

type SelectConfigValue = string | SelectConfigItem;

const defaultTransform = (
  data: Array<{ id: number; name: string }>
): OptionListItem[] => {
  return data.map((item) => ({
    value: item.id,
    label: item.name,
  }));
};

const selectConfig: Record<string, SelectConfigValue> = {
  // 问题卷分类
  problemType: '/api/admin/exam/problem/type/list',
  // 打回卷分类
  rejectType: '/api/admin/exam/reject/type/find',
};
export type SelectType = keyof typeof selectConfig;

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, any>>);
      } else {
        optionList.value = defaultTransform(res as Array<Record<string, any>>);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  return {
    loading,
    optionList,
    search,
  };
}
