import { defineStore } from 'pinia';
import { store } from '@/store';
import { getSubjectList, getCategories } from '@/api/user';

export const useCatchStore = defineStore('catch-store', {
  state: () => ({
    bookVersionList: [] as any[], // 其它类型
    musicTypeList: [] as any[], // 乐谱分类
    subjectList: [] as any[] // 声部列表
  }),
  getters: {
    getBookVersion(): any[] {
      return this.bookVersionList;
    },
    getMusicCategories(): any[] {
      return this.musicTypeList;
    },
    getAllMusicCategories(): any[] {
      return [
        {
          name: '全部',
          id: null
        },
        ...this.musicTypeList
      ];
    },
    getSubjectList(): any[] {
      return this.subjectList;
    },
    getSubjectAllList(): any[] {
      return [
        {
          name: '全部',
          id: null
        },
        ...this.subjectList
      ];
    }
  },
  actions: {
    setBookVersion(books: any[]) {
      this.bookVersionList = books;
    },
    setMusicCategories(musics: any[]) {
      this.musicTypeList = musics;
    },
    setSubjects(subjects: any[]) {
      this.subjectList = subjects;
    },
    /**
     * 判断是否有声部数据，如不存在则获取声部列表
     * @returns Promise
     */
    async getSubjects() {
      try {
        // 判断是否存在声部数据
        if (this.getSubjectList && this.getSubjectList.length > 0) {
          return Promise.resolve();
        }
        const { data } = await getSubjectList({
          enableFlag: true,
          delFlag: 0,
          page: 1,
          rows: 999
        });

        this.setSubjects(data.rows || []);
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },
    /**
     * 判断是否有教材分类数据，如不存在则获取教材分类列表
     * @returns Promise
     */
    async getMusicSheetCategory() {
      try {
        // 判断是否存在声部数据
        if (this.getMusicCategories && this.getMusicCategories.length > 0) {
          return Promise.resolve();
        }
        const { data } = await getCategories({
          enable: true,
          page: 1,
          rows: 999
        });
        this.setMusicCategories(data.rows || []);
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    }
  }
});

// Need to be used outside the setup
export function useCatchStoreWidthOut() {
  return useCatchStore(store);
}
