import {
  DictType,
  GlobalDict,
  getGlobalDict,
  upload,
  UploadData,
} from "@/api/common";
import { getSession } from "@/utils";
import isEmpty from "lodash/isEmpty";
import { defineStore } from "pinia";
import { zhdd_plan_type, zhdd_incident_status, zhdd_incident_source, zhdd_org_upload, zhdd_resource, zhdd_incident_type, zhdd_incident_level } from "./mock";

export type GlobalDictStore = {
  [key in DictType]?: GlobalDict[];
};

export interface CommonStateType {
  globalDict: GlobalDictStore;
  loading: boolean;
  uploading: boolean;
  uploadFiles: UploadData[];
  isclick:boolean;
}

export interface CommonActionsType {
  toggleLoading(): void;
  getGlobalDict(dictType: DictType): void;
  upload(file: File): void;
}

export default defineStore<"common", CommonStateType, {}, CommonActionsType>(
  "common",
  {
    state: () => ({
      globalDict: {
        zhdd_incident_level:
          getSession<GlobalDict[]>("zhdd_incident_level") ?? [],
        zhdd_incident_source:
          getSession<GlobalDict[]>("zhdd_incident_source") ?? [],
        zhdd_incident_status:
          getSession<GlobalDict[]>("zhdd_incident_status") ?? [],
        zhdd_incident_type:
          getSession<GlobalDict[]>("zhdd_incident_type") ?? [],
        zhdd_org_upload: getSession<GlobalDict[]>("zhdd_org_upload") ?? [],
        zhdd_plan_type: getSession<GlobalDict[]>("zhdd_plan_type") ?? [],
        zhdd_resource: getSession<GlobalDict[]>("zhdd_resource") ?? [],
      },
      loading: false,
      uploading: false,
      uploadFiles: [],
      isclick:false,
    }),
    actions: {
      toggleLoading() {
        this.loading = !this.loading;
      },
      async getGlobalDict(params) {
         if (!isEmpty(this.globalDict[params])) return;
         try {
           this.toggleLoading();
           const { data } = await getGlobalDict(params);
           this.globalDict[params] = data;
         } finally {
           this.toggleLoading();
         }
      },
      async upload(params) {
        try {
          this.uploading = true;
          const { data } = await upload(params);
          this.uploadFiles.push(data);
        } finally {
          this.uploading = false;
        }
      },
    },
  }
);
