


// 获取url参数
/**
 * 
 * @param {*} name 需要获取的query名
 * @returns 
 */


 import { useRequest,request,history } from 'umi';
 import { stringify } from 'querystring';



const getQueryString = (name)=>{
    const reg = new RegExp(`(^|&)${ name }=([^&]*)(&|$)`);
    const r = window.location.search.substr(1).match(reg);
 
    if (r != null) {
        return decodeURIComponent(r[2]);
    };
    return null;
} 


  /**
 * 退出登录，并且将当前的 url 保存
 */
   const loginOut = async () => {

    const { query = {}, pathname } = history.location;
    const { redirect } = query;
    const hospSign = localStorage.getItem('hospSign');
    

    if (window.location.pathname !== '/user/login' && !redirect) {
      localStorage.removeItem('userData');
    //   history.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect:pathname,
    //       hospSign:hospSign
    //     }),
    //   });
      
    }
  };



/**
 * 
 * @param {Function} requestFunc request函数
 */
const CARequest = (url)=>{
      const { data, error, loading } = useRequest(() => {
        return request(url);
      });
      console.log({data, error, loading});
      
}

// 递归获取所有层级某一属性
const deepGetVal = (dataToDeep,key,subArr)=>{
    // console.log({dataToDeep,key,subArr});
    const resultArr = [];
    
    function looper(dataToDeep,key,subArr){
        dataToDeep.forEach(item=>{
            if(item[subArr]&&item[subArr].length>0){
                resultArr.push(item[key]);
                looper(item[subArr],key,subArr);
            }else {
                resultArr.push(item[key]);
            }
        });
    }
    looper(dataToDeep,key,subArr);

    return resultArr
}

// 递归获取所有有树子集的节点
const deepGetAllParents = (dataToDeep,subArr)=>{
    const resultArr = [];

    function looper(dataToDeep,subArr){
        dataToDeep.forEach(item=>{
            if(item[subArr]&&item[subArr].length>0){
                resultArr.push(item);
                // console.log({resultArr});
                looper(item[subArr],subArr);
            }
        });
    };

    looper(dataToDeep,subArr);

    return resultArr
    
}

// 数组去重
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    const array = [];
    for (let i = 0; i < arr.length; i++) {
        if (array .indexOf(arr[i]) === -1) {
            array .push(arr[i])
        }
    }
    return array;
}

export  {
    getQueryString,
    CARequest,
    deepGetVal,
    deepGetAllParents,
    unique,
    loginOut
}