utils.js 9.28 KB
import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { isArray } from 'util';
import { IMG_URL } from '@/common';
import { phoneReg } from '@/constants/reg';
import { message } from 'antd';
// 获取七牛图片
export function getImgUrl(imgname) {
  return `${IMG_URL}${imgname}`;
}

// 获取七牛图片的文件名
export function getFileName(fileurl) {
  let index1 = fileurl.lastIndexOf('/');
  let index2 = fileurl.length;
  fileurl = fileurl.substring(index1 + 1, index2);
  return fileurl;
}
// 获取文件类型
export function getFileType(file) {
  let filename = file;
  let index1 = filename.lastIndexOf('.');
  let index2 = filename.length;
  let type = filename.substring(index1, index2);
  return type;
}

/**
 * 将对象转换为以key对应的值为内容的数组
 * @param {Object} enums (将要转换的对象)
 */
export const objToArray = (enums = {}) => {
  const arr = [];
  Object.keys(enums).forEach(key => {
    arr.push(enums[key]);
  });
  return arr;
};
/**
 * 将数组转换为以指定字段为key的对象
 * @param {Array} arrs (将要转换的数组)
 * @param {String} key (以哪个字段作为对象的key)
 */
export const arrayToObj = (arrs = [], key = 'id') => {
  const params = {};
  for (let i = 0, len = arrs.length; i < len; i++) {
    const item = arrs[i];
    params[item[key]] = item;
  }
  return params;
};

// 将数字转换成金额显示
export const toMoney = num => {
  const type = Object.prototype.toString.call(num);

  switch (type) {
    case '[object Number]': {
      num = num.toFixed(2).replace('.00', '');
      break;
    }
    case '[object String]': {
      num -= 0;
      num = num.toFixed(2).replace('.00', '');
      break;
    }
    default: {
      num = '--';
    }
  }
  return num;
};

/**
 *
 * @param {*生成的独立id的长度} n
 * @param {*和将要生成的随机数作比较去重的id集合} arr
 * @param {*可用于生成随机数id的字符集合} str
 */
export const getUniqueId = (n, arr = [], comb = '123456789') => {
  const random = n => {
    let str = comb;
    let result = '';
    for (let i = 0; i < n; i++) {
      result += str[parseInt(Math.random() * str.length)];
    }

    if (arr.includes(result)) {
      random(n);
    } else {
      return result;
    }
  };

  return random(n);
};

export const isPhone = phone => phoneReg.test(phone);

/**
 * 判断数组里面是不是有重复项
 */
export const hasDuplicates = arr => {
  return _.uniq(arr).length !== arr.length;
};

/**
 * 获取权限配置数据
 */
export const getAuthData = (data = [], authObj) => {
  let dataMenu = []; // 菜单集合(不包含按钮菜单)
  let dataExpandedKeys = []; // 需要展开数的集合
  let { parentCode } = authObj;
  if (!parentCode) {
    data.push({ ...authObj });
  }
  function authFilter(data) {
    data = data.map(item => {
      if (item.code === parentCode) {
        item.subPermissionList.push({ ...authObj });
      }
      if (item.type !== 3) {
        dataMenu.push({
          name: item.name,
          code: item.code,
          url: item.url,
        });
      }
      dataExpandedKeys.push(item.code);

      const nextSubPermissionList = authFilter(item.subPermissionList);
      return {
        ...item,
        subPermissionList: nextSubPermissionList.length > 0 ? nextSubPermissionList : [],
      };
    });
    return data;
  }
  data = authFilter(data);
  return {
    data,
    dataMenu,
    dataExpandedKeys,
  };
};

/**
 * 编辑、删除权限
 */
export const getDelAuthData = (data = [], authObj, operateType) => {
  let { code, parentCode, oldCode } = authObj;
  let index = 0; // 次数
  function authFilter(data) {
    data = data
      .filter(_ => {
        if (_.subPermissionList.length > 0) {
          authFilter(_.subPermissionList);
        }
        return operateType === 'EDIT' ? _.code : _.code !== code;
      })
      .map(item => {
        /* 编辑时菜单没有改变 */
        if (!oldCode && code === item.code && operateType === 'EDIT') {
          item = { ...authObj };
        }
        /* 编辑时改变了菜单 */
        if (oldCode && item.code === oldCode) {
          let subData =
            item.subPermissionList.length > 1
              ? item.subPermissionList.filter(subItem => {
                  return subItem.code !== code;
                })
              : [];
          item.subPermissionList = subData;
        }
        if (index < 1 && oldCode && item.code === parentCode && operateType === 'EDIT') {
          index = index + 1;
          item.subPermissionList.push({ ...authObj, oldCode: undefined });
        }

        const nextSubPermissionList = authFilter(item.subPermissionList);
        return {
          ...item,
          subPermissionList: nextSubPermissionList.length > 0 ? nextSubPermissionList : [],
        };
      });
    return data;
  }
  data = authFilter(data);
  const { dataMenu, dataExpandedKeys } = getEditCode(data);
  return {
    data,
    dataMenu,
    dataExpandedKeys,
  };
};

/* 获取编辑之后的菜单和Code */
export const getEditCode = (data = []) => {
  let dataMenu = []; // 菜单集合(不包含按钮菜单)
  let dataExpandedKeys = []; // 需要展开数的集合
  function allFilter(data) {
    data.map(item => {
      if (item.type !== 3) {
        dataMenu.push({
          name: item.name,
          code: item.code,
          url: item.url,
        });
      }
      dataExpandedKeys.push(item.code);
      allFilter(item.subPermissionList);
    });
  }
  allFilter(data);
  return { dataMenu, dataExpandedKeys };
};

/**
 * 获取所有的code和除按钮菜单的菜单名称
 */
export const getAllMenuParams = (data = []) => {
  let allCode = [];
  let allMenuName = [];
  function allFilter(data) {
    data.map(item => {
      if (item.type !== 3) {
        allMenuName.push(item.name);
      }
      allCode.push(item.code);
      allFilter(item.subPermissionList);
    });
  }
  allFilter(data);
  return { allCode, allMenuName };
};

/**
 * 获得权限列表
 */
export const getPermissionList = (data = [], entry) => {
  let dataMenu = []; // 菜单集合(不包含按钮菜单)
  let dataExpandedKeys = []; // 需要展开数的集合
  function filterPermission(data) {
    data.map(item => {
      if (entry) {
        item.type =
          item.type === 3 || item.type === 'BTN'
            ? 3
            : (item.type === 'MENU' || item.type === 1) && item.parentId === 0
            ? 1
            : 2;
        item.key = item.code;
        dataExpandedKeys.push(item.code);
        if (item.type !== 3 && item.type !== 'BTN') {
          dataMenu.push({
            name: item.name,
            code: item.code,
            url: item.url,
          });
        }
        /* 加上parentCode */
        if (item.subPermissionList.length) {
          item.subPermissionList.map(_ => {
            _.parentCode = item.code;
          });
        }
      } else {
        item.type = item.type === 3 || item.type === 'BTN' ? 'BTN' : 'MENU';
        if (item.parentCode) {
          delete item.parentCode;
        }
        delete item.key;
      }
      filterPermission(item.subPermissionList);
    });
  }
  filterPermission(data);
  return !entry ? data : { data, dataMenu, dataExpandedKeys };
};

/* 获取拖拽之后的数据 */
export const getDragData = (data = []) => {
  let dataMenu = []; // 菜单集合(不包含按钮菜单)
  let dataExpandedKeys = []; // 需要展开数的集合
  let isFlag = false;
  let dragData = data.map(item => {
    if (item.type === 3) {
      message.warning('按钮不能做为一级菜单使用');
      isFlag = true;
    }
    return {
      ...item,
      type: 1,
      parentId: 0,
      parentCode: undefined,
    };
  });
  function allFilter(data) {
    data = data.map(item => {
      item.subPermissionList.map(_ => {
        if (_.parentId === 0) {
          message.warning('一级菜单不能做为子菜单');
          isFlag = true;
        }
      });
      if (item.type !== 1) {
        item.subPermissionList.map(_ => {
          _.parentCode = item.code;
        });
      }
      if (item.type !== 3) {
        dataMenu.push({
          name: item.name,
          code: item.code,
          url: item.url,
        });
      }
      if (item.type === 3 && item.subPermissionList.length) {
        message.warning('按钮下面不能有子类');
        isFlag = true;
      }
      dataExpandedKeys.push(item.code);

      const nextSubPermissionList = allFilter(item.subPermissionList);
      return {
        ...item,
        subPermissionList: nextSubPermissionList.length > 0 ? nextSubPermissionList : [],
      };
    });
    return data;
  }
  data = allFilter(dragData);
  let dataDragAuth = !isFlag ? data : [];
  return { dataDragAuth, dataMenu, dataExpandedKeys };
};

// 导出文件(流的形式)
export const ExportFile = (name, fn, params = {}) => {
  fn(params)
    .then(resp => {
      const blob = new Blob([resp]);
      let downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(blob); //创建下载的链接
      downloadElement.href = href;
      downloadElement.download = `${name}.xlsx`;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    })
    .catch(e => {
      message.error(`导出错误: e`);
      console.error(e);
    });
};