import { defineStore } from 'pinia';
import { store } from '@/store';
import {
  getSubjectList,
  getSubjectList2,
  getCategories,
  api_musicalInstrumentList,
  api_musicTagTree
} from '@/api/user';
import deepClone from '/src/helpers/deep-clone';
import { api_materialTagPage } from '/src/views/natural-resources/api';

export const useCatchStore = defineStore('catch-store', {
  state: () => ({
    bookVersionList: [] as any[], // 其它类型
    musicTypeList: [] as any[], // 乐谱分类
    subjectList: [] as any[], // 声部列表,
    musicInstrumentList: [] as any[], // 乐器列表,
    subjectInstruemnts: [] as any[], // 乐器列表，
    musicTagTree: [] as any[], // 分类列表
    materialTags: [] as any[] // 素材标签
  }),
  getters: {
    getBookVersion(): any[] {
      return this.bookVersionList;
    },
    getMusicCategories(): any[] {
      return this.musicTypeList;
    },
    getMusicInstruments(): any[] {
      return this.musicInstrumentList;
    },
    getAllMusicCategories(): any[] {
      return [
        {
          name: '全部',
          id: null
        },
        ...this.musicTypeList
      ];
    },
    getSubjectList(): any[] {
      return this.subjectList;
    },
    getSubjectAllList(): any[] {
      return [
        {
          name: '全部',
          id: null
        },
        ...this.subjectList
      ];
    },
    /**
     * 获取所有启用的声部
     */
    getEnableSubjects(): any[] {
      const temp: any[] = [];
      this.subjectList.forEach((subject: any) => {
        if (subject.enableFlag) {
          const { instruments, ...r } = subject;

          if (instruments && instruments.length > 0) {
            const tempChild: any[] = [];
            instruments?.forEach((instrument: any) => {
              if (instrument.enableFlag) {
                tempChild.push(instrument);
              }
            });

            if (tempChild.length > 0)
              temp.push({ ...r, instruments: tempChild });
          }
        }
      });

      return temp;
    },
    getSubjectInstruments(): any[] {
      return [
        {
          name: '全部',
          id: null,
          label: '全部',
          value: null
        },
        ...this.subjectInstruemnts
      ];
    },
    getSubjectInstrumentOnly(): any[] {
      return this.subjectInstruemnts;
    },
    getMusicTagTree(): any[] {
      return this.musicTagTree;
    },
    getMaterialTags(): any[] {
      return this.materialTags;
    },
    getAllMaterialTags(): any[] {
      return [
        {
          label: '全部',
          value: null
        },
        ...this.materialTags
      ];
    }
  },
  actions: {
    setBookVersion(books: any[]) {
      this.bookVersionList = books;
    },
    setMusicCategories(musics: any[]) {
      this.musicTypeList = musics;
    },
    setSubjects(subjects: any[]) {
      this.subjectList = subjects;
    },
    setSubjectInstruemnts(subjects: any[]) {
      this.subjectInstruemnts = subjects;
    },
    setMusicInstruments(instruments: any[]) {
      this.musicInstrumentList = instruments;
    },
    setMusicTagTree(tagTree: any[]) {
      this.musicTagTree = tagTree;
    },
    setMaterialTags(materialTags: any[]) {
      this.materialTags = materialTags;
    },
    /**
     * 判断是否有声部数据，如不存在则获取声部列表
     * @returns Promise
     */
    async getSubjects() {
      try {
        // 判断是否存在声部数据
        if (this.getSubjectList && this.getSubjectList.length > 0) {
          return Promise.resolve();
        }
        const { data } = await getSubjectList2({
          // enableFlag: true,
          delFlag: 0,
          page: 1,
          rows: 999
        });

        const tempSubjectList = data || [];

        const tempSubjectInstruments: any = [];
        tempSubjectList.forEach((item: any) => {
          if (item.instruments && item.instruments.length > 0) {
            item.value = item.id;
            item.label = item.name;
            item.instruments.forEach((child: any) => {
              child.label = child.name;
              child.value = child.id;
            });

            const tempSi = {
              value: item.id,
              label: item.name,
              id: item.id,
              name: item.name,
              instruments: [] as any
            };
            if (item.instruments) {
              if (item.instruments.length == 1) {
                tempSi.value = item.instruments[0].id;
                tempSi.label = item.instruments[0].name;
                tempSi.id = item.id;
                tempSi.name = item.name;
              } else if (item.instruments.length > 1) {
                item.instruments.forEach((child: any) => {
                  child.label = child.name;
                  child.value = child.id;
                  tempSi.instruments.push({
                    label: child.name,
                    value: child.id,
                    id: child.id,
                    name: child.name
                  });
                });
              }
            }
            tempSubjectInstruments.push(tempSi);
          }
        });

        this.setSubjects(
          tempSubjectList.filter(
            (item: any) => item.instruments && item.instruments.length > 0
          ) || 0
        );
        this.setSubjectInstruemnts(tempSubjectInstruments || []);

        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },
    /**
     * 获取所有启用的乐器并包含修改的声部
     */
    getEnableSingleAllSubjects(ids?: any) {
      ids = ids || [];
      const subjects: any = [];
      this.getSubjectList.forEach((subject: any) => {
        const temp = deepClone(subject);
        if (Array.isArray(temp.instruments)) {
          temp.instruments.forEach((item: any) => {
            if (ids.includes(item.id)) {
              item.enableFlag = true;
              temp.enableFlag = true;
            }
          });
        }
        subjects.push(temp);
      });
      const temp: any[] = [];
      subjects.forEach((subject: any) => {
        if (subject.enableFlag) {
          const { instruments, ...r } = subject;

          const tempChild: any[] = [];
          instruments?.forEach((instrument: any) => {
            if (instrument.enableFlag) {
              tempChild.push(instrument);
            }
          });

          if (tempChild.length > 0) temp.push({ ...r, instruments: tempChild });
        }
      });
      return temp;
    },
    /**
     * 判断是否有教材分类数据，如不存在则获取教材分类列表
     * @returns Promise
     */
    async getMusicSheetCategory(resset = false) {
      try {
        // 判断是否存在声部数据
        if (
          this.getMusicCategories &&
          this.getMusicCategories.length > 0 &&
          !resset
        ) {
          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);
      }
    },
    /**
     * 获取乐器列表
     * @returns Promise
     */
    async getMusicInstrument() {
      try {
        // 判断是否存在声部数据
        if (this.getMusicInstruments && this.getMusicInstruments.length > 0) {
          return Promise.resolve();
        }
        const { data } = await api_musicalInstrumentList({
          enableFlag: true
        });
        console.log(data, 'data');
        this.setMusicInstruments(data || []);
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // ?queryCategory=true
    /**
     * 获取层级
     * @returns Promise
     */
    async getMusicTagTreeApi() {
      try {
        // // 判断是否存在声部数据
        if (this.getMusicTagTree && this.getMusicTagTree.length > 0) {
          return Promise.resolve();
        }
        const { data } = await api_musicTagTree();

        const result = data || [];
        // result.forEach((item: any) => {
        //   if (item.children && item.children.length > 0) {
        //     item.children.forEach((child: any) => {
        //       child.children =
        //         child.categoriesList && child.categoriesList.length > 0
        //           ? child.categoriesList
        //           : '';
        //     });
        //   }
        // });
        // console.log(result, 'result');
        this.setMusicTagTree(result || []);
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },
    /**
     * 获取所有标签
     * @returns Promise
     */
    async getMaterialTagsApi() {
      try {
        // 判断是否存在声部数据
        if (this.getMaterialTags && this.getMaterialTags.length > 0) {
          return Promise.resolve();
        }
        const { data } = await api_materialTagPage({ page: 1, rows: 100 });
        const result = data.rows || [];
        const tempList: any = [];
        result.forEach((item: any) => {
          tempList.push({
            label: item.name,
            value: item.id
          });
        });
        this.setMaterialTags(tempList || []);
        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    }
  }
});

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