/* eslint-disable no-useless-escape */
export const encodeHtml = (string: string) => {
  let ret = string.replace(/&/g, '&amp;');
  ret = ret.replace(/</g, '&lt;');
  ret = ret.replace(/>/g, '&gt;');
  ret = ret.replace(/ /g, '&nbsp;');
  ret = ret.replace(/\'/g, '&#39;');
  ret = ret.replace(/\"/g, '&quot;');
  ret = ret.replace(/\n/g, '<br/>');
  return ret;
};

export const decodeHtml = (string: string) => {
  let ret = string.replace(/&amp;/g, '&');
  ret = ret.replace(/&lt;/g, '<');
  ret = ret.replace(/&gt;/g, '>');
  ret = ret.replace(/&nbsp;/g, ' ');
  ret = ret.replace(/&#39;/g, "'");
  ret = ret.replace(/&quot;/g, '"');
  ret = ret.replace(/<br\/>/g, '\n');
  return ret;
};

/**
 * @name 获取svg图片的字符串
 * @param file 文件
 * @returns
 */
export const getSvgText = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    try {
      const fileReader = new FileReader();
      fileReader.readAsText(new Blob([file]), 'UTF-8');
      fileReader.onload = () => {
        const result = (fileReader.result || '') as string;
        resolve(result);
      };
    } catch (error) {
      reject(error);
    }
  });
};

/**
 * @name 验证是否是svg字符串
 * @param svg
 * @returns
 */
export const isSvg = (svg: string) =>
  /<svg([\S\s]*?)>([\S\s]*?)<\/svg>/.test(svg);

/**
 * @name 清除svg的fill属性
 * @param svg
 * @returns
 */
export const clearSvgColor = (svg: string) =>
  svg.replace(/fill="([\S\s]*?)"/g, ''); // 清除svg的填充色

/**
 * @name 获取纯svg字符串
 * @param svg
 * @returns
 */
export const getPureSvgText = (svg: string) =>
  svg.replace(
    /<svg[\S\s]*?>([\S\s]*?)<\/svg>/,
    '<svg viewBox="0 0 1024 1024">$1</svg>',
  );
