import { defineStore } from "pinia";

export const useProjectInfoStore = defineStore("projectInfo", {
  state: () => ({
    projectInfo: null,
  }),
  getters: {
    getProjectInfo: (state) => state.projectInfo,
  },
  actions: {
    // 设置项目信息（增）
    setProjectInfo(data) {
      this.projectInfo = data;
      sessionStorage.setItem("projectFinalInfo", JSON.stringify(data));
    },
    // 更新项目信息的某个字段（改）
    updateProjectInfo(field, value) {
      if (this.projectInfo) {
        this.projectInfo[field] = value;
        sessionStorage.setItem(
          "projectFinalInfo",
          JSON.stringify(this.projectInfo),
        );
      }
    },
    // 批量更新项目信息（改）
    batchUpdateProjectInfo(updates) {
      if (this.projectInfo) {
        Object.assign(this.projectInfo, updates);
        sessionStorage.setItem(
          "projectFinalInfo",
          JSON.stringify(this.projectInfo),
        );
      }
    },
    // 获取项目信息（查）- 优先从 state 取，没有则从 sessionStorage 恢复
    loadProjectInfo() {
      if (this.projectInfo) return this.projectInfo;
      const raw = sessionStorage.getItem("projectFinalInfo");
      if (raw) {
        try {
          this.projectInfo = JSON.parse(raw);
          return this.projectInfo;
        } catch {
          return null;
        }
      }
      return null;
    },
    // 通过接口获取并保存项目信息（查 + 增）
    fetchProjectInfo(proxy, projectId) {
      return new Promise((resolve, reject) => {
        proxy.$post({
          url: "/api/project/getProjectFinalInfo",
          data: { id: projectId },
          callback: (data) => {
            this.setProjectInfo({ ...data, projectId: projectId - 0 });
            resolve(data);
          },
          error: () => {
            console.error("获取项目详情失败");
            reject(new Error("获取项目详情失败"));
          },
        });
      });
    },
    // 清除项目信息（删）
    clearProjectInfo() {
      this.projectInfo = null;
      sessionStorage.removeItem("projectFinalInfo");
    },
  },
});
