// 滚动到头部
import { Local } from "@/utils/storage.js";
import { ref, watch } from 'vue';
export function scrollToTop(ele) {
  const start = ele.scrollTop;
  const end = 0;
  const duration = 500; // 滚动时间
  let startTime = null;

  const animateScroll = (timestamp) => {
    if (!startTime) {
      startTime = timestamp;
    }
    const progress = timestamp - startTime;
    const distance = end - start;
    const easeInOutQuad = (t) => {
      return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
    }; // 缓动函数

    ele.scrollTop = distance * easeInOutQuad(Math.min(progress / duration, 1)) + start;

    if (progress < duration) {
      window.requestAnimationFrame(animateScroll);
    }
  };

  window.requestAnimationFrame(animateScroll);
}
// 判断用户是否有权限
export const hasPermission = (userPermission) => {
  const permissionList = Local.get('ruleBtn')?.filter(Boolean) ?? [];

  const userPermissionList = [].concat(userPermission);

  const permissionSet = new Set(permissionList);

  return userPermissionList.some(permission => permissionSet.has(permission));
}
// 根据文件url来下载文件
export const downloadFile = (url) => {
  return new Promise(async (resolve, reject) => {
    try {
      const fileName = new URL(url).pathname.split('/').at(-1)
      const response = await fetch(url)
      if (!response.ok) {
        throw new Error(`下载失败，状态码：${response.status}`);
      }
      const blob = await response.blob()
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob)
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(link.href);
      resolve(fileName);
    } catch (error) {
      console.error('下载文件失败:', error);
      reject(error);
    }
  });
};
/**
 * 将对象中的空字符串转换为null
 * @param {Object} obj - 源对象
 * @returns {Object} - 新对象
 */
export const convertEmptyToNull = (() => {
  const isArray = Array.isArray;
  const hasOwn = Object.prototype.hasOwnProperty;

  const cache = new WeakMap();

  return (obj) => {
    if (obj === null || obj === undefined) return obj;
    if (obj === '') return null;
    if (typeof obj !== 'object') return obj;
    if (cache.has(obj)) return cache.get(obj);

    if (isArray(obj)) {
      const arr = new Array(obj.length);
      let hasChanged = false;
      for (let i = 0, len = obj.length; i < len; i++) {
        const item = obj[i];
        const newItem = item === '' ? null :
          typeof item === 'object' && item !== null ? convertEmptyToNull(item) :
            item;
        if (newItem !== item) hasChanged = true;
        arr[i] = newItem;
      }

      const result = hasChanged ? arr : obj;
      cache.set(obj, result);
      return result;
    }
    let hasChanged = false;
    const newObj = {};

    for (const key in obj) {
      if (!hasOwn.call(obj, key)) continue;

      const val = obj[key];
      const newVal = val === '' ? null :
        typeof val === 'object' && val !== null ? convertEmptyToNull(val) :
          val;

      if (newVal !== val) hasChanged = true;
      newObj[key] = newVal;
    }

    const result = hasChanged ? newObj : obj;
    cache.set(obj, result);
    return result;
  };
})();
// 计算图片文件或图片 URL 的宽高
export function getImageDimensions(input) {
  return new Promise((resolve, reject) => {
    let file;

    // 判断输入类型
    if (typeof input === 'string') {
      // 如果是 URL，直接使用 URL 创建图片
      file = new Image();
      file.onload = () => {
        resolve({ width: file.width, height: file.height });
      };
      file.onerror = () => {
        reject(new Error('Failed to load image URL'));
      };
      file.src = input;  // 设置图片的 URL
    } else if (input && input.type && input.type.startsWith('image/')) {
      // 如果是文件对象，使用 FileReader 读取
      const reader = new FileReader();

      reader.onload = (event) => {
        const img = new Image();

        img.onload = () => {
          resolve({ width: img.width, height: img.height });
        };

        img.onerror = () => {
          reject(new Error('Failed to load image from file'));
        };

        img.src = event.target.result;
      };

      reader.onerror = () => {
        reject(new Error('Failed to read file'));
      };

      reader.readAsDataURL(input);
    } else {
      reject(new Error('The input is neither a valid image URL nor an image file'));
    }
  });
}


export function useNullIfEmptyRef(initialValue) {
  const data = ref(convertEmptyToNull(initialValue));

  watch(data, (newValue) => {
    data.value = convertEmptyToNull(newValue);
  }, { deep: true, immediate: true });
  return data;
}
// 判断是否是json字符串
export const isJSON = (str) => {
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
};

export const isEmpty = (val) => {
  if (Array.isArray(val)) {
    return val.length === 0;
  }
  return val === null || val === undefined || val === '';
};