// src/stores/modules/common.ts
import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';

// 定义接口以明确数据结构
interface QuestionPage {
  page: number;
  pageId?: string; // 唯一 ID
}

interface QuestionsInfo {
  survey: {
    title: string;
    introduction: string;
    ip_number: number;
    is_ip_number: number;
    is_browser_number: number;
    browser_number: number;
    publish_number: number;
    is_time: number;
    start_time: string;
    end_time: string;
    last_question_index: number;
    is_one_page_one_question: number;
    is_publish_number: number;
  };
  logics: any[]; // 根据实际需求调整类型
  questions: QuestionPage[]; // 明确类型
  cycle_pages: null | number; // 根据实际需求调整类型
}

export const useCommonStore = defineStore('common', {
  state: (): { questionsInfo: QuestionsInfo } => ({
    questionsInfo: {
      survey: {
        title: '',
        introduction: '',
        ip_number: 1,
        is_ip_number: 1,
        is_browser_number: 1,
        browser_number: 1,
        publish_number: 1,
        is_time: 1,
        start_time: '',
        end_time: '',
        last_question_index: 0,
        is_one_page_one_question: 1,
        is_publish_number: 1
      },
      logics: [],
      questions: [], // 初始化为明确类型的空数组
      cycle_pages: null
    }
  }),
  actions: {
    async fetchQuestionInfo(questionInfo: string) {
      try {
        if (!questionInfo) return;

        const info = JSON.parse(questionInfo) as QuestionsInfo; // 类型断言
        if (info?.questions?.length) {
          info.questions.forEach((page: QuestionPage) => {
            // 使用 UUID 生成唯一 ID
            if (page?.page) {
              page.pageId = page.pageId || uuidv4();
            }
          });
        }
        this.setQuestionInfo(info);
      } catch (error) {
        console.error('Error fetching question info:', error);
      }
    },
    setQuestionInfo(questionInfo: Partial<QuestionsInfo>) {
      // 保持原有响应式引用，仅更新变化的部分
      this.questionsInfo = Object.assign({}, this.questionsInfo, questionInfo);

      // 对嵌套结构特殊处理（如数组需要保持引用）
      if (questionInfo.questions) {
        this.questionsInfo.questions = [...questionInfo.questions]; // 类型已明确，无需额外断言
      }
    }
  },
  getters: {
    getQuestionsInfo: (state): QuestionsInfo => state.questionsInfo
  }
});
