/*
 * @Author: your name
 * @Date: 2022-01-13 17:09:05
 * @LastEditTime: 2023-08-16 16:39:42
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/utils.js
 */


import axios from 'axios';

export const randomString = (length: number) => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_=-';
  let result = '';
  for (let i = length; i > 0; --i) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
};

export interface TreeItemType {
  children?: TreeItemType[];
  [key: string]: any;
}

//获取树结构指定的值集合
export const getValsFromTree = (data: TreeItemType[], key: string) => {
  let result: any[] = [];
  function looper(data: TreeItemType[], key: string) {
    data.forEach((t) => {
      if (t[key]) {
        result.push(t[key]);
      }
      if (t.children && t.children.length > 0) {
        looper(t.children, key);
      }
    });
  }
  looper(data, key);
  return result;
};

export const searchTree = (treeData: TreeItemType[]) => {};



export const downloadTemplateReq = (path:string) => {

  const userData = localStorage.getItem('userData');
  const { token = '' } = JSON.parse(userData as any);

  axios({
      method: 'get',
      url: `/gateway/${path}`,
      responseType: 'blob',
      headers: { token },
  })
      .then(function (response:any) {
          //console.log({ 'chunk': response });
          const filename = decodeURI(response.headers["content-disposition"]);
          const objectUrl = URL.createObjectURL(
              new Blob([response.data], {
                  type: 'application/vnd.ms-excel',
              })
          )
          const link = document.createElement('a')
          // 设置导出的文件名称
          link.download = `${filename}` + '.xls'
          link.style.display = 'none'
          link.href = objectUrl
          link.click()
          document.body.appendChild(link)

      });



}




let parent:any = undefined;

export const getDeepestTreeData:any= (tree:any,childrenName:string)=>{
     
      if(tree[`${childrenName}`]&&tree[`${childrenName}`].length>0){
           parent = tree;
           return getDeepestTreeData(tree[`${childrenName}`][0],childrenName)    
      }

      return  [tree,parent] 
}



export const  uniqueFunc = (arr:any[], uniId:string) => {
  const res = new Map();
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}


//获取树结构的所有叶子节点

interface TreeNode {
  [key:string]:any
  child?: TreeNode[];
}


export const  getLeafNodes = (node: TreeNode, leaves: TreeNode[] = []): TreeNode[] => {
  if (!node.child || node.child.length === 0) {
    leaves.push(node);
  } else {
    for (const child of node.child) {
      getLeafNodes(child, leaves);
    }
  }
  return leaves;
}



//根据树结构中的某个属性的集合，获取对应的节点，返回一个集合

export const findNodesBySomes = (node: TreeNode, keys: Set<string|number>,str:string): TreeNode[] => {
  let results: TreeNode[] = [];

  if (keys.has(node[`${str}`])) {
      results.push(node);
  }

  if (node.child) {
      for (let child of node.child) {
          results = results.concat(findNodesBySomes(child,keys,str));
      }
  }

  return results;
}






