// 获取元素宽高
export const getRect = ({ name, onSuccess, instance, multiple }) => {
  // 创建一个选择器查询对象
  const select = uni.createSelectorQuery().in(instance.proxy);
  // 选择指定元素，并获取其矩形信息
  select
    .select(name)
    .boundingClientRect((rect) => {
      // 如果rect是一个数组，则返回
      if (!rect) return;
      if (Array.isArray(rect)) return multiple ? rect : rect[0];
      // 如果onSuccess存在，则调用onSuccess函数，并传入rect的高度
      onSuccess?.(rect);
    })
    .exec();
};

//- 小写数字转换成大写, 只处理到[0 ~ 99]
export const numberConvertToUppercase = (num) => {
  num = Number(num);
  const upperCaseNumber = [
    "零",
    "一",
    "二",
    "三",
    "四",
    "五",
    "六",
    "七",
    "八",
    "九",
    "十",
    "百",
    "千",
    "万",
    "亿",
  ];
  let length = String(num).length;
  if (length == 1) {
    return upperCaseNumber[num];
  } else if (length == 2) {
    if (num == 10) {
      return upperCaseNumber[num];
    } else if (num > 10 && num < 20) {
      return "十" + upperCaseNumber[String(num).charAt(1)];
    } else {
      return (
        upperCaseNumber[String(num).charAt(0)] +
        "十" +
        upperCaseNumber[String(num).charAt(1)].replace("零", "")
      );
    }
  }
};

// 将扁平数组转为树形结构
export const arrayToTree = ({
  list,
  id = "id",
  pid = "parent_id",
  firstId = 1,
}) => {
  let res = []; // 存放结果集
  let map = {};
  // 判断对象是否有某个属性
  let getHasOwnProperty = (obj, property) =>
    Object.prototype.hasOwnProperty.call(obj, property);

  // 边做map存储，边找对应关系
  for (const i of list) {
    map[i[id]] = {
      ...i,
      children: getHasOwnProperty(map, i[id]) ? map[i[id]].children : [],
    };
    const newItem = map[i[id]];
    if (i[pid] === firstId) {
      res.push(newItem);
    } else {
      if (!getHasOwnProperty(map, i[pid])) {
        map[i[pid]] = {
          children: [],
        };
      }
      map[i[pid]].children.push(newItem);
    }
  }
  return res;
};

// 防抖
export const debounce = (fn, delay = 300) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 节流
export const throttle = (fn, interval = 300) => {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= interval) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
};