index.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. import { isArray, isNullOrUnDef, isNumber, isString, isDate, isObject } from "@/utils/is";
  2. import { FieldNamesProps } from "@/components/LjVxeTable/interface";
  3. import XEUtils from "xe-utils";
  4. import { cloneDeep, pick, get } from "lodash-es";
  5. import dayjs from "dayjs";
  6. import { useAuthButtons } from "@/hooks/useAuthButtons";
  7. import { useUserStore } from "@/stores/modules/user";
  8. import { GetFormulaCompute } from "@/api/modules/common";
  9. import { ElMessage } from "element-plus";
  10. import type { Menu } from "@/typings/global";
  11. /**
  12. * @description 获取localStorage
  13. * @param {String} key Storage名称
  14. * @returns {String}
  15. */
  16. export function localGet(key: string) {
  17. const value = window.localStorage.getItem(key);
  18. try {
  19. return JSON.parse(window.localStorage.getItem(key) as string);
  20. } catch (error) {
  21. return value;
  22. }
  23. }
  24. /**
  25. * @description 存储localStorage
  26. * @param {String} key Storage名称
  27. * @param {*} value Storage值
  28. * @returns {void}
  29. */
  30. export function localSet(key: string, value: any) {
  31. window.localStorage.setItem(key, JSON.stringify(value));
  32. }
  33. /**
  34. * @description 清除localStorage
  35. * @param {String} key Storage名称
  36. * @returns {void}
  37. */
  38. export function localRemove(key: string) {
  39. window.localStorage.removeItem(key);
  40. }
  41. /**
  42. * @description 清除所有localStorage
  43. * @returns {void}
  44. */
  45. export function localClear() {
  46. window.localStorage.clear();
  47. }
  48. /**
  49. * @description 判断数据类型
  50. * @param {*} val 需要判断类型的数据
  51. * @returns {String}
  52. */
  53. export function isType(val: any) {
  54. if (val === null) return "null";
  55. if (typeof val !== "object") return typeof val;
  56. else return Object.prototype.toString.call(val).slice(8, -1).toLocaleLowerCase();
  57. }
  58. /**
  59. * @description 生成唯一 uuid
  60. * @returns {String}
  61. */
  62. export function generateUUID() {
  63. let uuid = "";
  64. for (let i = 0; i < 32; i++) {
  65. let random = (Math.random() * 16) | 0;
  66. if (i === 8 || i === 12 || i === 16 || i === 20) uuid += "-";
  67. uuid += (i === 12 ? 4 : i === 16 ? (random & 3) | 8 : random).toString(16);
  68. }
  69. return uuid;
  70. }
  71. /**
  72. * 判断两个对象是否相同
  73. * @param {Object} a 要比较的对象一
  74. * @param {Object} b 要比较的对象二
  75. * @returns {Boolean} 相同返回 true,反之 false
  76. */
  77. export function isObjectValueEqual(a: { [key: string]: any }, b: { [key: string]: any }) {
  78. if (!a || !b) return false;
  79. let aProps = Object.getOwnPropertyNames(a);
  80. let bProps = Object.getOwnPropertyNames(b);
  81. if (aProps.length != bProps.length) return false;
  82. for (let i = 0; i < aProps.length; i++) {
  83. let propName = aProps[i];
  84. let propA = a[propName];
  85. let propB = b[propName];
  86. if (!b.hasOwnProperty(propName)) return false;
  87. if (propA instanceof Object) {
  88. if (!isObjectValueEqual(propA, propB)) return false;
  89. } else if (propA !== propB) {
  90. return false;
  91. }
  92. }
  93. return true;
  94. }
  95. /**
  96. * @description 生成随机数
  97. * @param {Number} min 最小值
  98. * @param {Number} max 最大值
  99. * @returns {Number}
  100. */
  101. export function randomNum(min: number, max: number): number {
  102. let num = Math.floor(Math.random() * (min - max) + max);
  103. return num;
  104. }
  105. /**
  106. * @description 获取当前时间对应的提示语
  107. * @returns {String}
  108. */
  109. export function getTimeState(t: any) {
  110. // @ts-ignore
  111. let timeNow = new Date();
  112. let hours = timeNow.getHours();
  113. if (hours >= 6 && hours <= 10) return t("sys.greetings.morning") + ` ⛅`;
  114. if (hours >= 10 && hours <= 13) return t("sys.greetings.noon") + ` 🌞`;
  115. if (hours >= 13 && hours <= 18) return t("sys.greetings.afternoon") + ` 🌞`;
  116. if (hours >= 18 && hours <= 24) return t("sys.greetings.evening") + ` 🌛`;
  117. if (hours >= 0 && hours <= 6) return t("sys.greetings.deadOfNight") + ` 🌑`;
  118. }
  119. /**
  120. * @description 获取浏览器默认语言
  121. * @returns {String}
  122. */
  123. export function getBrowserLang() {
  124. let browserLang = navigator.language ? navigator.language : navigator.browserLanguage;
  125. console.log("getBrowserLang browserLang :>> ", browserLang);
  126. let defaultBrowserLang = "";
  127. if (["cn", "zh", "zh-cn"].includes(browserLang.toLowerCase())) {
  128. defaultBrowserLang = "zh-cn";
  129. } else {
  130. defaultBrowserLang = "en";
  131. }
  132. return defaultBrowserLang;
  133. }
  134. /**
  135. * @description 使用递归扁平化菜单,方便添加动态路由
  136. * @param {Array} menuList 菜单列表
  137. * @returns {Array}
  138. */
  139. export function getFlatMenuList(menuList: Menu.MenuOptions[]): Menu.MenuOptions[] {
  140. let newMenuList: Menu.MenuOptions[] = JSON.parse(JSON.stringify(menuList));
  141. // let newMenuList: Menu.MenuOptions[] = menuList;
  142. return newMenuList.flatMap(item => [item, ...(item.children ? getFlatMenuList(item.children) : [])]);
  143. }
  144. /**
  145. * @description 使用递归过滤出需要渲染在左侧菜单的列表 (需剔除 isHide == true 的菜单)
  146. * @param {Array} menuList 菜单列表
  147. * @returns {Array}
  148. * */
  149. export function getShowMenuList(menuList: Menu.MenuOptions[]) {
  150. const { CheckPower } = useAuthButtons(undefined);
  151. let newMenuList: Menu.MenuOptions[] = cloneDeep(menuList);
  152. return newMenuList.filter(item => {
  153. if (item.meta.funid && !CheckPower(item.meta.funid)) {
  154. return false;
  155. }
  156. // 父级节点隐藏,跳过,不需要再递归子级节点
  157. !item.meta?.isHide && item.children?.length && (item.children = getShowMenuList(item.children));
  158. // 过滤隐藏节点
  159. return !item.meta?.isHide;
  160. });
  161. }
  162. /**
  163. * @description 使用递归找出所有面包屑存储到 pinia/vuex 中
  164. * @param {Array} menuList 菜单列表
  165. * @param {Array} parent 父级菜单
  166. * @param {Object} result 处理后的结果
  167. * @returns {Object}
  168. */
  169. export const getAllBreadcrumbList = (menuList: Menu.MenuOptions[], parent = [], result: { [key: string]: any } = {}) => {
  170. for (const item of menuList) {
  171. result[item.path] = [...parent, item];
  172. if (item.children) getAllBreadcrumbList(item.children, result[item.path], result);
  173. }
  174. return result;
  175. };
  176. /**
  177. * @description 使用递归过滤出需要渲染在首页常用功能树 (需剔除 isHide == true 的菜单)
  178. * @param {Array} menuList 菜单列表
  179. * @returns {Array}
  180. * */
  181. export function getQuickEnterFuncTree(menuList: Menu.MenuOptions[]): any[] {
  182. class TreeNode {
  183. key: string;
  184. label: string;
  185. children: TreeNode[] | null;
  186. icon?: string;
  187. path?: string;
  188. disabled: boolean;
  189. constructor(key: string, label: string, hasChild?: boolean) {
  190. this.key = key;
  191. this.label = label;
  192. this.children = hasChild ? [] : null;
  193. }
  194. public get getIcon(): string | undefined {
  195. return this.icon;
  196. }
  197. public set setIcon(v: string) {
  198. this.icon = v;
  199. }
  200. public get getPath(): string | undefined {
  201. return this.path;
  202. }
  203. public set setPath(v: string) {
  204. this.path = v;
  205. }
  206. }
  207. const { userInfo } = useUserStore();
  208. const recursiveFunTree = (children: Menu.MenuOptions[]): TreeNode[] => {
  209. let treeArray: TreeNode[] = [];
  210. for (const menu of children) {
  211. if (menu.meta?.isHide) continue;
  212. let treeNode = new TreeNode(menu.name, menu.meta?.title, isNullOrUnDef(menu.children));
  213. if (isNullOrUnDef(menu.component)) treeNode.path = menu.path;
  214. if (isNullOrUnDef(menu.meta?.icon)) treeNode.icon = menu.meta?.icon;
  215. if (!isNullOrUnDef(menu.meta?.funid))
  216. treeNode.disabled = userInfo?.rsltFunids && !userInfo?.rsltFunids.includes(menu.meta?.funid);
  217. if (isNullOrUnDef(menu.children)) continue;
  218. treeArray.push(treeNode);
  219. // 递归子集
  220. treeNode.children = recursiveFunTree(menu.children);
  221. }
  222. return treeArray;
  223. };
  224. console.log("getQuickEnterFuncTree menuList :>> ", menuList);
  225. let functionTree = recursiveFunTree(menuList);
  226. return functionTree;
  227. }
  228. /**
  229. * @description 使用递归过滤出需要渲染在首页常用功能树路由 (需剔除 isHide == true 的菜单)
  230. * @param {Array} menuList 菜单列表
  231. * @returns {Array}
  232. * */
  233. export function getQuickEnterFuncTreeRouter(menuList: Menu.MenuOptions[]): Map<string, { [key: string]: any }> {
  234. console.log("getQuickEnterFuncTreeRouter menuList :>> ", menuList);
  235. class TreeNode {
  236. key: string;
  237. name: string;
  238. icon?: string;
  239. path: string;
  240. funid: number | string;
  241. constructor(key: string, label: string, path: string, icon?: string, funid?: number) {
  242. this.key = key;
  243. this.name = label;
  244. this.path = path;
  245. this.icon = icon || "";
  246. this.funid = funid ?? 0;
  247. }
  248. }
  249. const recursiveFunTree = (children: Menu.MenuOptions[]): Map<string, TreeNode> => {
  250. let routerMap: Map<string, TreeNode> = new Map();
  251. for (const menu of children) {
  252. // 跳过已隐藏的菜单 | 跳过不存在component的
  253. if (!(menu.meta?.isHide || isNullOrUnDef(menu.component))) {
  254. //
  255. let treeNode = new TreeNode(menu.name, menu.meta?.title, menu.path, menu.meta?.icon, menu.meta?.funid);
  256. routerMap.set(menu.name, treeNode);
  257. }
  258. if (isNullOrUnDef(menu.children)) continue;
  259. // 递归子集
  260. routerMap = new Map([...routerMap, ...recursiveFunTree(menu.children)]);
  261. }
  262. return routerMap;
  263. };
  264. let routerMap = recursiveFunTree(menuList);
  265. return routerMap;
  266. }
  267. /**
  268. * @description 使用递归处理路由菜单 path,生成一维数组 (第一版本地路由鉴权会用到,该函数暂未使用)
  269. * @param {Array} menuList 所有菜单列表
  270. * @param {Array} menuPathArr 菜单地址的一维数组 ['**','**']
  271. * @returns {Array}
  272. */
  273. export function getMenuListPath(menuList: Menu.MenuOptions[], menuPathArr: string[] = []): string[] {
  274. for (const item of menuList) {
  275. if (typeof item === "object" && item.path) menuPathArr.push(item.path);
  276. if (item.children?.length) getMenuListPath(item.children, menuPathArr);
  277. }
  278. return menuPathArr;
  279. }
  280. /**
  281. * @description 递归查询当前 path 所对应的菜单对象 (该函数暂未使用)
  282. * @param {Array} menuList 菜单列表
  283. * @param {String} path 当前访问地址
  284. * @returns {Object | null}
  285. */
  286. export function findMenuByPath(menuList: Menu.MenuOptions[], path: string): Menu.MenuOptions | null {
  287. for (const item of menuList) {
  288. if (item.path === path) return item;
  289. if (item.children) {
  290. const res = findMenuByPath(item.children, path);
  291. if (res) return res;
  292. }
  293. }
  294. return null;
  295. }
  296. /**
  297. * @description 使用递归过滤需要缓存的菜单 name (该函数暂未使用)
  298. * @param {Array} menuList 所有菜单列表
  299. * @param {Array} keepAliveNameArr 缓存的菜单 name ['**','**']
  300. * @returns {Array}
  301. * */
  302. export function getKeepAliveRouterName(menuList: Menu.MenuOptions[], keepAliveNameArr: string[] = []) {
  303. menuList.forEach(item => {
  304. item.meta.isKeepAlive && item.name && keepAliveNameArr.push(item.name);
  305. item.children?.length && getKeepAliveRouterName(item.children, keepAliveNameArr);
  306. });
  307. return keepAliveNameArr;
  308. }
  309. /**
  310. * @description 格式化表格单元格默认值 (el-table-column)
  311. * @param {Number} row 行
  312. * @param {Number} col 列
  313. * @param {*} callValue 当前单元格值
  314. * @returns {String}
  315. * */
  316. export function formatTableColumn(row: number, col: number, callValue: any) {
  317. // 如果当前值为数组,使用 / 拼接(根据需求自定义)
  318. if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "";
  319. return callValue ?? "";
  320. }
  321. /**
  322. * @description 处理值无数据情况
  323. * @param {*} callValue 需要处理的值
  324. * @returns {String}
  325. * */
  326. export function formatValue(callValue: any) {
  327. // 如果当前值为数组,使用 / 拼接(根据需求自定义)
  328. if (isArray(callValue)) return callValue.length ? callValue.join(" / ") : "";
  329. return callValue ?? "";
  330. }
  331. /**
  332. * @description 处理 prop 为多级嵌套的情况,返回的数据 (列如: prop: user.name)
  333. * @param {Object} row 当前行数据
  334. * @param {String} prop 当前 prop
  335. * @returns {*}
  336. * */
  337. export function handleRowAccordingToProp(row: { [key: string]: any }, prop: string, ...args: any) {
  338. if (args[0]) {
  339. return row[prop] && formatFn[args[0]] ? formatFn[args[0]]({ val: row[prop], format: args[0] }) : "";
  340. }
  341. if (!prop.includes(".")) return row[prop] ?? "";
  342. prop.split(".").forEach(item => (row = row[item] ?? ""));
  343. return row;
  344. }
  345. /**
  346. * @description 处理 prop,当 prop 为多级嵌套时 ==> 返回最后一级 prop
  347. * @param {String} prop 当前 prop
  348. * @returns {String}
  349. * */
  350. export function handleProp(prop: string) {
  351. const propArr = prop.split(".");
  352. if (propArr.length == 1) return prop;
  353. return propArr[propArr.length - 1];
  354. }
  355. /**
  356. * @description 根据枚举列表查询当需要的数据(如果指定了 label 和 value 的 key值,会自动识别格式化)
  357. * @param {String} callValue 当前单元格值
  358. * @param {Array} enumData 字典列表
  359. * @param {Array} fieldNames label && value && children 的 key 值
  360. * @param {String} type 过滤类型(目前只有 tag)
  361. * @returns {String}
  362. * */
  363. export function filterEnum(callValue: any, enumData?: any, fieldNames?: FieldNamesProps, type?: "tag") {
  364. const value = fieldNames?.value ?? "value";
  365. const label = fieldNames?.label ?? "label";
  366. const children = fieldNames?.children ?? "children";
  367. let filterData: { [key: string]: any } = {};
  368. // 判断 enumData 是否为数组
  369. if (Array.isArray(enumData)) filterData = findItemNested(enumData, callValue, value, children);
  370. // 判断是否输出的结果为 tag 类型
  371. if (type == "tag") {
  372. return filterData?.tagType ? filterData.tagType : "";
  373. } else {
  374. return filterData ? filterData[label] : "";
  375. }
  376. }
  377. /**
  378. * @description 递归查找 callValue 对应的 enum 值
  379. * */
  380. export function findItemNested(enumData: any, callValue: any, value: string, children: string) {
  381. return enumData.reduce((accumulator: any, current: any) => {
  382. if (accumulator) return accumulator;
  383. if (current[value] === callValue) return current;
  384. if (current[children]) return findItemNested(current[children], callValue, value, children);
  385. }, null);
  386. }
  387. // 日期格式化
  388. function formatDate({ val, format }: any) {
  389. return XEUtils.toDateString(val, format || "yyyy-MM-dd HH:mm:ss");
  390. }
  391. // 四舍五入金额,每隔3位逗号分隔,默认0位小数
  392. export function formatIntNumber({ val }: any, digits = 0) {
  393. if (isNaN(Number(val))) return val;
  394. return XEUtils.commafy(XEUtils.toNumber(val), { digits });
  395. }
  396. // 四舍五入金额,每隔3位逗号分隔,默认2位数
  397. export function formatAmount3({ val }: any, digits = 2) {
  398. if (isNaN(Number(val))) return val;
  399. return XEUtils.commafy(XEUtils.toNumber(val), { digits });
  400. }
  401. // 向下舍入,默认两位数
  402. export function formatCutNumber({ val }: any, digits = 2) {
  403. if (isNaN(Number(val))) return val;
  404. if (Number(val) == 0) return 0;
  405. return XEUtils.toFixed(XEUtils.floor(val, digits), digits);
  406. }
  407. // 向下舍入,默认两位数
  408. function formatCutNumber3({ val }: any, digits = 3) {
  409. if (isNaN(Number(val))) return val;
  410. return XEUtils.toFixed(XEUtils.floor(val, digits), digits);
  411. }
  412. // 四舍五入,默认两位数
  413. export function formatFixedNumber({ val }: any, digits = 2) {
  414. if (isNaN(Number(val))) return val;
  415. return XEUtils.toFixed(XEUtils.round(val, digits), digits);
  416. }
  417. // 百分比:四舍五入金额,每隔3位逗号分隔,默认2位
  418. function formatPercent({ val }: any, digits = 2) {
  419. if (isNaN(Number(val))) return val;
  420. return XEUtils.commafy(XEUtils.toNumber(val) * 100, { digits }) + "%";
  421. }
  422. /**
  423. * @description 格式化调用函数对照
  424. */
  425. const formatFn: any = {
  426. "yyyy-MM-dd": formatDate,
  427. "yyyy-MM-dd HH:mm:ss": formatDate,
  428. "yyyy-MM-dd HH:mm": formatDate,
  429. "MM/dd/yyyy": formatDate,
  430. "MM/dd": formatDate,
  431. "dd/MM/yyyy": formatDate,
  432. "yyyy/MM/dd": formatDate,
  433. intNumber: formatIntNumber,
  434. cutNumber: formatCutNumber,
  435. amountNumber: formatAmount3,
  436. fixedNumber: formatFixedNumber,
  437. cutNumber3: formatCutNumber3,
  438. percent: formatPercent
  439. };
  440. /**
  441. * 一维,精简对象储存属性;支持数组型默认数据(关键字:field)
  442. * 逻辑:精简出与默认数据不同的属性,保留layoutAttr包含的字段
  443. * @param {Object} column 列数据
  444. * @param {String[]} layoutAttr 需要保留的数据名称
  445. * @param {Object | Array} layoutDefine 数据默认值 {...} Or [{field: xxx, ...}, ...]
  446. * @returns {Array} 返回精简后的对象
  447. */
  448. export function streamlineFunc(column: any, layoutAttr: string[], layoutDefine: any) {
  449. let streamlinedColumns = [];
  450. if (Array.isArray(layoutDefine)) {
  451. for (let item of column) {
  452. const matchingDefinition = layoutDefine.find(itm => itm.field === item.field);
  453. const relevantAttrs = layoutAttr.filter(attr => {
  454. const itemValue = get(item, attr);
  455. const defineValue = get(matchingDefinition, attr);
  456. // 排除某些属性,并检查值是否不同
  457. return !["field", "table", "datatype"].includes(attr) && defineValue !== itemValue;
  458. });
  459. // 将 "field" 包含在过滤后的属性中
  460. const attrsToPick = [...relevantAttrs, "field"];
  461. streamlinedColumns.push(pick(item, attrsToPick));
  462. }
  463. } else {
  464. for (let item of column) {
  465. const relevantAttrs = layoutAttr.filter(attr => {
  466. // 检查值是否与布局定义不同
  467. return item[attr] !== layoutDefine[attr];
  468. });
  469. streamlinedColumns.push(pick(item, relevantAttrs));
  470. }
  471. }
  472. return streamlinedColumns;
  473. }
  474. /**
  475. * 一维,精简对象储存属性
  476. * @param {Object} column 列数据
  477. * @param {String[]} layoutAttr 需要保留的数据名称
  478. * @param {Object} layoutDefine 数据默认值
  479. * @param {String} attr 列数据的二级属性
  480. * @returns {Object} 返回精简后的对象
  481. */
  482. export function streamlineAttrFunc(column: any, layoutAttr: string[], layoutDefine: any, attr: string) {
  483. let _map = new Map();
  484. for (let item of column) {
  485. let saveProp = cloneDeep(layoutAttr);
  486. if (item.basicinfo) {
  487. for (let key in layoutDefine) {
  488. if (item[attr].hasOwnProperty(key) && layoutDefine[key] === item[attr][key]) {
  489. saveProp.splice(saveProp.indexOf(key), 1);
  490. }
  491. }
  492. _map.set(item.field, pick(item[attr], saveProp));
  493. }
  494. }
  495. return _map;
  496. }
  497. /**
  498. * 提取目标数据差异属性
  499. * @param {Object} oriLayout 原始对象,带默认值
  500. * @param {Object} targetLayout 目标对象,需要提取差异的数据
  501. * @param {String[]} attrs 需要保留字符串名称,规则:仅需提供最底层属性名称
  502. * @param {String} arrayAttr 数组数据,关键字段,用于排序
  503. * @returns {Object}
  504. */
  505. export function getDifference(oriLayout: any, targetLayout: any, attrs: string[] = [], arrayAttr = "id") {
  506. const diff: any = {};
  507. // 检查oriLayout中的属性
  508. for (const key in oriLayout) {
  509. if (oriLayout.hasOwnProperty(key)) {
  510. // 如果targetLayout中没有这个属性,则将它添加到差异中
  511. if (!targetLayout.hasOwnProperty(key)) {
  512. diff[key] = oriLayout[key];
  513. } else {
  514. // 如果targetLayout中也有这个属性,则比较它们的值
  515. if (Array.isArray(oriLayout[key])) {
  516. // 比较数组
  517. // 调整顺序,根据目标对象,调整原始对象数组顺序
  518. let _oriLayout = oriLayout[key];
  519. if (arrayAttr) {
  520. _oriLayout = oriLayout[key].slice().sort((a: any, b: any) => {
  521. let indexA = targetLayout[key].findIndex((item: any) => item[arrayAttr] === a[arrayAttr]);
  522. let indexB = targetLayout[key].findIndex((item: any) => item[arrayAttr] === b[arrayAttr]);
  523. return indexA - indexB;
  524. });
  525. }
  526. let arrAttr = [];
  527. for (const idx in _oriLayout) {
  528. console.log("oriLayout[key][idx] :>> ", _oriLayout[idx]);
  529. if (targetLayout[key][idx]) {
  530. const nestedDiff = getDifference(_oriLayout[idx], targetLayout[key][idx], attrs, arrayAttr);
  531. console.log(nestedDiff);
  532. if (Object.keys(nestedDiff).length > 0) {
  533. arrAttr.push(nestedDiff);
  534. }
  535. }
  536. }
  537. arrAttr.length && (diff[key] = arrAttr);
  538. } else if (typeof oriLayout[key] === "object" && typeof targetLayout[key] === "object") {
  539. // 递归比较对象
  540. console.log("key :>> ", key, oriLayout[key], targetLayout[key]);
  541. const nestedDiff = getDifference(oriLayout[key], targetLayout[key], attrs, arrayAttr);
  542. console.log("nestedDiff :>> ", key, nestedDiff);
  543. if (Object.keys(nestedDiff).length > 0) {
  544. console.log("nestedDiff :>> ", nestedDiff);
  545. diff[key] = nestedDiff;
  546. }
  547. } else if ((oriLayout[key] !== targetLayout[key] || key == arrayAttr) && attrs.includes(key)) {
  548. console.log("key :>> ", key);
  549. diff[key] = targetLayout[key];
  550. }
  551. }
  552. }
  553. }
  554. // 补充:检查targetLayout中的属性
  555. for (const key in targetLayout) {
  556. if (targetLayout.hasOwnProperty(key)) {
  557. // 如果oriLayout中没有这个属性,则将它添加到差异中
  558. if (
  559. !oriLayout.hasOwnProperty(key) ||
  560. (oriLayout.hasOwnProperty(key) && isObject(oriLayout[key]) && Object.keys(oriLayout[key]).length == 0)
  561. ) {
  562. diff[key] = targetLayout[key];
  563. }
  564. }
  565. }
  566. return diff;
  567. }
  568. /**
  569. * 读取数据到原始对象
  570. * @param {Object} oriLayout 原始对象,带默认值
  571. * @param {Object} targetLayout 差异的数据
  572. * @param {String} arrayAttr 数组数据,关键字段,用于排序
  573. * @returns {Object}
  574. */
  575. export function setDifference(oriLayout: any, loadLayout: any, arrayAttr: string = "id") {
  576. let _oriLayout = cloneDeep(oriLayout);
  577. for (const key in loadLayout) {
  578. if (loadLayout.hasOwnProperty(key)) {
  579. if (Array.isArray(loadLayout[key])) {
  580. // console.log("setDifference _oriLayout :>> ", _oriLayout);
  581. let _sortedObj1 = _oriLayout[key].slice().sort((a: any, b: any) => {
  582. let indexA = loadLayout[key].findIndex((item: any) => item[arrayAttr] === a[arrayAttr]);
  583. let indexB = loadLayout[key].findIndex((item: any) => item[arrayAttr] === b[arrayAttr]);
  584. if (indexA == -1 || indexB == -1) {
  585. return 0;
  586. } else {
  587. return indexA - indexB;
  588. }
  589. });
  590. // console.log("setDifference _sortedObj1 :>> ", _sortedObj1);
  591. // console.log("setDifference loadLayout[key] :>> ", loadLayout[key]);
  592. let arr = [];
  593. for (const idx in _sortedObj1) {
  594. // console.log("idx :>> ", idx);
  595. // console.log("loadLayout[key][idx] :>> ", loadLayout[key][idx]);
  596. // console.log("_sortedObj1[idx] :>> ", _sortedObj1[idx]);
  597. // if (loadLayout[key][idx] && _sortedObj1[idx] && loadLayout[key][idx][arrayAttr] == _sortedObj1[idx][arrayAttr]) {
  598. // arr.push(setDifference(_sortedObj1[idx], loadLayout[key][idx], arrayAttr));
  599. // }
  600. let itemIdx = loadLayout[key].findIndex((item: any) => item[arrayAttr] === _sortedObj1[idx][arrayAttr]);
  601. // console.log(itemIdx);
  602. let _loadLayout = itemIdx > -1 ? loadLayout[key][itemIdx] : {};
  603. arr.push(setDifference(_sortedObj1[idx], _loadLayout, arrayAttr));
  604. }
  605. // console.log("arr :>> ", arr);
  606. arr.length && (_oriLayout[key] = arr);
  607. } else if (typeof loadLayout[key] === "object") {
  608. if (!_oriLayout.hasOwnProperty(key)) {
  609. _oriLayout[key] = {};
  610. }
  611. _oriLayout[key] = setDifference(_oriLayout[key], loadLayout[key], arrayAttr);
  612. } else {
  613. _oriLayout[key] = loadLayout[key];
  614. }
  615. }
  616. }
  617. return _oriLayout;
  618. }
  619. /**
  620. * 金额缩略显示
  621. * @param s 数值
  622. * @param n 小数保留位数
  623. * @returns {string}
  624. */
  625. export function numberFormat(s: number, n: number) {
  626. n = n !== undefined && n >= 0 && n <= 20 ? n : 2;
  627. let sum = Math.abs(Number(s));
  628. let sumStr = parseFloat((sum + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  629. let r = n ? "." + sumStr.split(".")[1] : "";
  630. let l = sumStr.split(".")[0].split("").reverse();
  631. let t = "";
  632. for (let i = 0; i < l.length; i++) {
  633. t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
  634. }
  635. if (s < 0) return "-" + t.split("").reverse().join("") + r;
  636. return t.split("").reverse().join("") + r;
  637. }
  638. export const noop = () => {};
  639. /**
  640. * 获取目标属性,转换字符串对象
  641. * @param obj 目标值
  642. * @param str 目标字符串属性
  643. */
  644. export function convertStrToObj(obj: any, str?: string): any {
  645. console.log("convertStrToObj obj :>> ", obj);
  646. console.log("convertStrToObj str :>> ", str);
  647. if (!obj || JSON.stringify(obj) == "{}" || !str) return undefined;
  648. const keys = str.split(".");
  649. for (let i = 0; i < keys.length; i++) {
  650. const key = keys[i];
  651. obj[key] = obj[key] || undefined;
  652. obj = obj[key];
  653. }
  654. return obj;
  655. }
  656. /**
  657. * 时间格式转义, detaTime to Diff
  658. * @param data {value:Object}
  659. * @returns {Object}
  660. */
  661. export const getDiffToDate = (data: any) => {
  662. const today = dayjs(dayjs().format("YYYY-MM-DD"));
  663. for (const key in data) {
  664. if (key.indexOf("date") > -1) {
  665. if (isNumber(data[key])) {
  666. // number => string
  667. data[key] = today.add(data[key], "day").format("YYYY-MM-DD HH:mm:ss");
  668. } else if (isArray(data[key])) {
  669. // [number, number] => [string, string]
  670. data[key] = data[key].map((item: any) => {
  671. if (isNumber(item)) {
  672. return today.add(item, "day").format("YYYY-MM-DD HH:mm:ss");
  673. } else {
  674. return item;
  675. }
  676. });
  677. }
  678. }
  679. }
  680. console.log("getDiffToDate data :>> ", data);
  681. return data;
  682. };
  683. /**
  684. * 时间格式转义, Diff to DetaTime
  685. * @param data {value:Object}
  686. * @returns
  687. */
  688. export const setDateToDiff = (data: any) => {
  689. const today = dayjs(dayjs().format("YYYY-MM-DD"));
  690. for (const key in data) {
  691. if (key.indexOf("date") > -1) {
  692. if (isString(data[key]) || isDate(data[key])) {
  693. // string => number
  694. let newDate = dayjs(dayjs(data[key]).format("YYYY-MM-DD"));
  695. data[key] = newDate.diff(today, "day");
  696. } else if (isArray(data[key])) {
  697. // [string, string] => [number, number]
  698. data[key] = data[key].map((item: any) => {
  699. let newDate = dayjs(dayjs(item).format("YYYY-MM-DD"));
  700. return newDate.diff(today, "day");
  701. });
  702. }
  703. }
  704. }
  705. console.log("_habit setDateToDiff data :>> ", data);
  706. return data;
  707. };
  708. /**
  709. * 捕捉报错提示
  710. * @param err 报错含有,关键字:会话、已与服务器失联、找不到网络路径
  711. * @returns {Boolean}
  712. */
  713. export const ifErrorToLogin = (err: any) => {
  714. return err.indexOf("会话") >= 0 || err.indexOf("已与服务器失联") >= 0 || err.indexOf("找不到网络路径") >= 0;
  715. };
  716. /**
  717. * 遍历树形结构的数据
  718. * @param tree 遍历的树形结构数据
  719. * @param callback 回调函数,用于处理遍历到的每个节点
  720. */
  721. export const traverseNode = (root: any, action: (node: any) => void) => {
  722. const queue = [root];
  723. while (queue.length > 0) {
  724. const node = queue.shift();
  725. action(node);
  726. if (node.children && node.children.length > 0) {
  727. for (const child of node.children) {
  728. queue.push(child);
  729. }
  730. }
  731. }
  732. };
  733. /*用正则表达式实现html转码*/
  734. export const htmlEncodeByRegExp = (str: string) => {
  735. let s = "";
  736. if (str.length == 0) return "";
  737. s = str.replace(/&/g, "&amp;");
  738. s = s.replace(/</g, "&lt;");
  739. s = s.replace(/>/g, "&gt;");
  740. s = s.replace(/ /g, "&nbsp;");
  741. s = s.replace(/\'/g, "&#39;");
  742. s = s.replace(/\"/g, "&quot;");
  743. return s;
  744. };
  745. /*用正则表达式实现html解码*/
  746. export const htmlDecodeByRegExp = (str: string) => {
  747. let s = "";
  748. if (str.length == 0) return "";
  749. s = str.replace(/&amp;/g, "&");
  750. s = s.replace(/&lt;/g, "<");
  751. s = s.replace(/&gt;/g, ">");
  752. s = s.replace(/&nbsp;/g, " ");
  753. s = s.replace(/&#39;/g, "'");
  754. s = s.replace(/&quot;/g, '"');
  755. return s;
  756. };
  757. /**
  758. * 小数点加、减、乘、除
  759. * @param {Number} arg1 数1
  760. * @param {Number} arg2 数2
  761. * @returns
  762. */
  763. export const floatAdd = (arg1: any, arg2: any) => {
  764. let r1, r2, m;
  765. try {
  766. r1 = arg1.toString().split(".")[1].length;
  767. } catch (e) {
  768. r1 = 0;
  769. }
  770. try {
  771. r2 = arg2.toString().split(".")[1].length;
  772. } catch (e) {
  773. r2 = 0;
  774. }
  775. m = Math.pow(10, Math.max(r1, r2));
  776. return (Math.round(arg1 * m) + Math.round(arg2 * m)) / m;
  777. };
  778. export const floatAddMore = (arr: any) => {
  779. let r1,
  780. r2,
  781. m,
  782. sum = 0;
  783. for (const item of arr) {
  784. if (item == undefined || item == null) continue;
  785. r1 = sum.toString().split(".")[1]?.length ?? 0;
  786. r2 = item.toString().split(".")[1]?.length ?? 0;
  787. m = Math.pow(10, Math.max(r1, r2));
  788. sum = (Math.round(sum * m) + Math.round(item * m)) / m;
  789. }
  790. return sum;
  791. };
  792. export const floatSub = (arg1: any, arg2: any) => {
  793. let r1, r2, m, n;
  794. try {
  795. r1 = arg1.toString().split(".")[1].length;
  796. } catch (e) {
  797. r1 = 0;
  798. }
  799. try {
  800. r2 = arg2.toString().split(".")[1].length;
  801. } catch (e) {
  802. r2 = 0;
  803. }
  804. m = Math.pow(10, Math.max(r1, r2));
  805. //动态控制精度长度
  806. n = r1 >= r2 ? r1 : r2;
  807. return ((Math.round(arg1 * m) - Math.round(arg2 * m)) / m).toFixed(n);
  808. };
  809. export const floatMul = (arg1: any, arg2: any) => {
  810. let m = 0,
  811. s1 = (arg1 ?? 0).toString(),
  812. s2 = (arg2 ?? 0).toString();
  813. try {
  814. m += s1.split(".")[1].length;
  815. } catch (e) {}
  816. try {
  817. m += s2.split(".")[1].length;
  818. } catch (e) {}
  819. return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m);
  820. };
  821. export const floatMulMore = (arr: any) => {
  822. let m = 0,
  823. sum = 1;
  824. for (const item of arr) {
  825. if (item) {
  826. let s1 = item.toString();
  827. try {
  828. m += s1.split(".")[1].length;
  829. } catch (e) {}
  830. sum = sum * Number(s1.replace(".", ""));
  831. }
  832. }
  833. return Number(sum) / Math.pow(10, m);
  834. };
  835. export const floatDiv = (arg1: any, arg2: any) => {
  836. let t1 = 0,
  837. t2 = 0,
  838. r1,
  839. r2;
  840. try {
  841. t1 = arg1.toString().split(".")[1].length;
  842. } catch (e) {}
  843. try {
  844. t2 = arg2.toString().split(".")[1].length;
  845. } catch (e) {}
  846. r1 = Number(arg1.toString().replace(".", ""));
  847. r2 = Number(arg2.toString().replace(".", ""));
  848. return (r1 / r2) * Math.pow(10, t2 - t1);
  849. };
  850. /**
  851. * @description 文件类型转化base64类型
  852. * @param type 文件类型
  853. * @returns base64类型
  854. */
  855. export const getBase64Type = (type: string) => {
  856. switch (type.toLowerCase()) {
  857. case "txt":
  858. return "data:text/plain;base64,";
  859. case "doc":
  860. return "data:application/msword;base64,";
  861. case "docx":
  862. return "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,";
  863. case "xls":
  864. return "data:application/vnd.ms-excel;base64,";
  865. case "xlsx":
  866. return "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,";
  867. case "pdf":
  868. return "data:application/pdf;base64,";
  869. case "pptx":
  870. return "data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,";
  871. case "ppt":
  872. return "data:application/vnd.ms-powerpoint;base64,";
  873. case "png":
  874. return "data:image/png;base64,";
  875. case "jpg":
  876. return "data:image/jpeg;base64,";
  877. case "gif":
  878. return "data:image/gif;base64,";
  879. case "svg":
  880. return "data:image/svg+xml;base64,";
  881. case "ico":
  882. return "data:image/x-icon;base64,";
  883. case "bmp":
  884. return "data:image/bmp;base64,";
  885. default:
  886. return "";
  887. }
  888. };
  889. /**
  890. * @description 自定义函数检查className中是否包含需要的类名
  891. */
  892. export const classNameIncludes = (element: any, target: string[]) => {
  893. if (!element) return false;
  894. let _className: string[] = [];
  895. let parent = element.parentElement;
  896. // 获取当前元素的类名
  897. if (typeof element.className === "string") {
  898. _className = element.className.split(/\s+/g);
  899. }
  900. // 如果父元素存在,则获取父元素的类名
  901. while (parent) {
  902. if (parent.classList) {
  903. // 获取当前父元素的所有类名并添加到数组中
  904. Array.from(parent.classList).forEach((className: any) => {
  905. if (!_className.includes(className)) {
  906. _className.push(className);
  907. }
  908. });
  909. }
  910. // 移动到下一个父元素
  911. parent = parent.parentElement;
  912. }
  913. return target.some(item => _className.indexOf(item) > -1);
  914. };
  915. /**
  916. * @description 倒计时
  917. * @param {number} value 剩余秒数
  918. * @returns {string} 倒计时 00:00:30,
  919. */
  920. export const countDownTime = (value: number) => {
  921. // 处理数字类型的秒数
  922. if (value <= 0) {
  923. return "";
  924. }
  925. const days = Math.floor(value / 86400);
  926. const hours = Math.floor((value % 86400) / 3600)
  927. .toString()
  928. .padStart(2, "0");
  929. const minutes = Math.floor((value % 3600) / 60)
  930. .toString()
  931. .padStart(2, "0");
  932. const seconds = (value % 60).toString().padStart(2, "0");
  933. let text = "";
  934. if (days > 365) {
  935. text = `${Math.floor(days / 365)}年`;
  936. } else if (days > 31) {
  937. text = `${Math.floor(days / 31)}月`;
  938. } else if (days > 0) {
  939. text = `${days}天`;
  940. } else {
  941. text = `${hours}:${minutes}:${seconds}`;
  942. }
  943. return text;
  944. };
  945. const parseTime = (time: any, cFormat?: string) => {
  946. let format = cFormat ?? `{y}-{m}-{d} {h}:{i}:{s}`;
  947. let date;
  948. if (typeof time === "object") {
  949. date = time;
  950. } else {
  951. if (typeof time === "string") {
  952. if (/^[0-9]+$/.test(time)) {
  953. time = parseInt(time);
  954. } else {
  955. time = time.replace(new RegExp(/-/gm), "/");
  956. }
  957. }
  958. if (typeof time === "number" && time.toString().length === 10) {
  959. time = time * 1000;
  960. }
  961. date = new Date(time);
  962. }
  963. const formatObj: any = {
  964. y: date.getFullYear(),
  965. m: date.getMonth() + 1,
  966. d: date.getDate(),
  967. h: date.getHours(),
  968. i: date.getMinutes(),
  969. s: date.getSeconds(),
  970. a: date.getDay()
  971. };
  972. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  973. const value = formatObj[key];
  974. // Note: getDay() returns 0 on Sunday
  975. if (key === "a") {
  976. return ["日", "一", "二", "三", "四", "五", "六"][value];
  977. }
  978. return value.toString().padStart(2, "0");
  979. });
  980. return time_str;
  981. };
  982. /**
  983. * 最近时间-时差
  984. * @param {number} time
  985. * @param {string} option
  986. * @returns {Number} (秒)
  987. */
  988. export const formatTime = function (time: string | number, option: string, ifshort: boolean, nowtime?: string) {
  989. const _time = new Date(time);
  990. const d = new Date(time);
  991. const now = nowtime ? new Date(nowtime) : new Date();
  992. const diff = (now.getTime() - d.getTime()) / 1000;
  993. if (ifshort) {
  994. if (diff < 0) {
  995. // flutter
  996. } else if (diff < 30) {
  997. return "刚刚";
  998. } else if (diff < 3600) {
  999. // less 1 hour
  1000. return Math.ceil(diff / 60) + "分钟前";
  1001. } else if (diff < 3600 * 6) {
  1002. // 1~6小时
  1003. return Math.ceil(diff / 3600) + "小时前";
  1004. }
  1005. let hourMins = parseTime(_time, "{h}:{i}");
  1006. let isSameDay = now.setHours(0, 0, 0, 0) - d.setHours(0, 0, 0, 0);
  1007. switch (isSameDay) {
  1008. case 0:
  1009. return `今天 ${hourMins}`;
  1010. case 86400000:
  1011. return `昨天 ${hourMins}`;
  1012. // case 172800000:
  1013. // return `前天 ${hourMins}`
  1014. }
  1015. if (now.getFullYear() == d.getFullYear()) {
  1016. return parseTime(_time, "{m}-{d} {h}:{i}");
  1017. } else {
  1018. return parseTime(_time, "{y}-{m}-{d} {h}:{i}");
  1019. }
  1020. }
  1021. if (option) {
  1022. return parseTime(_time, option);
  1023. }
  1024. };
  1025. const funcGetFormulaValue = (item, tgList, fieldList, valueList) => {
  1026. let _paras = item?.formula
  1027. .replace(/【/g, "[")
  1028. .replace(/】/g, "]")
  1029. .match(/\[([^\]]*)\]/g);
  1030. let resultFormula = item?.formula.replace(/【/g, "[").replace(/】/g, "]");
  1031. _paras.forEach(part => {
  1032. // console.log(part);
  1033. let fieldName = part.slice(1, -1); // 去掉方括号
  1034. // console.log(fieldName);
  1035. let sumVal = tgList.find(f => {
  1036. if (f.field === fieldName) {
  1037. return f;
  1038. } else if (f.label === fieldName) {
  1039. fieldName = f.field;
  1040. return f;
  1041. }
  1042. });
  1043. !sumVal &&
  1044. (sumVal = fieldList.find(f => {
  1045. if (f.field === fieldName) {
  1046. return f;
  1047. } else if (f.label === fieldName) {
  1048. fieldName = f.field;
  1049. return f;
  1050. }
  1051. }));
  1052. if (sumVal) {
  1053. let res = valueList[fieldName];
  1054. let _formula;
  1055. if (sumVal?.formula) {
  1056. _formula = sumVal.formula.replace(part, `${valueList[fieldName]}`);
  1057. }
  1058. // console.log(fieldName, _formula, sumVal);
  1059. if (_formula && _formula.indexOf("[") > -1) {
  1060. let _res = formulaPartsFormula([{ formula: _formula }], fieldList, valueList, tgList);
  1061. res = `(${_res[0]})`;
  1062. }
  1063. if (typeof res === "undefined") {
  1064. ElMessage.warning("接口未提供数据,请检查:" + fieldName);
  1065. console.error("接口未提供数据,请检查:" + fieldName);
  1066. return;
  1067. }
  1068. resultFormula = resultFormula.replace(part, res);
  1069. } else {
  1070. valueList[fieldName] && (resultFormula = resultFormula.replace(part, `${valueList[fieldName]}`));
  1071. }
  1072. });
  1073. return resultFormula;
  1074. };
  1075. export const formulaPartsFormula = (formulaList, fieldList, valueList, tgList = formulaList) => {
  1076. let result = [];
  1077. formulaList.map((item, index) => {
  1078. if (item?.formula) {
  1079. let res = funcGetFormulaValue(item, tgList, fieldList, valueList);
  1080. result.push(res);
  1081. }
  1082. });
  1083. return result;
  1084. };
  1085. /**
  1086. * @description 公式计算
  1087. * @param formulaList 公式列表 [{field: 'a', formula: '[b] + [c]'}]
  1088. * @param fieldList 字段列表 [{field: 'a', label: '字段A'}, {field: 'a', formula: '[b] + [c]'}]
  1089. * @param valueList 值列表 {a: 1, b: 2, c: 3}
  1090. * @returns {number[]} 计算结果 [1]
  1091. */
  1092. export const calculateFormula = async (formulaList, fieldList, valueList) => {
  1093. let resultFormula: any[] = formulaPartsFormula(formulaList, fieldList, valueList);
  1094. console.log("resultFormula: ", resultFormula);
  1095. try {
  1096. let res = await GetFormulaCompute({
  1097. formulas: resultFormula
  1098. });
  1099. if (res.values.length == 0) return [];
  1100. let result = formulaList.map((item, index) => {
  1101. let _res = res.values[index] ?? 0;
  1102. return {
  1103. ...item,
  1104. value: _res
  1105. };
  1106. });
  1107. return result;
  1108. } catch (error) {
  1109. console.error("Formula evaluation error:", error);
  1110. return [];
  1111. }
  1112. };
  1113. /**
  1114. * @description LjVxeTable获取当前表格选中数据;默认第一条记录
  1115. * @param targetRef 表格ref
  1116. * @returns {$table, curRecords} 当前表格对象,当前选中数据
  1117. */
  1118. export const getCurrentRecords = (targetRef: any) => {
  1119. const $table = targetRef.element;
  1120. const _records = $table.getCheckboxRecords() ?? [];
  1121. const _cRecords = $table.getCurrentRecord() ?? null;
  1122. let curRecords = [];
  1123. if ($table) {
  1124. if (_records.length) {
  1125. // 获取勾选列表
  1126. curRecords = _records;
  1127. } else if (_cRecords) {
  1128. // 获取当前选中数据
  1129. curRecords = [_cRecords];
  1130. } else {
  1131. // 默认获取第一条记录
  1132. let fullData = $table.getTableData().fullData;
  1133. if (fullData.length) {
  1134. curRecords = [fullData[0]];
  1135. $table.setCurrentRow(fullData[0]);
  1136. }
  1137. }
  1138. }
  1139. return { $table, curRecords };
  1140. };
  1141. export const transformTreeData = (data: any) => {
  1142. return data?.map(node => ({
  1143. ...node.data,
  1144. children: node.children ? transformTreeData(node.children) : []
  1145. }));
  1146. };
  1147. /**
  1148. * @description 过滤掉末尾的0
  1149. * @param data
  1150. * @returns
  1151. */
  1152. export const isFilterPrice = (data, digits?: number) => {
  1153. let _digits = digits ?? 2;
  1154. let val = formatAmount3({ val: data }, _digits);
  1155. // 过滤掉末尾的0
  1156. let arr = val.split("");
  1157. while (arr[arr.length - 1] === "0") {
  1158. arr.pop();
  1159. }
  1160. return arr.join("");
  1161. };
  1162. /**
  1163. * @description 计算vxetable的合并单元格
  1164. * @param $table 表对象
  1165. * @param fields 计算合并的字段明
  1166. * @returns 需要合并的单元格数组
  1167. */
  1168. export const autoMergeCells = ($table: any, fields: string[]) => {
  1169. let result: any = [];
  1170. let columns = $table.getColumns();
  1171. let { visibleData: data } = $table.getTableData();
  1172. // console.log("mergeCells data :>> ", columns, data);
  1173. data.map((item: any, rowIndex: number) => {
  1174. for (const key in item) {
  1175. if (fields.includes(key)) {
  1176. let rowspan = 1;
  1177. let currentVal = "";
  1178. let lastVal = "";
  1179. let colIndex = 0;
  1180. colIndex = columns.findIndex((item: any) => item.field == key);
  1181. currentVal = item[key];
  1182. if (rowIndex - 1 >= 0) {
  1183. lastVal = data[rowIndex - 1][key];
  1184. }
  1185. // console.log("lastVal currentVal:>> ", colIndex, key, lastVal, currentVal);
  1186. // if (rowIndex > 0) {
  1187. // if (!lastVal) {
  1188. if (lastVal != currentVal) {
  1189. // 计算合并行数
  1190. let _span = 0;
  1191. for (let i = rowIndex + 1; i < data.length; i++) {
  1192. if (data[i][key] && currentVal && data[i][key] == currentVal) {
  1193. _span++;
  1194. } else {
  1195. break;
  1196. }
  1197. }
  1198. rowspan += _span;
  1199. } else {
  1200. rowspan = 0;
  1201. }
  1202. // console.log("rowspan :>> ", key, lastVal, currentVal, rowspan);
  1203. // }
  1204. // }
  1205. if (rowspan > 0) {
  1206. result.push({
  1207. row: rowIndex,
  1208. col: colIndex,
  1209. rowspan: rowspan,
  1210. colspan: 1
  1211. });
  1212. }
  1213. }
  1214. }
  1215. });
  1216. return result;
  1217. };
  1218. export const text2Formula = (str: any) => {
  1219. let rt = [];
  1220. if (str.includes("以上") || str.includes("以下")) {
  1221. // 匹配 "上下拼接X及以上Y以下"
  1222. let rangeMatch = str.match(/(\d+)及以下/);
  1223. if (rangeMatch) {
  1224. const value = parseInt(rangeMatch[1], 10);
  1225. rt.push(`value <= ${value}`);
  1226. } else {
  1227. rangeMatch = str.match(/(\d+)以下/);
  1228. if (rangeMatch) {
  1229. const value = parseInt(rangeMatch[1], 10);
  1230. rt.push(`value < ${value}`);
  1231. }
  1232. }
  1233. rangeMatch = str.match(/(\d+)及以上/);
  1234. if (rangeMatch) {
  1235. const value = parseInt(rangeMatch[1], 10);
  1236. rt.push(`value >= ${value}`);
  1237. } else {
  1238. rangeMatch = str.match(/(\d+)以上/);
  1239. if (rangeMatch) {
  1240. const value = parseInt(rangeMatch[1], 10);
  1241. rt.push(`value > ${value}`);
  1242. }
  1243. }
  1244. } else {
  1245. // 匹配 "上下拼接X"
  1246. const exactMatch = str.match(/(\d+)/);
  1247. if (exactMatch) {
  1248. const value = parseInt(exactMatch[1], 10);
  1249. rt.push(`value == ${value}`);
  1250. }
  1251. }
  1252. if (rt.length > 0) {
  1253. return rt.join(" && ");
  1254. }
  1255. throw new Error(`无法解析规则: ${str}`);
  1256. };
  1257. /**
  1258. * @description 事件: 一键复制
  1259. */
  1260. export const copyFunc = (data: any) => {
  1261. const input = document.createElement("textarea");
  1262. input.value = data;
  1263. document.body.appendChild(input);
  1264. input.select();
  1265. document.execCommand("Copy");
  1266. document.body.removeChild(input);
  1267. ElMessage({
  1268. type: "success",
  1269. message: "复制成功"
  1270. });
  1271. };