const uploadFile = (extension) =>
  new Promise((resolve, reject) => {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.style.display = 'none'
    fileInput.accept = extension;
    fileInput.onchange = ()=> {
      if (fileInput.files) {
        resolve(fileInput.files[0]);
        fileInput.remove()
      }
    };
    document.body.appendChild(fileInput);
    fileInput.click();
  });

  // HSL 转 RGB
const hslToRgb = (h, s, l) => {
  let R, G, B;

  if (s === 0) {
    R = G = B = l;
  } else {
    const hue2rgb = function hue2rgb(p, q, t) {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    }

    const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    const p = 2 * l - q;
    R = Math.round(hue2rgb(p, q, h + 1 / 3) * 255);
    G = Math.round(hue2rgb(p, q, h) * 255);
    B = Math.round(hue2rgb(p, q, h - 1 / 3) * 255);
  }

  return {R, G, B};
}

// 转换颜色 hsl / hex -> rgb
const convertColor = (colorStr) => {
  if (!colorStr) return null;

  if (colorStr.startsWith('#')) {
    const hexValues = colorStr.slice(1).match(/.{2}/g);
    if (hexValues) {
      return {
        R: parseInt(hexValues[0], 16),
        G: parseInt(hexValues[1], 16),
        B: parseInt(hexValues[2], 16)
      };
    }
  }

  if (colorStr.startsWith('rgb')) {
    const matches = colorStr.match(/\d+/g);
    if (matches && matches.length === 3) {
      return {
        R: parseInt(matches[0]),
        G: parseInt(matches[1]),
        B: parseInt(matches[2])
      };
    }
  }

  if (colorStr.startsWith('hsl')) {
    const matches = colorStr.match(/(\d+),\s*(\d+%),\s*(\d+%)/);
    if (matches) {
      const [h, s, l] = [parseInt(matches[1]), parseInt(matches[2]) / 100, parseInt(matches[3]) / 100];
      const {R, G, B} = hslToRgb(h / 360, s, l);
      return {R, G, B};
    }
  }
}

// 判断两个颜色字符串在阈值外是否相同
const areColorsSimilar = (colorStr1, colorStr2, threshold = 10) => {
  const rgb1 = convertColor(colorStr1);
  const rgb2 = convertColor(colorStr2);

  if (!rgb1 || !rgb2) return false;

  // 比较RGB值是否在每个分量上差异都小于阈值
  const diffR = Math.abs(rgb1.R - rgb2.R);
  const diffG = Math.abs(rgb1.G - rgb2.G);
  const diffB = Math.abs(rgb1.B - rgb2.B);

  return diffR <= threshold && diffG <= threshold && diffB <= threshold;
}
export { uploadFile, areColorsSimilar }
