import QRCode from "qrcode";
import dayjs from 'dayjs';
import copy from "copy-to-clipboard";
import { ElMessage } from "element-plus";
import validate from "./validate";

export function getBirthFromIdNo(idNo = "") {
  const [isIdNo] = validate.isChinaId(idNo);
  if (isIdNo) {
    const birthDay = idNo.slice(6, 14).replace(/(?=\d{2}$)|(?=\d{4}$)/g, "-");
    return birthDay;
  }
  return "";
}
export function maskPhone(phone = "", headNumLength = 3, tailNumLength = 2) {
  if (!phone) return;

  phone = phone + "";
  const isMobile = validate.isMobile(phone);
  const phoneRegxp = new RegExp(`^(\\d{${headNumLength}})\\d{${11 - headNumLength - tailNumLength}}(\\d{${tailNumLength}})$`);
  return isMobile ? phone.replace(phoneRegxp, `$1${'*'.repeat(11 - headNumLength - tailNumLength)}$2`) : phone;
}

export function maskIdNo(idNo = "") {
  if (!idNo) return;
  const [isIdNo] = validate.isChinaId(idNo);
  return isIdNo ? idNo.replace(/^(\d{3})\d+(\w{4})$/, "$1***********$2") : idNo;
}

export async function downloadQrcode(content, name, options = { width: 560 }) {
  const base64 = await QRCode.toDataURL(content, options);
  download(base64, name);
}

export function download(href, filename) {
  let tag = document.createElement("a");
  tag.href = href;
  tag.download = filename;
  tag.click();
  tag = null;
}
export function useCopy(text, msg = "已复制到剪切板") {
  copy(text);
  ElMessage.success(msg);
}

export function getRandomStr(letterNum = 10, tailNum = 5) {
  const prefix = new Array(letterNum).fill(1).reduce((s) => s + getRandomLetter());
  const tail = String(Math.floor(Math.random() * 10 ** tailNum)).padStart(tailNum, "0");
  return `${prefix}${+new Date()}${tail}`;
}

function getRandomLetter() {
  let num = Math.floor(Math.random() * 58) + 65;
  if (num > 90 && num < 97) {
    num -= 7;
  }
  return String.fromCharCode(num);
}

export function file2Base64(file) {
  const reader = new FileReader();
  return new Promise((resolve) => {
    reader.readAsDataURL(file);
    reader.onload = (evt) => resolve(evt.target.result);
  });
}
export function urlParamsToObject(url = window.location.href) {
  const obj = {};
  // 获取 URL 中的查询字符串部分
  const queryString = url.split("?")[1];
  if (queryString) {
    const params = new URLSearchParams(queryString);
    // 2. 创建一个空对象来存储解析后的参数
    // 3. 遍历每个参数，并将其存储在对象中
    for (const [key, value] of params) {
      obj[key] = value;
    }
  }
  return obj;
}

export function transformData(data) {
  return data.map((item) => {
    const transformedItem = {
      label: item.sourceName,
      value: item.sourceId,
    };

    if (item.children && item.children.length > 0) {
      transformedItem.children = transformData(item.children);
    }

    return transformedItem;
  });
}

export function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = function () {
      const base64String = reader.result.split(",")[1];
      resolve(base64String);
    };

    reader.onerror = function (error) {
      reject(error);
    };

    reader.readAsDataURL(file);
  });
}

export function blobUrlToBase64(blobUrl) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";

    xhr.onload = function () {
      if (xhr.status === 200) {
        const arrayBuffer = xhr.response;
        const uint8Array = new Uint8Array(arrayBuffer);
        const base64String = btoa(String.fromCharCode.apply(null, uint8Array));

        // Determine the appropriate image type based on the blob URL
        const contentType = xhr.getResponseHeader("Content-Type");
        const imageType = contentType.substring(contentType.indexOf("/") + 1);

        // Add the appropriate image base64 prefix
        const base64WithPrefix = `data:image/${imageType};base64,${base64String}`;

        resolve(base64WithPrefix);
      } else {
        reject(new Error("Failed to fetch the Blob content."));
      }
    };

    xhr.open("GET", blobUrl, true);
    xhr.send();
  });
}

export function validateColor(color) {
  // 使用正则表达式检查颜色字符串是否符合 RGB、RGBA、十六进制颜色、HSL 或 HSLA 的格式
  const rgbRegex = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;
  const rgbaRegex = /^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(0|1|0\.\d+)\s*\)$/i;
  const hexRegex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
  const hslRegex = /^hsl\(\s*(\d+)\s*,\s*(\d+%)\s*,\s*(\d+%)\s*\)$/i;
  const hslaRegex = /^hsla\(\s*(\d+)\s*,\s*(\d+%)\s*,\s*(\d+%)\s*,\s*(0|1|0\.\d+)\s*\)$/i;

  if (rgbRegex.test(color) || rgbaRegex.test(color) || hexRegex.test(color) || hslRegex.test(color) || hslaRegex.test(color)) {
    return true; // 颜色格式匹配
  } else {
    return false; // 颜色格式不匹配
  }
}

export function getCateTreeData(list) {
  if (!Array.isArray(list)) return [];
  const level3 = list.filter(i => i.level === 3).map(i => {
    const children = list.filter(j => j.parentId === i._id).map(j => ({ ...j }))
    const childrenIds = children.map(j => j._id)
    return { ...i, children, childrenIds }
  })
  const level2 = list.filter(i => i.level === 2).map(i => {
    const children = level3.filter(j => j.parentId === i._id).map(j => ({ ...j }))
    const childrenIds = children.map(j => j._id)
    children.forEach(child => {
      if (Array.isArray(child.childrenIds) && child.childrenIds.length > 0) {
        childrenIds.push(...child.childrenIds)
      }
    })
    return { ...i, children, childrenIds }
  })
  return list.filter(i => i.level === 1).map(i => {
    const children = level2.filter(j => j.parentId === i._id)
    const childrenIds = children.map(j => j._id)
    children.forEach(child => {
      if (Array.isArray(child.childrenIds) && child.childrenIds.length > 0) {
        childrenIds.push(...child.childrenIds)
      }
    })
    return { ...i, children, childrenIds }
  }).sort((a, b) => {
    const aSort = a.sort >= 0 ? a.sort : 10000;
    const bSort = b.sort >= 0 ? b.sort : 10000;
    return aSort - bSort
  })

}

export function disableBeforeDay(date) {
  return dayjs(date).isBefore(dayjs().startOf('day'))
}


export function getAttachmentFileList(list) {
  return list.map((i) => {
    let typeStr = "";
    const type = i.type;
    const fileType = i.file && typeof i.file.type === "string" ? i.file.type : "";
    if (fileType.includes("video")) typeStr = "【视频】";
    else if (fileType.includes("image") || type === "image") typeStr = "【图片】";
    else if (fileType === "article") typeStr = "【文章】";
    else if (fileType === "questionnaire") typeStr = "【问卷】";
    else if (type === "link") typeStr = "【链接】";
    return { name: i.file && i.file.name ? i.file.name : '', type: typeStr };
  });
}

export function verifyString(str, label, min = 0, max = 100) {
  if (typeof str === 'number') {
    str = str.toString()
  }
  if (str === undefined || str === null) {
    str = ''
  }
  if (typeof str === 'string' && str.trim().length >= min && str.trim().length < max) {
    return [true, str.trim()];
  }
  if (typeof str !== 'string' && min === 0) {
    return [true, ''];
  }
  if (typeof str !== 'string') {
    return [false, `${label}格式不正确`];
  }
  if (str.trim().length === 0 && min > 0) {
    return [false, `${label}不能为空`];
  }
  if (min > 0 && str.trim().length < min) {
    return [false, `${label}不能少于${min}个字符`];
  }
  return [false, `${label}不能超过${max}个字符`]
}

export function verifyNumber(value, label, len = 0, min, max, minEq, maxEq) {
  // 1. 检查 value 是否为字符串或数字类型
  if (typeof value !== 'string' && typeof value !== 'number') {
    return [false, `${label}无效`];
  }

  // 2. 如果是字符串类型，尝试转为数字
  if (typeof value === 'string') {
    // 去除前后空格
    value = value.trim();
    // 空字符串或非数字字符串直接返回 false
    if (value === '' || isNaN(value)) {
      return [false, `${label}无效`];
    }
    value = Number(value);
  }

  // 3. 检查是否为有效数字（排除 NaN 和 Infinity）
  if (typeof value !== 'number' || !isFinite(value)) {
    return [false, `${label}无效`];
  }

  // 4. 检查小数位数是否 <= len
  const decimalPart = String(value).split('.')[1];
  if (decimalPart && decimalPart.length > len) {
    return len === 0 ? [false, `${label}只能输入整数`] : [false, `${label}最多输入${len}位小数`];
  }
  if (typeof min === 'number' && minEq && value < min) {
    return [false, `${label}最小为${min}`];
  }
  if (typeof min === 'number' && !minEq && value <= min) {
    return [false, `${label}应该大于${min}`];
  }
  if (typeof max === 'number' && maxEq && value > max) {
    return [false, `${label}不能大于${max}`];
  }
  if (typeof max === 'number' && !maxEq && value >= max) {
    return [false, `${label}应该小于${max}`];
  }

  return [true, value];
}


export function verifyListItem(val, list, required, label, defaultValue = '') {
  if (!val && val !== 0 && !required) {
    return [true, defaultValue]
  }
  if (list.includes(val)) {
    return [true, val]
  }
  return [false, `${label}无效`]
}