import { surveyAnalysis } from '@/api/survey';
import { ref } from 'vue';
import { analysisInsights, checkAnalysisStatus, getAnalysis } from '@/api/anslysis/aiInsight';

const currentSn = ref<string>('');
const aiAnalysisData = ref();
type AiInsightType = {
  visible: boolean;
  timer: NodeJS.Timeout | undefined;
  message: string;
  info: string;
};

// ai 智能洞察
export const aiInsightsConfig = ref<AiInsightType>({
  visible: false,
  timer: undefined,
  message: '',
  info: ''
});

const params: AnalysisParam = {
  page: 1,
  per_page: 30,
  source: 1
};

export async function postAnalysis(sn: string) {
  let code;
  let message;

  aiInsightsConfig.value.visible = true;
  analysisInsights(sn)
    .then((res) => {
      code = res.code;
      message = res.message;
    })
    .catch((e) => {
      aiInsightsConfig.value.info = e.data.message;
    });

  //   此时正在进行 ai 洞察
  if (code === 10015) aiInsightsConfig.value.message = message;

  if (!aiInsightsConfig.value.timer) {
    // 每 1 s 检查一次是否分析完成
    aiInsightsConfig.value.timer = setInterval(async () => {
      const { code, data } = await checkAnalysis(sn);

      // 如果状态正常且标记成功，清除 timer 内容
      if (code === 0 && data.status === 1) {
        clearInterval(aiInsightsConfig.value.timer);
        //   获取洞察结果
        const { data } = await getAnalysis(sn);

        aiAnalysisData.value = data;
        aiInsightsConfig.value.message = data.other.overall_conclusion;
        aiInsightsConfig.value.visible = false;
      } else if (data.status === 2) {
        //   标记失败， 后续增加处理
      }
    }, 1000);
  }
}

export async function checkAnalysis(sn: string) {
  const { data } = await checkAnalysisStatus(sn, 2);
  return data;
}

export { aiAnalysisData, currentSn };
export { useFetchAnalysis } from '@/hooks/request/useSurvey';
