import { ElMessage } from 'element-plus';

function useChangeColor() {
  const hexToRgb = (str) => {
    let hexs = "";
    let reg = /^\#?[0-9A-Fa-f]{6}$/;
    if (!reg.test(str)) {
      return "";
    }
    str = str.replace("#", "");
    hexs = str.match(/../g);
    for (let i = 0; i < 3; i++) hexs[i] = parseInt(hexs[i], 16);
    return hexs;
  };
  const rgbToHex = (r, g, b) => {
    let reg = /^\d{1,3}$/;
    if (!reg.test(r) || !reg.test(g) || !reg.test(b)) {
      ElMessage.warning("\u8F93\u5165\u9519\u8BEF\u7684rgb\u989C\u8272\u503C");
      return "";
    }
    let hexs = [r.toString(16), g.toString(16), b.toString(16)];
    for (let i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = `0${hexs[i]}`;
    return `#${hexs.join("")}`;
  };
  const getDarkColor = (color, level) => {
    let reg = /^\#?[0-9A-Fa-f]{6}$/;
    if (!reg.test(color)) {
      ElMessage.warning("\u8F93\u5165\u9519\u8BEF\u7684hex\u989C\u8272\u503C");
      return "";
    }
    let rgb = useChangeColor().hexToRgb(color);
    for (let i = 0; i < 3; i++) rgb[i] = Math.floor(rgb[i] * (1 - level));
    return useChangeColor().rgbToHex(rgb[0], rgb[1], rgb[2]);
  };
  const getLightColor = (color, level) => {
    let reg = /^\#?[0-9A-Fa-f]{6}$/;
    if (!reg.test(color)) {
      ElMessage.warning("\u8F93\u5165\u9519\u8BEF\u7684hex\u989C\u8272\u503C");
      return "";
    }
    let rgb = useChangeColor().hexToRgb(color);
    for (let i = 0; i < 3; i++) rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i]);
    return useChangeColor().rgbToHex(rgb[0], rgb[1], rgb[2]);
  };
  return {
    hexToRgb,
    rgbToHex,
    getDarkColor,
    getLightColor
  };
}

export { useChangeColor };
