import { ref } from "vue";
/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params: any) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof value[key] !== "undefined") {
            const params = propName + "[" + key + "]";
            const subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 构造树型结构数据
export function handleTree(arr: any, id: string) {
  // 数组去重
  arr = arr.filter((item: any, index: number) => {
    if (arr.findIndex((ite: any) => ite[id] === item[id]) === index) {
      return item;
    }
  });

  function turnTree(arr: any, id: string) {
    const tree = ref<any>([]);
    for (let i = 0; i < arr.length; i++) {
      const isFirst = tree.value.findIndex((item: any) => arr[i][id].includes(item[id]));
      if (isFirst !== -1) {
        tree.value[isFirst].children.push(arr[i]);
      } else {
        arr[i].children = [];
        tree.value.push(arr[i]);
      }
    }
    return tree.value;
  }
  return turnTree(arr, id);
}
