BearJiaUtil.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. import {BearJiaIcon} from '@/utils/BearJiaIcon.js';
  2. import axios from 'axios';
  3. import {saveAs} from 'file-saver';
  4. import {getToken} from '@/utils/auth';
  5. import {message, Modal} from 'ant-design-vue';
  6. import {getDicts as getDicts} from '@/api/system/dict/data';
  7. import {treeselect} from '@/api/system/dept';
  8. import {usePagination} from 'vue-request';
  9. import {blobValidate, handleTree, parseTime, tansParams} from '@/utils/bearjia.js';
  10. import request from '@/utils/request';
  11. const baseURL =
  12. import.meta.env.VITE_API_DOMAIN;
  13. const BearJiaUtil = {
  14. parseDateTime: function (dateTime, pattern) {
  15. return parseTime(dateTime, pattern);
  16. },
  17. getDictLabelByKey: function (key, dict) {
  18. // key为0时,判断返回false
  19. // if (key && dict) {
  20. if (dict) {
  21. for (let index = 0; index < dict.length; index++) {
  22. const element = dict[index];
  23. // 都转为字符后进行判断,防止数值类型和字符类型比较时,返回false
  24. if (element.value + '' === key + '') {
  25. return element.label;
  26. }
  27. }
  28. } else {
  29. return key;
  30. }
  31. },
  32. getPostNamesByPostIds: function (postIds, dict) {
  33. let postNames = '';
  34. for (let index = 0; index < dict.length; index++) {
  35. const element = dict[index];
  36. for (let i = 0; i < postIds.length; i++) {
  37. if (element.value === postIds[i]) {
  38. if (postNames === '') {
  39. postNames = element.label;
  40. } else {
  41. postNames = postNames + '、' + element.label;
  42. }
  43. }
  44. }
  45. }
  46. return postNames;
  47. },
  48. getRoleNamesByRoleIds: function (roleIds, dict) {
  49. let names = '';
  50. for (let index = 0; index < dict.length; index++) {
  51. const element = dict[index];
  52. for (let i = 0; i < roleIds.length; i++) {
  53. if (element.value === roleIds[i]) {
  54. if (names === '') {
  55. names = element.label;
  56. } else {
  57. names = names + '、' + element.label;
  58. }
  59. }
  60. }
  61. }
  62. return names;
  63. },
  64. getDeptNameByDeptId: function (deptId, treeData) {
  65. if (treeData) {
  66. let result = []; // 记录路径结果
  67. // 递归方法
  68. let recursiveFun = (curKey, path, data) => {
  69. if (data.length === 0) {
  70. return;
  71. }
  72. for (let dept of data) {
  73. path.push(dept.label);
  74. if (dept.id === curKey) {
  75. result = JSON.parse(JSON.stringify(path));
  76. return;
  77. }
  78. const children = Array.isArray(dept.children) ? dept.children : [];
  79. recursiveFun(curKey, path, children); // 遍历
  80. path.pop(); // 回溯
  81. }
  82. };
  83. // 通过递归方法获取路径
  84. recursiveFun(deptId, [], treeData);
  85. return result.join('/');
  86. } else {
  87. console.log('调用方法getDeptNameByDeptId时,传入的参数不正确!');
  88. }
  89. },
  90. getMenuNameByMenuId: function (menuId, treeData) {
  91. if (treeData) {
  92. for (let index = 0; index < treeData.length; index++) {
  93. let menu = treeData[index];
  94. if (menu.menuId === menuId) {
  95. return menu.menuName;
  96. }
  97. if (menu.children) {
  98. for (let index = 0; index < menu.children.length; index++) {
  99. let menu2 = menu.children[index];
  100. if (menu2.menuId === menuId) {
  101. return menu.menuName + ' / ' + menu2.menuName;
  102. }
  103. if (menu2.children) {
  104. for (let index2 = 0; index2 < menu2.children.length; index2++) {
  105. let menu3 = menu2.children[index2];
  106. if (menu3.menuId === menuId) {
  107. console.log('menu3.label=' + JSON.stringify(menu3.menuName));
  108. }
  109. }
  110. }
  111. }
  112. }
  113. }
  114. } else {
  115. console.log('调用方法getMenuNameByMenuId时,传入的参数不正确!');
  116. }
  117. },
  118. getIcon: function (iconName) {
  119. return BearJiaIcon({
  120. icon: iconName
  121. });
  122. },
  123. confirmDeleteSelectedData: function (okFun, cancelFun) {
  124. return Modal.confirm({
  125. content: '确认删除选中记录?',
  126. icon: BearJiaUtil.getIcon('ExclamationCircleOutlined'),
  127. onOk() {
  128. okFun();
  129. },
  130. });
  131. },
  132. confirmCleanAllData: function (okFun, cancelFun) {
  133. return Modal.confirm({
  134. content: '确认清空全部记录?',
  135. icon: BearJiaUtil.getIcon('ExclamationCircleOutlined'),
  136. onOk() {
  137. okFun();
  138. },
  139. });
  140. },
  141. confirmOperate: function (operateName, okFun, cancelFun) {
  142. return Modal.confirm({
  143. content: '确认进行【' + operateName + '】操作吗?',
  144. icon: BearJiaUtil.getIcon('ExclamationCircleOutlined'),
  145. onOk() {
  146. okFun();
  147. },
  148. });
  149. },
  150. // 将form中所有字段的值清空
  151. resetFormFieldsToEmpty: function (objData, arrData) {
  152. for (let ele in objData) {
  153. if (objData[ele] instanceof Array) {
  154. objData[ele] = [];
  155. } else {
  156. if (ele === 'params') {
  157. objData[ele] = {};
  158. } else {
  159. objData[ele] = '';
  160. }
  161. }
  162. }
  163. for (let arrEle in arrData) {
  164. arrData[arrEle] = [];
  165. }
  166. },
  167. getDeptTreeData: function () {
  168. return treeselect();
  169. },
  170. getDictsByType: function (type) {
  171. return new Promise((resolve, reject) => {
  172. var dicts = [];
  173. getDicts(type).then((res) => {
  174. for (let d of res.data) {
  175. if (d) {
  176. dicts.push({
  177. value: d.dictValue,
  178. label: d.dictLabel,
  179. cssClass: d.cssClass,
  180. listClass: d.listClass
  181. });
  182. }
  183. }
  184. resolve(dicts);
  185. });
  186. });
  187. },
  188. // 调用后端列表查询方法,通过返回结果设置tableObj.total,tableObj.dataSource,tableObj.loading
  189. getTableDataByQueryFunc: function (queryFunc, tableObj) {
  190. tableObj.loading = true;
  191. queryFunc.then((res) => {
  192. // 获取列表记录数
  193. tableObj.total = res.total;
  194. // 获取列表数据
  195. if (res.rows) {
  196. tableObj.dataSource = res.rows;
  197. } else if (res.data) {
  198. tableObj.dataSource = res.data;
  199. }
  200. tableObj.loading = false;
  201. });
  202. },
  203. // 转为树形结构:调用后端列表查询方法,通过返回结果设置tableObj.total,tableObj.dataSource,tableObj.loading
  204. getTableTreeByQueryFunc: function (queryFunc, tableObj, treeId) {
  205. tableObj.loading = true;
  206. queryFunc.then((res) => {
  207. // 获取列表记录数
  208. tableObj.total = res.total;
  209. // 获取列表数据
  210. if (res.rows) {
  211. tableObj.dataSource = handleTree(res.rows, treeId);
  212. } else if (res.data) {
  213. tableObj.dataSource = handleTree(res.data, treeId);
  214. }
  215. tableObj.loading = false;
  216. });
  217. },
  218. tableHandChangePage: function (tablePage, page, filters, sorter) {
  219. tablePage.run({
  220. results: page.pageSize,
  221. page: page?.current,
  222. sortField: sorter.field,
  223. sortOrder: sorter.order,
  224. ...filters,
  225. });
  226. },
  227. // 获取翻页工具栏对象
  228. createTablePagination: function (tableObj, queryForm) {
  229. return {
  230. total: tableObj.total,
  231. current: queryForm.data.pageNum,
  232. pageSize: queryForm.data.pageSize,
  233. showSizeChanger: true,
  234. showTotal: function (total, range) {
  235. return `第${range[0]}-${range[1]}条,共${total}条`;
  236. },
  237. };
  238. },
  239. getTablePagination: function (table) {
  240. return {
  241. total: table.total,
  242. current: table.current.value,
  243. pageSize: table.pageSize.value,
  244. showSizeChanger: true,
  245. showTotal: function (total, range) {
  246. return `第${range[0]}-${range[1]}条,共${total}条`;
  247. },
  248. };
  249. },
  250. usePagination: function (queryListFun, tableData) {
  251. return usePagination(queryListFun, {
  252. formatResult: (res) => {
  253. // 获取列表记录数
  254. tableData.total = res.total;
  255. // 获取列表数据
  256. if (res.rows) {
  257. tableData.dataSource = res.rows;
  258. } else if (res.data) {
  259. tableData.dataSource = res.data;
  260. }
  261. },
  262. pagination: {
  263. currentKey: 'page', // 这个必须为page,否则翻页不好使
  264. pageSizeKey: 'results', // 这个必须为results,否则切换每页显示多少条不好使
  265. },
  266. });
  267. },
  268. usePaginationByHandleTree: function (queryListFun, tableData, treeId) {
  269. return usePagination(queryListFun, {
  270. formatResult: (res) => {
  271. // 获取列表记录数
  272. tableData.total = res.total;
  273. // 获取列表数据
  274. if (res.rows) {
  275. tableData.dataSource = handleTree(res.rows, treeId);
  276. } else if (res.data) {
  277. tableData.dataSource = handleTree(res.data, treeId);
  278. }
  279. },
  280. pagination: {
  281. currentKey: 'page', // 这个必须为page,否则翻页不好使
  282. pageSizeKey: 'results', // 这个必须为results,否则切换每页显示多少条不好使
  283. },
  284. });
  285. },
  286. getPostDict: function (postOptions) {
  287. var dict = [];
  288. for (let index = 0; index < postOptions.length; index++) {
  289. let element = postOptions[index];
  290. if (element.status != 1) {
  291. dict.push({
  292. value: element.postId,
  293. label: element.postName
  294. });
  295. }
  296. }
  297. return dict;
  298. },
  299. getRoleDict: function (roleOptions) {
  300. var dict = [];
  301. for (let index = 0; index < roleOptions.length; index++) {
  302. let element = roleOptions[index];
  303. if (element.status != 1) {
  304. dict.push({
  305. value: element.roleId,
  306. label: element.roleName
  307. });
  308. }
  309. }
  310. return dict;
  311. },
  312. messageInfo: function (msg) {
  313. if (msg) {
  314. message.info(msg);
  315. } else {
  316. message.info('请求操作成功。');
  317. }
  318. },
  319. messageSuccess: function (msg) {
  320. if (msg) {
  321. message.success(msg);
  322. } else {
  323. message.success('请求操作成功。');
  324. }
  325. },
  326. messageWarn: function (msg) {
  327. if (msg) {
  328. message.warn(msg);
  329. } else {
  330. message.warn('请确认操作是否正确!');
  331. }
  332. },
  333. messageError: function (msg) {
  334. if (msg) {
  335. message.error(msg);
  336. } else {
  337. message.error('请求操作失败!');
  338. }
  339. },
  340. showTableTotal: function (total, range) {
  341. return `${range[0]}-${range[1]} of ${total} items`;
  342. },
  343. zip(url, name) {
  344. var url = baseURL + url;
  345. axios({
  346. method: 'get',
  347. url: url,
  348. responseType: 'blob',
  349. headers: {
  350. Authorization: 'Bearer ' + getToken()
  351. },
  352. }).then(async (res) => {
  353. const isLogin = await blobValidate(res.data);
  354. if (isLogin) {
  355. const blob = new Blob([res.data], {
  356. type: 'application/zip'
  357. });
  358. saveAs(blob, name);
  359. } else {
  360. printErrMsg(res.data);
  361. }
  362. });
  363. },
  364. // 对应后端处理方式
  365. download(url, params, fileName) {
  366. BearJiaUtil.messageInfo('开始下载数据,请稍候...');
  367. const baseURL = import.meta.env.VITE_API_DOMAIN;
  368. request.post(url, params, {
  369. transformRequest: [
  370. (params) => {
  371. return tansParams(params);
  372. },
  373. ],
  374. headers: {
  375. 'Content-Type': 'application/x-www-form-urlencoded'
  376. },
  377. responseType: 'blob',
  378. })
  379. .then(async (response) => {
  380. const isLogin = await blobValidate(response);
  381. if (isLogin) {
  382. const blob = new Blob([response], {
  383. type: 'application/octet-stream'
  384. });
  385. saveAs(blob, fileName);
  386. } else {
  387. printErrMsg(response);
  388. }
  389. })
  390. .catch((r) => {
  391. console.error(r);
  392. BearJiaUtil.messageError('下载文件出现错误,请联系管理员!');
  393. });
  394. },
  395. // 构造树型结构数据
  396. handleTree: function(data, id, parentId, children) {
  397. return handleTree(data, id, parentId, children);
  398. },
  399. /**
  400. * 清理空值,对象
  401. * @param children
  402. * @returns {*[]}
  403. */
  404. filterEmpty: function (children = []) {
  405. return children.filter(c => c.tag || (c.text && c.text.trim() !== ''));
  406. },
  407. /**
  408. * 获取字符串长度,英文字符 长度1,中文字符长度2
  409. * @param {*} str
  410. */
  411. getStrFullLength: function (str = '') {
  412. return str.split('').reduce((pre, cur) => {
  413. const charCode = cur.charCodeAt(0);
  414. if (charCode >= 0 && charCode <= 128) {
  415. return pre + 1;
  416. }
  417. return pre + 2;
  418. }, 0);
  419. },
  420. /**
  421. * 截取字符串,根据 maxLength 截取后返回
  422. * @param {*} str
  423. * @param {*} maxLength
  424. */
  425. cutStrByFullLength: function (str = '', maxLength) {
  426. let showLength = 0;
  427. return str.split('').reduce((pre, cur) => {
  428. const charCode = cur.charCodeAt(0);
  429. if (charCode >= 0 && charCode <= 128) {
  430. showLength += 1;
  431. } else {
  432. showLength += 2;
  433. }
  434. if (showLength <= maxLength) {
  435. return pre + cur;
  436. }
  437. return pre;
  438. }, '');
  439. },
  440. };
  441. export default BearJiaUtil;