import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { AnswerApi } from '@/views/Survey/views/Preview/js/api';
import { getLanguage } from '@/views/Survey/views/Preview/js/language';

export const useQuestionStore = defineStore('questionStore', () => {
  const currentSn = ref<string>('');

  const questionsData = ref();

  // 是否是模板模式
  const isTemplate = ref<boolean>(true);
  // styleInfo 主题样式
  const styleInfo = computed(() => questionsData.value?.survey?.style || {});
  // 当前页数
  const page = ref(1);
  // 分页
  const pages = computed(() => questionsData.value?.answer?.pages || []);
  // 加载
  const loading = ref(false);
  // 上一页时的加载状态
  const prevLoading = ref(false);
  // 分页计时器
  const localPageTimer = ref({});
  // 当前页问卷
  const questions = computed(() => {
    if (isTemplate.value) return questionsData.value?.questions;
    const currentPages = pages.value[page.value - 1] || [];
    return (questionsData.value?.questions || []).filter((quetion: any) =>
      currentPages.find((index: any) => quetion.question_index === index)
    );
  });

  // 答题之后的字段，应该是判断获取对应的字体
  const translatedText = computed(() => questionsData.value.language || {});
  // 是否显示分页器
  const showPage = computed(() => {
    return ![102, 104, 105, 201].includes(questions.value[0]?.question_type);
  });

  // 作用未知, 应该是 language
  const l = ref({});
  // 主题颜色
  const themeColor = ref({});

  // 开始更新数据
  getQuestions();

  // 更新数据
  async function getQuestions() {
    const _url = new URL(location.href).pathname;
    const urlParamSearch = new URL(location.href).searchParams;
    let { data } = await AnswerApi.getQuetions({
      id: urlParamSearch.get('sn'),
      data: {
        is_preview: _url.includes('templatePreview') ? 0 : 1,
        is_template: _url.includes('templatePreview') ? 1 : 0,
        // is_template: urlParamSearch.get('is_template') || 0,
        source: urlParamSearch.get('source') ?? ''
      }
    });
    data = data.data;
    // 多语言
    data.languageType = [
      data?.survey?.style?.is_en_tips ? 'en' : '',
      data?.survey?.style?.is_cn_tips ? 'zh' : ''
    ].filter((i) => !!i);
    l.value = getLanguage(data.languageType);
    // console.log(`l value:`, l.value);
    data.language = l.value;
    questionsData.value = data;
    currentSn.value = urlParamSearch.get('sn') || '';
  }

  return {
    fetchQuestions: getQuestions,
    currentSn,
    questionsData,
    styleInfo,
    page,
    pages,
    translatedText,
    l,
    themeColor,
    loading,
    prevLoading,
    localPageTimer,
    questions,
    showPage,
    isTemplate
  };
});
