import { cycleProgress, quotaProgress, randomProgress } from '@/api/anslysis';
import { getSurveysDetail } from '@/api/design';
import { getSurveysPage } from '@/api/home';
import { surveyAnalysis } from '@/api/survey';
import { ref, type Ref } from 'vue';

// 异步函数获取数据
function fetchSurveys({ page = 1, perPage = 3 } = {}) {
  const surveys = ref<SurveyItem[]>([]);

  const params = {
    page: page,
    per_page: perPage,
    group_id: 0
  };

  getSurveysPage(params).then(({ data }) => {
    if (data.code !== 0) return;
    surveys.value = data.data;
  });

  return {
    surveys
  };
}

/**
 * 通过 sn 获取单个问卷的数据
 * @param sn {string}
 * @returns { {currentSurvey: Ref<SurveyItem> }}
 */
function fetchSingleSurvey(sn: string) {
  const currentSurvey = ref<SurveyItem>();

  getSurveysDetail(sn).then(({ data }) => {
    if (data.code !== 0) return;
    currentSurvey.value = data.data;
  });
  return { currentSurvey };
}

function useFetchAnalysis(sn: string) {
  const questionAnalysis = ref();

  surveyAnalysis(sn).then(({ data }) => {
    questionAnalysis.value = data.data;
  });

  return {
    questionAnalysis
  };
}

function fetchLogicInfo(sn: string) {
  // 用于控制 loading 状态
  const loading = ref(false);
  const quota = ref<any[]>([]);
  const cycle = ref<any[]>([]);
  const random = ref<any[]>([]);

  // 获取逻辑配额相关数据
  let response = quotaProgress(sn).then(({ data }) => {
    quota.value = data.data;
  });

  // 获取循环配额相关数据
  response = cycleProgress(sn).then(({ data }) => {
    cycle.value = data.data.cycle_progress;
  });

  response = randomProgress(sn).then(({ data }) => {
    random.value = data.data.randomProgress;
  });

  loading.value = false;

  return {
    loading,
    quota,
    cycle,
    random
  };
}

export { fetchSurveys, fetchSingleSurvey, useFetchAnalysis, fetchLogicInfo };
