import MergeData from './MergeData.json';
import dayjs from 'dayjs';

export function getImageUrl(key: string): string {
  if (!key) return '';

  // 1. 判断 key 是否为 UI_MergeData_<number> 格式，取出数字；同时支持直接传入数字字符串或数字
  let id: string | null = null;
  const m = /^UI_MergeData_(\d+)$/.exec(key);
  if (m) id = m[1] ?? '';
  else if (/^\d+$/.test(key)) id = key;
  else id = String(key);

  // 2. 从 MergeData 中取出 id 对应的 Icon
  const item = (MergeData as any)[id];
  const icon = item && typeof item.Icon === 'string' ? item.Icon : '';
  if (!icon) return '';

  // 3. 在 Node 环境中遍历指定文件夹寻找包含 Icon 名称的文件并返回绝对路径
  //    如果不在 Node 环境（例如浏览器），则回退返回 icon 字符串
  try {
    // @ts-ignore
    const fs = require('fs');
    // @ts-ignore
    const path = require('path');
    const SEARCH_DIR =
      'D:\\Github\\AplusB_Pet_nation\\Assets\\GameMain\\UI\\UISprites\\MergeObj';

    function findFile(dir: string): string | null {
      let entries: string[] = [];
      try {
        entries = fs.readdirSync(dir);
      } catch (e) {
        return null;
      }
      for (const name of entries) {
        const full = path.join(dir, name);
        let stat;
        try {
          stat = fs.statSync(full);
        } catch (e) {
          continue;
        }
        if (stat.isDirectory()) {
          const res = findFile(full);
          if (res) return res;
        } else {
          if (name.indexOf(icon) !== -1) return path.resolve(full);
        }
      }
      return null;
    }

    const found = findFile(SEARCH_DIR);
    if (found) return found;
  } catch (e) {
    // 非 Node 环境或访问失败，忽略并回退
  }

  // 回退：返回 icon 名称（供前端拼接资源路径使用）
  return icon;
}

export const getUnixTime = (date: any): number => {
  if (date) {
    if (typeof date === 'string') {
      return dayjs(date).unix();
    } else if (dayjs.isDayjs(date)) {
      return date.unix();
    } else if (typeof (date as any).unix === 'function') {
      return (date as any).unix();
    } else {
      return dayjs(date).unix();
    }
  }
  return 0;
};

export const getItemUrl = (itemId: number): string => {
  switch (itemId) {
    case 100001:
      return './Assets/Art_SubModule/Art_Resource/Art_UISprites/Shop/Big/shop_energy_LV1.png';
    case 100003:
      return './Assets/Art_SubModule/Art_Resource/Art_UISprites/Shop/Big/shop_diamond_LV2.png';
    default:
      return '';
  }
};
