import { parseTime } from "./vctgo";
import { selectUrlById } from "@/api/toy/file";
import Define from "@/utils/dict/Define";
/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue);
  var year = date.getFullYear();
  var month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var minutes =
    date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var seconds =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return (
    year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
  );
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

export function throttle(fn, wait = 500) {
  let last, now;
  return function () {
    now = Date.now();
    if (last && now - last < wait) {
      last = now;
    } else {
      last = now;
      fn.call(this, ...arguments);
    }
  };
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null);
  const list = str.split(",");
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true;
  }
  return expectsLowerCase ? (val) => map[val.toLowerCase()] : (val) => map[val];
}

export const exportDefault = "export default ";

export const beautifierConf = {
  html: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "separate",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
  js: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "normal",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
};

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}
export function findFileIcon(fileExtension) {
  const fileTypes = {};
  Object.keys(Define.FILE).forEach((k) => {
    fileTypes[k.toLowerCase()] = Define.FILE[k].replace(/\./gi, "").split(",");
  });
  return Object.keys(fileTypes).find((k) =>
    fileTypes[k].includes(fileExtension)
  );
}
export const fetchFileUrl = (fileId = "", toyCoverUrl) => {
  return new Promise((resolve, reject) => {
    if (!fileId) {
      resolve([]);
    } else {
      selectUrlById(fileId).then(({ data: fileData }) => {
        resolve(
          fileData && fileData.length > 0
            ? fileData
                .map((item) => {
                  return {
                    name: item.fileName,
                    url: item.fileUrl,
                    fileUrl: item.fileUrl,
                    id: item.id,
                    uid: item.id,
                    key: Math.random(),
                    isPrimary: item.fileUrl === toyCoverUrl,
                    isPrimarySort: item.fileUrl === toyCoverUrl ? 1 : 0,
                    fileSize: item.fileSize,
                    fileSizeStr: getFileSize(item.fileSize),
                    fileExtension: item.fileExtension,
                    fileIcon: findFileIcon(item.fileExtension),
                  };
                })
                .sort((a, b) => b.isPrimarySort - a.isPrimarySort)
            : []
        );
      });
    }
  });
};
export const fetchFileUrlAll = (fileId = "") => {
  return new Promise((resolve, reject) => {
    if (!fileId) {
      resolve([]);
    } else {
      selectUrlById(fileId).then(({ data: fileData }) => {
        resolve(
          fileData && fileData.length > 0
            ? fileData.map((item) => {
                return item;
              })
            : []
        );
      });
    }
  });
};
export function getFileSize(size) {
  // 把字节转换成正常文件大小
  if (!size) return "";
  const num = 1024.0; // byte
  if (size < num) {
    return size + "B";
  }
  if (size < Math.pow(num, 2)) {
    return (size / num).toFixed(2) + "KB";
  } // kb
  if (size < Math.pow(num, 3)) {
    return (size / Math.pow(num, 2)).toFixed(2) + "MB";
  } // M
  if (size < Math.pow(num, 4)) {
    return (size / Math.pow(num, 3)).toFixed(2) + "G";
  } // G
  return (size / Math.pow(num, 4)).toFixed(2) + "T";
}

// urlbase64
export function urlToBase64(url, ext, callback) {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new window.Image();
    img.crossOrigin = "Anonymous";
    img.src = url;
    img.onload = function () {
      canvas.height = 80;
      canvas.width = 80;
      ctx.drawImage(img, 0, 0, 80, 80);
      const dataURL = canvas.toDataURL("image/" + ext);
      // callback.call(this, dataURL); // 回掉函数获取Base64编码
      resolve(dataURL);
      canvas = null;
    };
    img.onerror = function () {
      reject(null);
    };
  });
}

// 图片转webp格式
export function getWebpFileByImageFile(imageFile) {
  const base64ToFile = (base64, fileName) => {
    const arr = base64.split(",");
    const type = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], fileName, {
      type,
    });
  };
  return new Promise((resolve, reject) => {
    const imageFileReader = new FileReader();
    imageFileReader.onload = function (e) {
      const image = new Image();
      image.src = e.target.result;
      image.onload = function () {
        const canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext("2d").drawImage(image, 0, 0);
        resolve(
          base64ToFile(
            canvas.toDataURL("image/webp"),
            `${imageFile.name.split(".")[0]}.webp`
          )
        );
      };
    };
    imageFileReader.readAsDataURL(imageFile);
  });
}

// src转base64 再转文件流
export function urlToBase64ToFile(url) {
  return new Promise((resolve) => {
    let canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const img = new window.Image();
    img.crossOrigin = "Anonymous";
    img.src = url;
    img.onload = function () {
      canvas.height = img.height;
      canvas.width = img.width;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const dataURL = canvas.toDataURL(
        "image/" + url.slice(url.lastIndexOf(".") + 1)
      );
      canvas = null;
      const arr = dataURL.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      const files = new File([u8arr], url.slice(url.lastIndexOf("/") + 1), {
        type: mime,
      });
      resolve(files); // 回掉函数获取File
    };
  });
}

/**
 * 压缩图片方法
 * @param {file} file 文件
 * @param {Number} quality 图片质量(取值0-1之间默认0.92)
 * @param {Number} maxSize 压缩图片的最大大小，同时会影响图片的尺寸比例（1.7*maxSize+300，单位px）
 */
export function compressImg(file, quality = null, maxSize = 300) {
  let qualitys = 0.92
  let maxDim = 1
  if (quality) qualitys = quality
  if (file[0]) {
    return Promise.all(
      Array.from(file).map((e) => this.compressImg(e, qualitys, maxSize))
    ); // 如果是 file 数组返回 Promise 数组
  } else {
    // 计算压缩值
    maxDim = Math.sqrt(
      (file.size / 1024).toFixed(2) / (((maxSize || 300) / 3) * 2).toFixed(2)
    ).toFixed(2)
    return new Promise((resolve) => {
      if ((file.size / 1024).toFixed(2) < (maxSize || 300)) {
        resolve({ file: file });
      } else {
        const reader = new FileReader(); // 创建 FileReader
        reader.onload = ({ target: { result: src } }) => {
          const image = new Image(); // 创建 img 元素
          image.onload = () => {
            const canvas = document.createElement("canvas"); // 创建 canvas 元素
            const context = canvas.getContext("2d");
            let targetWidth = image.width;
            let targetHeight = image.height;
            const originWidth = image.width;
            const originHeight = image.height;
            // 图片尺寸超过的限制
            if (originWidth / originHeight > 1) {
              // 更宽，按照宽度限定尺寸
              targetWidth = Math.round(originWidth / maxDim)
              targetHeight = Math.round(originHeight / maxDim)
            } else {
              targetHeight = Math.round(originHeight / maxDim)
              targetWidth = Math.round(originWidth / maxDim)
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.clearRect(0, 0, targetWidth, targetHeight);
            context.drawImage(image, 0, 0, targetWidth, targetHeight); // 绘制 canvas
            const canvasURL = canvas.toDataURL(file.type, quality);
            const buffer = atob(canvasURL.split(",")[1]);
            let length = buffer.length;
            const bufferArray = new Uint8Array(new ArrayBuffer(length));
            while (length--) {
              bufferArray[length] = buffer.charCodeAt(length);
            }
            const miniFile = new File([bufferArray], file.name, {
              type: file.type,
            });
            resolve({
              file: miniFile,
              origin: file,
              beforeSrc: src,
              afterSrc: canvasURL,
              beforeKB: Number((file.size / 1024).toFixed(2)),
              afterKB: Number((miniFile.size / 1024).toFixed(2)),
              quality: qualitys,
            });
          };
          image.src = src;
        };
        reader.readAsDataURL(file);
      }
    });
  }
}

/**
 * 身份证截取出生日期
 */

export function getBirthdayByIdCard(iIdNo) {
  var tmpStr = "";
  var idDate = "";
  var tmpInt = 0;
  var strReturn = "";

  iIdNo = iIdNo.replace(/^\s+|\s+$/g, "");
  if (iIdNo.length == 15) {
    tmpStr = iIdNo.substring(6, 12);
    tmpStr = "19" + tmpStr;
    tmpStr =
      tmpStr.substring(0, 4) +
      "-" +
      tmpStr.substring(4, 6) +
      "-" +
      tmpStr.substring(6);
    console.log(tmpStr);
    return tmpStr;
  } else {
    tmpStr = iIdNo.substring(6, 14);
    tmpStr =
      tmpStr.substring(0, 4) +
      "-" +
      tmpStr.substring(4, 6) +
      "-" +
      tmpStr.substring(6);
    return tmpStr;
  }
}

/**
 * 拼接省市
 */

export function findProvinceCity(treeData, provinceId, cityId) {
  const result = [];
  // 递归函数，用于在树形数据中查找省市
  function search(node, provinceId, cityId) {
    if (node.provinceId === provinceId) {
      result.push(node.province);
      if (node.children) {
        for (const child of node.children) {
          if (child.cityId === cityId) {
            result.push(child.city);
            return;
          }
        }
      }
    } else if (node.children) {
      for (const child of node.children) {
        search(child, provinceId, cityId);
      }
    }
  }

  // 遍历树形数据
  for (const item of treeData) {
    search(item, provinceId, cityId);
  }
  // 将结果拼接成字符串
  return result.join("");
}

/**
 * 去重校验
 * @param valArr
 * @param keys
 * @returns {*|boolean}
 */
export function handleUniqueItems(valArr, keys) {
  const list = new Set();
  const duplicates = []; // 保存重复值的数组
  valArr.forEach((item) => {
    const value = keys.map((key) => item[key]).join("-");
    if (list.has(value)) {
      duplicates.push(value); // 将重复值添加到数组中
    } else {
      list.add(value);
    }
  });
  if (duplicates.length > 0) {
    return false; // 存在重复值
  }
  return true; // 没有重复值
}

// export function areArraysEqualByKeys(array1, array2, keys) {
//   // 检查数组长度是否相同
//   if (array1?.length !== array2?.length) {
//     return false
//   }
//
//   // 遍历数组对象并比较指定键的值
//   for (let i = 0; i < array1.length; i++) {
//     const obj1 = array1[i]
//     const obj2 = array2[i]
//
//     // 遍历键数组并比较对应键的值
//     for (let j = 0; j < keys.length; j++) {
//       const key = keys[j]
//
//       // 如果键对应的值不相等，则返回 false
//       if (obj1[key] !== obj2[key]) {
//         return false
//       }
//     }
//   }
//   // 如果所有对象的所有键的值都相等，则返回 true
//   return true
// }

export function findAllIndices(arr, conditionFn) {
  return arr
    .map((item, index) => (conditionFn(item, index) ? index : -1))
    .filter((index) => index !== -1);
}
// js创建a标签实现下载
export function downExcel(url, conditionFn) {
  const a = document.createElement('a')// 创建a标签
  a.setAttribute('href', url)// 设置文件下载地址
  a.setAttribute('download', url)// 设置文件下载地址
  // a.setAttribute('target', '_blank')// 在当前页面创建下载
  document.body.appendChild(a)// 添加到body
  a.click()// 触发事件
  document.body.removeChild(a)// 移除标签
}

