import pinyin from 'pinyin'
/**
 * * 生成一个不重复的ID
 * @param { Number } randomLength
 */
export const getUUID = (randomLength = 10) => {
  return 'id_' + Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36)
}

/**
 * * JSON序列化，支持函数和 undefined
 * @param data
 */
export const JSONStringify = (data) => {
  return JSON.stringify(
    data,
    (key, val) => {
      // 处理函数丢失问题
      if (typeof val === 'function') {
        return `${val}`
      }
      // 处理 undefined 丢失问题
      if (typeof val === 'undefined') {
        return null
      }
      return val
    },
    2
  )
}
/**
 * * JSON反序列化，支持函数和 undefined
 * @param data
 */

export const JSONParse = (data) => {
  if (data.trim() === '') return
  return JSON.parse(data, (k, v) => {
    if (k !== 'formatter') {
      return v
    }
    // 还原函数值
    if (typeof v === 'string' && checkJsonStringify(v)) {
      return eval2(`(function(){return ${v}})()`)
    } else if (typeof v === 'string' && v.indexOf && v.indexOf('return ') > -1) {
      const baseLeftIndex = v.indexOf('(')
      if (baseLeftIndex > -1) {
        const newFn = `function ${v.substring(baseLeftIndex)}`
        return eval2(`(function(){return ${newFn}})()`)
      }
    }
    return v
  })
}

export const getParseLang = (data, lang) => {
  try {
    return JSONParse(JSONParse(data))[lang];
  } catch (error) {
    return data;
  }
};

export const getFirstLetter = (name) => {
  const py = pinyin(name[0], {
    style: pinyin.STYLE_FIRST_LETTER,
    heteronym: false
  });
  const letter = py?.[0]?.[0]?.toUpperCase() || '#';
  return /^[A-Z]$/.test(letter) ? letter : '#';
}


// utils/eventBus.js
import { ref } from 'vue';
const listeners = ref(new Map());

export const eventBus = {
  $emit(event, ...args) {
    const callbacks = listeners.value.get(event) || [];
    callbacks.forEach(cb => cb(...args));
  },
  $on(event, callback) {
    const callbacks = listeners.value.get(event) || [];
    listeners.value.set(event, [...callbacks, callback]);
  },
  $off(event) {
    listeners.value.delete(event);
  }
};