import axios from '@/http';
import { cdn } from './api';

const market = import.meta.env.VITE_BASEURL;

const normalFolder = market ? '/2d/png/' : '/png/';
/**
 * 请求 png 的目录
 * @returns
 */
export async function getPngFolders() {
  return await getFolders(normalFolder);
}

/**
 * 请求 png 目录下的所有 png
 * @param name 目录名
 * @returns
 */
export async function getPngs(name: string) {
  const files = (await axios.get(normalFolder + name + '/')) as any[];
  if (!files || !files.map) {
    return [];
  }
  return files.map((f) => {
    let fname = filename(f.name);
    return {
      name: globalThis.fileJson
        ? globalThis.fileJson[fname]
          ? globalThis.fileJson[fname]
          : fname
        : fname,
      pinyin: globalThis.fileJson ? fname : null,
      image: cdn + normalFolder + name + '/' + f.name,
    };
  });
}

export async function getFolders(folderName: string) {
  const ret = (await axios.get(folderName)) as any[];

  if (!ret || !ret.map) {
    return [];
  }
  return await Promise.all(
    ret.map(async (c: any) => {
      const files = (await axios.get(folderName + c.name + '/')) as any[];
      return {
        name: globalThis.folderJson
          ? globalThis.folderJson[c.name]
            ? globalThis.folderJson[c.name]
            : c.name
          : c.name,
        pinyin: globalThis.folderJson ? c.name : null,
        show: true,
        list: [],
        count: files.length,
        // 用于区别 png 与 svg 文件夹
        svgFolder: folderName === normalFolder ? true : false,
      };
    })
  );
}

export function filename(str: string) {
  const i = str.lastIndexOf('.');
  return str.substring(0, i);
}
