index.js 10.8 KB
Newer Older
duanledexianxianxian's avatar
duanledexianxianxian committed
1 2 3
// eslint-disable-next-line eslint-comments/disable-enable-pair
/* eslint-disable no-bitwise */
import pathToRegexp from 'path-to-regexp';
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
4
import { parse } from 'qs';
duanledexianxianxian's avatar
duanledexianxianxian committed
5
import { async } from 'q';
duanledexianxianxian's avatar
sync  
duanledexianxianxian committed
6 7 8 9 10 11 12

/**
 * 获取链接的query url部分
 */
export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}
duanledexianxianxian's avatar
duanledexianxianxian committed
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

export const generateUUID = () => {
  let d = new Date().getTime();
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
  });
  return uuid;
};

/**
 * 检查是否为正确的移动的电话号码
 */
export const checkMobilePhone = mobilePhone => {
  if (!/^1(3|4|5|7|8)\d{9}$/.test(mobilePhone)) {
    return false;
  }
  return true;
};

/**
 * 检查是否为正确的邮箱
 */

export const checkEmail = mobilePhone => {
  const reg = new RegExp(
    '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$',
  );
  if (!reg.test(mobilePhone)) {
    return false;
  }
  return true;
};

/**
 * 检查是否为正确的密码
 * @param {*} password
 */
export const checkPassword = password => {
  const reg = new RegExp(/^(\w){6,20}$/);
  if (!reg.test(password)) {
    return false;
  }
  return true;
};

/**
 * 转换后端返回的表格数据成前端使用的表格数据
 * @param {object} data 后端数据
 * @param {object} option
 * @param {string} option.keyCode 指定唯一标识字段
 * @param {function} option.onChange 分页回调
 */
export const trimTableData = (data = {}, option = {}) => {
  const { records = [], current = 1, pageSize = 1, total = 1 } = data;
  const { keyCode, onChange } = option;
  let tableData = records;
  const pageData = {
    current,
    pageSize,
    total,
  };
  if (keyCode) {
    tableData = records.map(item => ({ key: item[keyCode], ...item }));
  }
  if (typeof onChange === 'function') {
    pageData.onChange = onChange;
  }
  return {
    tableData,
    pageData,
  };
};

/**
 * 转换后端返回的静态数据为key、value格式
 * @param {object} staticData 后端静态数据
 * @param {string} staticKey 需要处理的静态数据唯一ID
 */
export const trimStaticData = (staticData = {}, staticKey) =>
  (staticData[staticKey] || [])
    // .filter(item => item.paramLocale === "zh_CN")
    .map(item => ({
      key: item.paramValue,
      value: item.paramName,
    }));

/**
 * 处理后端返回的组织数据为供Select组件使用的带结构数据
 * @param {object} data
 */
export const trimOrgaData = data => {
  const trimData = clone(
    data.map(item => ({
      ...item,
      title: item.orgName,
      value: item.orgId,
      key: item.orgId,
    })),
  );
  const orgaData = trimData.filter(item => item.orgType === 1);
  const depaData = trimData.filter(item => item.orgType === 2);

  // 处理部门数据
  depaData.forEach(item => {
    const orgaKey = orgaData.findIndex(orgaItem => orgaItem.orgId === item.parentOrgId);
    if (orgaKey > -1) {
      const children = orgaData[orgaKey].children || [];
      children.push(item);
      orgaData[orgaKey].children = [...children];
    }
  });

  // 处理公司数据
  // 目前只支持两层数据
  return orgaData.reduce((container, item) => {
    const orgaKey = container.findIndex(orgaItem => orgaItem.orgId === item.parentOrgId);
    if (orgaKey > -1) {
      const children = container[orgaKey].children || [];
      children.push(item);
      container[orgaKey].children = [...children];
    } else {
      container.push(item);
    }
    return container;
  }, []);
};

export const treeDataTransform = (data = [], key = 'id', parentKey = 'parendId', rootPid = -1) => {
  const midObj = {};
  const arr = [];

  data.sort((a, b) => b[parentKey] - a[parentKey]);

  // eslint-disable-next-line
  const translator = data => {
    if (!data || !data.length) {
      return data;
    }
    data.forEach((item, index) => {
      const nowPid = item[parentKey];
      const nowId = item[key];

      if (nowPid !== rootPid) {
        translator(item);
        delete data[index];
      }

      // 建立当前节点的父节点的children 数组
      if (midObj[nowPid]) {
        midObj[nowPid].push(item);
      } else {
        midObj[nowPid] = [];
        midObj[nowPid].push(item);
      }
      // 将children 放入合适的位置
      if (midObj[nowId]) {
        item.children = midObj[nowId];
        delete midObj[nowId];
        if (item && data[index]) {
          arr.push(item);
        }
      }
    });
  };
  translator(data);
  return arr;
};

export const treeTransform1 = (data = [], key = 'id', parentKey = 'parendId', rootPid = -1) => {
  const parents = data.filter(
    item => item[parentKey] === rootPid || item[parentKey] === 'undefined',
  );
  const children = data.filter(
    item => item[parentKey] !== rootPid && item[parentKey] !== 'undefined',
  );

  // eslint-disable-next-line
  const translator = (parents, children) => {
    parents.forEach(parent => {
      children.forEach((current, index) => {
        if (current[parentKey] !== parent[key]) {
          return;
        }
        const temp = JSON.parse(JSON.stringify(children));
        temp.splice(index, 1);
        if (typeof parent.children !== 'undefined') {
          parent.children.push(current);
        } else {
          parent.children = [current];
        }
        return translator([current], temp);
      });
    });
  };

  translator(parents, children);

  return parents;
};

/**
 * 平级数组菜单列表转成树形菜单列表
 * @param {平级数组菜单列表} flatMenuList
 */
export const toTreeMenuList = (flatMenuList = []) => {
  const tree = [];
  const key = 'menuId';
  const pKey = 'pMenuId';
  const topFlag = 0;

  if (flatMenuList) {
    const dict = {};
    // add  rood node
    flatMenuList.forEach(item => {
      dict[item[key]] = item;
      if (equals(item[pKey], topFlag) || item[pKey] === '') {
        item.level = 0;
        item.key = String(item[key]);
        item.icon = item.menuIcon;
        item.link = item.menuUrl;
        item.title = item.menuName;
        tree[tree.length] = item; // 添加根节点,可能有多个节点
      }
    });
    flatMenuList.forEach(item => {
      const child = item;
      if (equals(child[pKey], topFlag) || child[pKey] === '') {
        return;
      }
      const parent = dict[child[pKey]];
      if (parent) {
        // child.parent = parent;
        if (!parent.children) {
          parent.children = [];
        }
        child.key = String(child[key]);
        child.level = parent.level + 1;
        child.icon = child.menuIcon;
        child.link = child.menuUrl;
        child.title = child.menuName;
        parent.children[parent.children.length] = child;
      }
    });
    return tree;
  }
};

/**
 * 平级组织部门转换成树形组织部门
 * @param {*} flatList
 */
export const toDepaTree = (flatList = []) =>
  flatListToTree(flatList, 'orgId', 'parentOrgId', 0, {
    title: 'orgName',
    value: 'orgId',
  });

/**
 * 平级数组部门-组织列表转成树形部门-组织列表
 * @param {评级列表} flatList
 * @param {*} key
 * @param {*} pKey
 * @param {*} topFlag
 * @param {*} extentProcess
 */
export const flatListToTree = (
  flatList = [],
  key = 'id',
  pKey = 'pId',
  topFlag = 0,
  mappingData = {},
) => {
  const tree = [];
  if (flatList) {
    const dict = {};
    // add  rood node
    flatList.forEach(item => {
      dict[item[key]] = item;
      if (equals(item[pKey], topFlag) || item[pKey] === '') {
        item.level = 0;
        item.key = String(item[key]);

        Object.keys(mappingData).forEach(k => {
          item[k] = item[mappingData[k]];
        });

        tree[tree.length] = item; // 添加根节点,可能有多个节点
      }
    });
    flatList.forEach(item => {
      const child = item;
      if (equals(child[pKey], topFlag) || child[pKey] === '') {
        return;
      }
      const parent = dict[child[pKey]];
      if (parent) {
        // child.parent = parent;
        if (!parent.children) {
          parent.children = [];
        }
        child.key = String(child[key]);
        child.level = parent.level + 1;

        Object.keys(mappingData).forEach(k => {
          child[k] = child[mappingData[k]];
        });

        parent.children[parent.children.length] = child;
      }
    });
    return tree;
  }
};

/**
 * url转成数组
 * /userinfo/2144/id => ['/userinfo','/useinfo/2144,'/userindo/2144/id']
 * @param {url} url
 */
export function urlToList(url) {
  const urllist = url.split('/').filter(i => i);
  return urllist.map((urlItem, index) => `/${urllist.slice(0, index + 1).join('/')}`);
}

/**
 * 判断路径是否匹配了菜单旅游业经
 * @param {*} flatMenuList
 * @param {*} path
 */
export const getMenuMatches = (flatMenuList, path) =>
  flatMenuList.filter(item => {
    if (item.menuUrl) {
      return pathToRegexp(item.menuUrl).test(path);
    }
    return false;
  });

/**
 * 获得当前选中的菜单key
 * @param {*} flatMenuList
 * @param {*} path
 */
export const getSelectedkey = (flatMenuList = [], pathname) => {
  const items = urlToList(pathname)
    .map(item => getMenuMatches(flatMenuList, item)[0])
    .filter(item => item);
  return items && items.length > 0 ? String(items[items.length - 1].menuId) : '';
};

export const getDefaultOpenKeys = (flatMenuList = [], pathname) => {
  const openKeys = [];
  const topFlag = 0;
  if (flatMenuList.length > 0) {
    const key = getSelectedkey(flatMenuList, pathname);
    const menuIdMap = {};
    const pMenuIdMap = {};
    flatMenuList.forEach(item => {
      menuIdMap[item.menuId] = item;
      pMenuIdMap[item.pMenuId] = item;
    });
    if (key === '') {
      openKeys.push(String(pMenuIdMap[topFlag].menuId));
    } else {
      let t = key;
      for (let i = 0; i < flatMenuList.length; i += 1) {
        if (equals(t, topFlag)) {
          break;
        }
        if (menuIdMap[t]) {
          openKeys.push(String(menuIdMap[t].menuId));
          t = menuIdMap[t].pMenuId;
        }
      }
    }
  }
  return openKeys;
};

/**
 * 文件下载
 * @param {*} url
 * @param {*} fileNames
 * @param  {...any} params
 */
export async function downloadFile(url, params) {
  const token = storage.get('token');
  const formEle = document.createElement('form');
  formEle.method = 'get';
  formEle.style = 'display:none;';
  formEle.action = url;

  const tokenEle = document.createElement('input');
  tokenEle.type = 'hidden';
  tokenEle.name = 'token';
  tokenEle.value = token;
  formEle.appendChild(tokenEle);

  for (const key in params) {
    if (key && params[key]) {
      const paramsEle = document.createElement('input');
      paramsEle.type = 'hidden';
      paramsEle.name = key;
      paramsEle.value = params[key];
      formEle.appendChild(paramsEle);
    }
  }

  document.body.appendChild(formEle);
  formEle.submit();
  document.body.removeChild(formEle);
}