// 重复svg删除
export const repeatSVGCheck = (name: string) => {
  const svgDOM = document.getElementsByClassName(`${name}`);

  // 超过1个，说明有重复的svg
  if (svgDOM.length && svgDOM.length > 1) {
    const svgDOMArr = Array.from(svgDOM);

    const svgArr = svgDOMArr
      .map(v => ({
        svg: v,
        childLength: v.childNodes.length,
      }))
      .sort((a, b) => b.childLength - a.childLength);
    svgArr.forEach((item, index) => {
      if (index !== 0) {
        document.body.removeChild(item.svg);
      }
    });
  }
};

/**
 * 多包版本冲突问题解决
 *
 * @param name: '_iconfont_svg_string_' + icon项目id
 *
 */

export const versionConflictCheck = (name: string) => {
  let svgStr = window[name as keyof typeof window];
  try {
    Object.defineProperty(window, name, {
      get() {
        if (svgStr) {
          setTimeout(() => {
            // 不是必须操作，优化逻辑，用于删除dom里多余的svg
            repeatSVGCheck(name);
          }, 150);
        }
        return svgStr;
      },
      set(value) {
        if (!svgStr || value.length > svgStr.length) {
          svgStr = value.replace("<svg>", `<svg class="${name}">`);
        }
      },
    });
  } catch (error) {
    // console.log('versionConflictCheck----error', error);
  }
};
