// import React from 'react' import { CriteriaConfig, CustomButtonConfig, DtmplConfig, DtmplData, DtmplFormProps, EnumItem, LtmplConfig, SelectConfig, ThemeConfig } from "../tmpl/interface"; import dayjs from "dayjs"; import TmplConfigAnalysis from "../tmpl/tmpl-config-analysis"; import { ProgramConfig } from "../index"; import { CriteriaFormProps } from "../form/criteria-form"; import ControlTypeSupportor from "../tmpl/control-type-supportor"; import HcserviceV3 from "../tmpl/hcservice-v3"; import { UserInfo } from "../tmpl/interface"; import { gzipSync, strToU8, gunzipSync, strFromU8 } from 'fflate'; import { uint8ArrayToHex, hexToUint8Array } from 'uint8array-extras'; let storageKeyPrefix = undefined; const CUSTOM_PAGE_MAP = {}; let MENU_MAP = {}; let MENU_ID_ICON_MAP = {}; const CustomButtonConfig_Map = {} const CUSTOM_VIEW_CONTROL_MAP = {}; const AppDtmplConfigFuncMap = {}; const AppCtmplConfigFuncMap = {}; const CUSTOM_EDIT_CONTROL_MAP = {}; let currentUser = undefined; const extendServerMap = {}; let antdUseToken = undefined; const CUSTOM_COMPONENT_MAP = {}; // 主题url vx替换正则 const regexTheme = /(?<=#\/)vx/g; let themeConfig: ThemeConfig = undefined; // 系统配置主题等 const pageConfigCommons = {}; // 用户页面自定义配置 let components2DMap = {}; // 2D图形组件 let Cross_Project_Code = {}; // 跨项目编码 // let siderCollapsed:boolean = true; export default { setAntdUseToken(antdUseToken_) { antdUseToken = antdUseToken_; }, getAntdUseToken() { return antdUseToken; }, //静态补充 setAppDtmplConfigFunc( key: string, func: (dtmplConfig: DtmplConfig, dtmplData: DtmplData) => DtmplConfig ) { AppDtmplConfigFuncMap[key] = func; }, setMenuIconMap(menuIconMap) { MENU_ID_ICON_MAP = menuIconMap; }, mapMenuIcon(menuId) { return MENU_ID_ICON_MAP[menuId]; }, setMenuMap(menuMap) { MENU_MAP = menuMap; }, mapMenu(menuId) { if (menuId == 'home') { return "首页" } return MENU_MAP[menuId]; }, getAppDtmplConfig( dtmplConfig: DtmplConfig, dtmplData: DtmplData, props: DtmplFormProps ) { if (dtmplConfig) { if (AppDtmplConfigFuncMap[dtmplConfig.id]) { return AppDtmplConfigFuncMap[dtmplConfig.id]( dtmplConfig, dtmplData, props ); } else { //用内置的 return TmplConfigAnalysis.buildInDtmplConfig( dtmplConfig, dtmplData, props ); } } return dtmplConfig; }, setCustomButtonConfig( key: string, config: CustomButtonConfig ) { CustomButtonConfig_Map[key] = config; }, getCustomButtonConfig( key: string ) { return CustomButtonConfig_Map[key]; }, setAppCtmplConfigFunc( key: string, func: (ltmplConfig: SelectConfig, data: Object) => SelectConfig ) { AppCtmplConfigFuncMap[key] = func; }, getAppCtmplConfig( ltmplConfig: SelectConfig, criteriaData: Object, props: CriteriaFormProps ) { if (ltmplConfig) { if (AppCtmplConfigFuncMap[ltmplConfig.id]) { return AppCtmplConfigFuncMap[ltmplConfig.id]( ltmplConfig, criteriaData, props ); } else { //用内置的 return TmplConfigAnalysis.buildInCtmplConfig( ltmplConfig, criteriaData, props ); } } return ltmplConfig; }, isDynamicDtmplConfig(dtmplConfig: DtmplConfig) { if (dtmplConfig && AppDtmplConfigFuncMap[dtmplConfig.id]) { return true; } return false; }, setCustomPage(key_: string, name: object) { let key = key_; if (!key) { return; } if (!key.startsWith("/")) { key = "/" + key; } CUSTOM_PAGE_MAP[key] = name; }, setCustomControl(key_: string, view: object, edit: object) { let key = key_; if (!key.startsWith("/")) { key = "/" + key; } CUSTOM_VIEW_CONTROL_MAP[key] = view; CUSTOM_EDIT_CONTROL_MAP[key] = edit; }, getCustomViewControl(key: string) { if (!key) { return null; } if (!key.startsWith("/")) { return CUSTOM_VIEW_CONTROL_MAP["/" + key]; } else { return CUSTOM_VIEW_CONTROL_MAP[key]; } }, getCustomEditControl(key: string) { if (!key) { return null; } if (!key.startsWith("/")) { return CUSTOM_EDIT_CONTROL_MAP["/" + key]; } else { return CUSTOM_EDIT_CONTROL_MAP[key]; } }, getCustomPage(key: string) { if (!key) { return null; } if (!key.startsWith("/")) { return CUSTOM_PAGE_MAP["/" + key]; } else { return CUSTOM_PAGE_MAP[key]; } }, setProgramCode(programCode_: string, key?: string) { if (programCode_) { if (key) { window.localStorage.setItem(key + "programCode", programCode_); } else { window.localStorage.setItem("programCode", programCode_); window.sessionStorage.setItem("programCode", programCode_); } } }, setSessionProgramCode(programCode_: string) { if (programCode_) { window.sessionStorage.setItem("programCode", programCode_); } }, programCode(key?: string) { let programCode = null; if (key) { // 存在key时优先从本地缓存获取是否是跨项目的菜单 programCode = this.getCrossProjectCode(key) || window.localStorage.getItem(key + "programCode"); if (!programCode && key === "localDevopsServer") { // 2D图图片上传模型,配置为空则使用默认值 programCode = "282877560559017986"; } } else { programCode = window.sessionStorage.getItem("programCode"); } if (!programCode) { programCode = window.localStorage.getItem("programCode"); this.setSessionProgramCode(programCode); } return programCode; }, setApplicationCode(applicationCode_: string, key?: string) { if (applicationCode_) { if (key) { window.localStorage.setItem(key + "applicationCode", applicationCode_); } else { window.localStorage.setItem("applicationCode", applicationCode_); window.sessionStorage.setItem("applicationCode", applicationCode_); } } }, setSessionApplicationCode(applicationCode_: string) { if (applicationCode_) { window.sessionStorage.setItem("applicationCode", applicationCode_); } }, applicationCode(key?: string) { let applicationCode = null; if (key) { applicationCode = window.localStorage.getItem(key + "applicationCode"); } else { applicationCode = window.sessionStorage.getItem("applicationCode"); } if (!applicationCode) { applicationCode = window.localStorage.getItem("applicationCode"); this.setSessionProgramCode(applicationCode); } return applicationCode; }, setHydrocarbonServer(url: string, key?: string) { if (key) { window.localStorage.setItem(key + "hydrocarbonServer", url); } else if (this.programCode()) { window.localStorage.setItem( this.programCode() + "hydrocarbonServer", url ); } else { window.localStorage.setItem("hydrocarbonServer", url); } }, setProgramName_Logo(logo1: string) { if (this.programCode()) { window.localStorage.setItem( this.programCode() + "programName_Logo", logo1 ); } else { window.localStorage.setItem("programName_Logo", logo1); } }, api(key?: string) { let appi = null; if (key && !key.startsWith("cp_")) { // 跨项目菜单的api走原来配置 appi = window.localStorage.getItem(key + "hydrocarbonServer"); } else { appi = window.localStorage.getItem( this.programCode() + "hydrocarbonServer" ); } if (!appi) { appi = window.localStorage.getItem("hydrocarbonServer"); } if (!appi) { let url = new URL(window.location.href); let pathname = null; if (url.pathname.indexOf("/kuangkie") > 0) { pathname = url.pathname.split("/kuangkie")[0]; } appi = this.joinPath(url.origin, pathname); } else if (appi == "/") { //以当前为主 let url = new URL(window.location.href); let pathname = url.pathname.split("/kuangkie")[0]; appi = this.joinPath(url.origin, pathname); } else if (appi.startsWith("/-")) { let url = new URL(window.location.href); let afterOrigin = url.href.replace(`${url.origin}/`, '').split("/"); let num = appi.match(/-/g)?.length || 0; let pathname = afterOrigin.slice(0, num).join("/"); appi = this.joinPath(url.origin, pathname); } else if (!appi.startsWith("http")) { appi = this.joinPath(new URL(window.location.href).origin, appi); } return appi; }, hydrocarbonToken(programCode_?: string, applicationCode_?: string) { let programCode = programCode_ ? programCode_ : this.programCode(); let applicationCode = applicationCode_ || this.applicationCode() || ""; let hydrocarbonToken = window.sessionStorage.getItem( programCode + applicationCode + "hydrocarbonToken" ); if (!hydrocarbonToken) { hydrocarbonToken = window.sessionStorage.getItem("hydrocarbonToken"); } if (!hydrocarbonToken) { hydrocarbonToken = window.localStorage.getItem( programCode + applicationCode + "hydrocarbonToken" ); if (!hydrocarbonToken) { hydrocarbonToken = window.localStorage.getItem("hydrocarbonToken"); } if (hydrocarbonToken) { this.setSessionHydrocarbonToken(hydrocarbonToken, programCode, applicationCode); } } return hydrocarbonToken; }, setServerHydrocarbonToken(serverkey: string, token: string) { if (serverkey && token) { window.sessionStorage.setItem(serverkey + "hydrocarbonToken", token); } this.setHydrocarbonToken(token, serverkey); }, serverHydrocarbonToken(serverKey: string) { let hydrocarbonToken = window.sessionStorage.getItem(serverKey + "hydrocarbonToken"); if (!hydrocarbonToken) { hydrocarbonToken = window.localStorage.getItem(serverKey + "hydrocarbonToken"); } if (!serverKey || !hydrocarbonToken) { // serverKey不存在 hydrocarbonToken = this.hydrocarbonToken(); } return hydrocarbonToken; }, putExtendServers(extendServers) { for (let es of extendServers) { extendServerMap[es.key] = es; if (es.key && es["hydrocarbonServer"]) { ProgramConfig.setProgramCode(es["programCode"], es.key); ProgramConfig.setHydrocarbonServer(es["hydrocarbonServer"], es.key); } } }, getExtendServers(serverKey) { return extendServerMap[serverKey]; }, setHydrocarbonToken(token: string, serverkey?: string) { let programCode = this.programCode(serverkey); let applicationCode = this.applicationCode(serverkey); this.setLocalHydrocarbonToken(token, programCode, applicationCode); this.setSessionHydrocarbonToken(token, programCode, applicationCode); }, setLocalHydrocarbonToken(token: string, programCode_?: string, applicationCode_?: string) { if (!programCode_) { // if(!window.localStorage.getItem('hydrocarbonToken')){ window.localStorage.setItem("hydrocarbonToken", token); //} } let programCode = programCode_ ? programCode_ : this.programCode(); let applicationCode = applicationCode_ || this.applicationCode() || ""; if (programCode) { window.localStorage.setItem(programCode + applicationCode + "hydrocarbonToken", token); //初次设为默认 if (!window.localStorage.getItem("hydrocarbonToken")) { window.localStorage.setItem("hydrocarbonToken", token); } } // else{ // window.localStorage.setItem('hydrocarbonToken',token); // } }, setSessionHydrocarbonToken(token: string, programCode_?: string, applicationCode_?: string) { if (!programCode_) { //初次设为默认 //if(!window.sessionStorage.getItem('hydrocarbonToken')){ window.sessionStorage.setItem("hydrocarbonToken", token); // } } let programCode = programCode_ ? programCode_ : this.programCode(); let applicationCode = applicationCode_ || this.applicationCode() || ""; if (programCode) { window.sessionStorage.setItem(programCode + applicationCode + "hydrocarbonToken", token); if (!window.sessionStorage.getItem("hydrocarbonToken")) { window.sessionStorage.setItem("hydrocarbonToken", token); } } // else{ // window.sessionStorage.setItem('hydrocarbonToken',token) ; // } }, setProgramName(programName_: string) { if (this.programCode()) { window.localStorage.setItem( this.programCode() + "programName", programName_ ); } else { window.localStorage.setItem("programName", programName_); } }, programName() { if (this.programCode()) { return window.localStorage.getItem(this.programCode() + "programName"); } else { return window.localStorage.getItem("programName"); } }, setProgramName_sub(programName_sub_: string) { if (this.programCode()) { window.localStorage.setItem( this.programCode() + "programName_sub", programName_sub_ ); } else { window.localStorage.setItem("programName_sub", programName_sub_); } }, programName_sub() { if (this.programCode()) { return window.localStorage.getItem( this.programCode() + "programName_sub" ); } else { return window.localStorage.getItem("programName_sub"); } }, setProgramName_NavLeft(programName_NavLeft_: string) { if (this.programCode()) { window.localStorage.setItem( this.programCode() + "programName_NavLeft", programName_NavLeft_ ); } else { window.localStorage.setItem("programName_NavLeft", programName_NavLeft_); } }, programName_NavLeft() { let result; if (this.programCode()) { result = window.localStorage.getItem( this.programCode() + "programName_NavLeft" ); } if (!result) { result = window.localStorage.getItem("programName_NavLeft"); } return result ? result : "管理平台"; }, programName_Logo() { let item = null; if (this.programCode()) { item = window.localStorage.getItem( this.programCode() + "programName_Logo" ); } if (!item) { item = window.localStorage.getItem("programName_Logo"); } return item && item == "undefined" ? null : item; }, setThemes(themes: string[]) { const themesStr = themes?.length ? themes.join(",") : ""; if (this.programCode()) { window.localStorage.setItem( this.programCode() + "themes", themesStr ); } else { window.localStorage.setItem("themes", themesStr); } }, themes() { let themes = ""; if (this.programCode()) { themes = window.localStorage.getItem( this.programCode() + "themes" ); } else { themes = window.localStorage.getItem("themes"); } return themes ? themes.split(",") : []; }, setDefaultTheme(theme: string) { let key = "defaultTheme"; if (this.programCode()) { key = this.programCode() + "defaultTheme"; } if (!theme) { window.localStorage.removeItem(key); return; } window.localStorage.setItem(key, theme); }, getDefaultTheme() { let theme = ""; if (this.programCode()) { theme = window.localStorage.getItem( this.programCode() + "defaultTheme" ); } else { theme = window.localStorage.getItem("defaultTheme"); } return theme || "v2"; }, formateDate(time) { if (!time) return ""; return dayjs(new Date(time)).format("YYYY-MM-DD HH:mm:ss"); //let str=date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); // return str; }, dateToString(date) { //日期转字符串 //console.log(date) let year = date.getFullYear(); let month = (date.getMonth() + 1).toString(); let day = date.getDate().toString(); if (month.length === 1) { month = "0" + month; } if (day.length === 1) { day = "0" + day; } const dateTime = year + "-" + month + "-" + day; return dateTime; }, pagination(data, callback) { const page = { onchange: (current) => { callback(current); }, current: data.pageInfo.pageNo, pageSize: data.pageInfo.pageSize, total: data.pageInfo.count, showTotal: () => { return `共${data.pageInfo.count}条`; }, showQuickIumper: true, }; return page; }, // getRadioList(data) { // if (!data) { // return []; // } // const options = [] // data.map((item) => { // options.push({item.name}) // return false // }) // return options // }, // downloadFile_(url) { // try { // let elemIF = document.createElement("iframe"); // //elemIF.src = url; // elemIF.src = "javascript: ''" // elemIF.style.display = "none"; // document.body.appendChild(elemIF); // } catch (e) { // message.error(e) // } // }, openFile(url, fileName, toolbar) { try { let a = document.createElement("a"); a.href = url + toolbar; a.target = "_blank"; document.body.appendChild(a); a.click(); document.body.removeChild(a); } catch (e) { console.log(e); } }, toLogin() { let programCode = this.programCode(); let applicationCode = this.applicationCode(); const version = localStorage.getItem("version"); const themes = this.getAllThemes(); const loginPath = themes[version]?.loginPath || "login2"; if (programCode && programCode != "null" && programCode != "undefined") { window.location.hash = applicationCode && applicationCode != "null" && applicationCode != "undefined" ? `#/${loginPath}/${programCode}/${applicationCode}` : `#/${loginPath}/${programCode}`; } else { window.location.hash = `#/${loginPath}`; } }, logout() { // 退出登录,清除数据缓存 currentUser = undefined; }, async downloadFile(url, fileName) { try { // 检查是否跨域 if (new URL(url).origin !== window.location.origin) { // 跨域资源使用Fetch API方式 const response = await fetch(url); const blob = await response.blob(); const blobUrl = window.URL.createObjectURL(blob); let a = document.createElement('a'); a.href = blobUrl; a.download = fileName; document.body.appendChild(a); a.click(); // 清理 window.URL.revokeObjectURL(blobUrl); document.body.removeChild(a); } else { let a = document.createElement("a"); a.download = fileName; a.href = url; //a.target= "_blank"; document.body.appendChild(a); a.click(); document.body.removeChild(a); } } catch (e) { console.log(e); } }, downloadFile_old(url) { try { let a = document.createElement("form"); a.action = url; //a.target= "_blank"; document.body.appendChild(a); a.submit(); document.body.removeChild(a); } catch (e) { console.log(e); } }, //随机数 getRandomNum(n) { let rnd = ""; let f = Math.floor(Math.random() * 10); rnd += f == 0 ? "1" : f + ""; for (let i = 1; i < n; i++) { rnd += Math.floor(Math.random() * 10); } return rnd; }, /** * 获得用于在本地持久缓存的数据的Key前缀 * 当前返回的值是第一次访问当前方法时的所在页面链接的pathname * 表示在不同的pathname下,永久缓存的数据将互不干扰 * @returns {undefined} */ getStorageKeyPrefix() { if (storageKeyPrefix === undefined) { storageKeyPrefix = window.location.pathname || ""; } return storageKeyPrefix; }, getLongTextStyle(value) { if (!value) { return {}; } let style = { minWidth: "normal", maxWidth: "1000px", display: "block", // textAlign: 'left', whiteSpace: "normal", lineHeight: "20px", }; let min_value_length = value.length > 200 ? "350px" : value.length > 150 ? "300px" : value.length > 100 ? "250px" : value.length > 50 ? "200px" : value.length >= 20 ? "160px" : "80px"; //let min_value_length = value.length > 20 ? '160px' : '80px'; style.minWidth = min_value_length; return style; }, setLocalStorge(key, value, min = 60) { if (key) { key = this.getStorageKeyPrefix() + key; } // 设置过期原则 if (!value) { localStorage.removeItem(key); } else { const Min = min || 60; const exp = new Date(); const expireAddTime = Min * 60 * 1000; localStorage.setItem( key, JSON.stringify({ value, expireAddTime, expires: exp.getTime() + expireAddTime, }) ); } }, getLocalStorge(name) { if (name) { name = this.getStorageKeyPrefix() + name; } try { let o = JSON.parse(localStorage[name]); if (!o || o.expires < Date.now()) { return null; } else { o.expires = Date.now() + o.expireAddTime; localStorage.setItem(name, JSON.stringify(o)); return o.value; } } catch (e) { // 兼容其他localstorage return localStorage[name]; } finally { } }, getAnoHydrocarbonToken() { let token = this.getLocalStorge("anoHydrocarbonToken"); if (!token) { token = "tmpl" + this.getRandomNum(6); this.setLocalStorge("anoHydrocarbonToken", token); } return token; }, transQueryParamsToStr(data, isPrefix = false, excudekeys = []) { let prefix = isPrefix ? "?" : ""; let _result = []; let paramKeys = []; //寻找参数 for (let key in data) { if (excudekeys.indexOf(key) >= 0) { continue; } let value = data[key]; // 去掉为空的参数 if ([undefined, null].includes(value)) { value = ""; continue; } else { paramKeys.push(key); } } //排序 paramKeys.sort(); for (let key of paramKeys) { let value = data[key]; let str = encodeURIComponent(key); if (!value) { } else if (key === "sortColIds") { value.forEach((_value) => { _result.push(str + "[]=" + encodeURIComponent(_value)); }); } else if (value && value.constructor === Array) { value.forEach((_value) => { _result.push(str + "[]=" + encodeURIComponent(_value)); }); } else { _result.push(str + "=" + encodeURIComponent(value)); } } return _result.length ? prefix + _result.join("&") : ""; }, getItemType(name_: string, value: string, ltmplConfig: LtmplConfig) { let name = name_; if (!value || !ltmplConfig) { return null; } if (name.startsWith("c_")) { name = name.substring(2); } let cs: CriteriaConfig[] = []; if (ltmplConfig.criteria) { cs.push(...ltmplConfig.criteria); } if (ltmplConfig.updrillButtonConfigs) { cs.push(...ltmplConfig.updrillButtonConfigs); } if (ltmplConfig.innerParams) { cs.push(...ltmplConfig.innerParams); } if (ltmplConfig.drillingParams) { cs.push(...ltmplConfig.drillingParams); } for (let c of cs) { if (c.id == name) { return ControlTypeSupportor.getControlType(c, value); } } return null; }, transQueryStrToParams(str, ltmplConfig: LtmplConfig) { let obj = {}; const arr1 = str.split("?"); if (arr1 && arr1.length == 2) { const arr2 = arr1[1].split("&"); for (let i = 0; i < arr2.length; i++) { if (arr2[i].indexOf("[]=") > 0) { const res = arr2[i].split("[]="); const name = res[0]; if (!obj[name]) { obj[name] = []; } let pvalue = decodeURIComponent(res[1]); obj[name].push( this.configParamTrans( pvalue, this.getItemType(name, pvalue, ltmplConfig) ) ); } else { const res = arr2[i].split("="); const name = res[0]; if (name) { let pvalue = decodeURIComponent(res[1]); obj[name] = this.configParamTrans( pvalue, this.getItemType(name, pvalue, ltmplConfig) ); } } } } return obj; }, isConfigDefaultValue(defaultValue) { if (!defaultValue) { return false; } return defaultValue.startsWith("$$current"); }, configParamTrans(value: string, itemType: string) { if (value && value.startsWith && value.startsWith("$$current")) { return TmplConfigAnalysis.current(value, this.getDayjsFormat(itemType)); } else if (value?.startsWith && value.startsWith("$$user.")) { // 默认值根据用户配置 let userInfo: UserInfo = this.getCurrentUserInfo(); if (!userInfo) { return null; } if (value?.startsWith && value.startsWith("$$user.code")) { return userInfo.id + "@R@"; } else { return userInfo?.extInfo?.fieldMap?.[value.split("user.")[1]] || null; } } else { return value; } }, uniq(array, gWord) { const res = []; array.map((item) => { let flag = true; res.map((it) => { if (item[gWord] === it[gWord]) { flag = false; } return false; }); if (flag) { res.push(item); } return false; }); return res; }, deepCopy(obj) { var result = Array.isArray(obj) ? [] : {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { if (typeof obj[key] === "object") { result[key] = this.deepCopy(obj[key]); //递归复制 } else { result[key] = obj[key]; } } } return result; }, // forPic(fieldMap) { //原始数据的图片url转化为图片 // for (let i in fieldMap) { // if (fieldMap[i] && fieldMap[i].includes("download-files")) { // const url = this.api() + fieldMap[i] // fieldMap[i] = // } // } // return fieldMap // }, getFileUrl(file) { if (!file) { return file; } else if (file.constructor === String) { return file; } else if (file.constructor === Object) { if (file.props.children.props) { const { href } = file.props.children.props; return href; } else if (file.props.owlner) { return file.props.owlner; } else { return file; } } else { return file; } }, getOptionColor(options: EnumItem[], value) { if (!value) { return null; } let color; if (options) { options.forEach((option) => { if (option.value === value) { if (option.color) { color = option.color; } return; } }); } return color; }, getFieldItemType(item) { return item.extType ? item.extType : item.msExtType ? item.msExtType : item.msType ? item.msType : item.type; }, isEmpty(obj) { if (!obj) { return true; } for (let key in obj) { return false; //非空 } return true; }, getDayjsFormat(itemType) { let format = "YYYY-MM-DD HH:mm:ss"; switch (itemType) { case "daterange-YY": case "date-YY": format = "YYYY"; break; case "date-M1": case "daterange-M1": format = "YYYY-MM"; break; case "date": case "daterange": format = "YYYY-MM-DD"; break; case "datetime-HH": case "datetimerange-HH": format = "YYYY-MM-DD HH"; break; case "datetime-mm": case "datetimerange-mm": format = "YYYY-MM-DD HH:mm"; break; case "datetime": case "datetimerange": format = "YYYY-MM-DD HH:mm:ss"; break; case "timestamp": format = "YYYY-MM-DD HH:mm:ss SSS"; break; case "time-HH": case "timerange-HH": case "timerange-HH-unorder": format = "HH"; break; case "time-mm": case "timerange-mm": case "timerange-mm-unorder": format = "HH:mm"; break; case "time": case "timerange": case "timerange-unorder": format = "HH:mm:ss"; break; } return format; }, getDateTimeFormat(itemType) { let format = ""; switch (itemType) { case "time-HH": case "timerange-HH": case "datetime-HH": case "datetimerange-HH": return "HH"; case "time-mm": case "timerange-mm": case "datetime-mm": case "datetimerange-mm": return "HH:mm"; case "timestamp": case "time": case "timerange": case "datetime": case "datetimerange": return "HH:mm:ss"; default: return ""; } return format; }, // getSelectOptions(data: EnumItem[]) { // // if (!data) { // return []; // } // const options = [] // data.map((item) => { // options.push() // return false // }) // return options // }, // getSelectListOfStrList(data) { // // if (!data) { // return []; // } // const options = [] // data.map((item) => { // options.push() // return false // }) // return options // }, // getSelectOptionsOfMstrucId(mstrucId: string) { // return this.getSelectOptions(HCDataSource.getEnums(mstrucId)); // }, concatValue(value1, vaule2) { let newValue = undefined; if (value1) { newValue = value1 + "~"; } else { newValue = "~"; } if (vaule2) { newValue = newValue + vaule2; } return newValue; }, splitValue(value) { let valueBegin, valueEnd; if (value) { if (value.toString().indexOf("~") >= 0) { let splitValue: string[] = value.split("~"); valueBegin = splitValue[0] ? splitValue[0] : undefined; valueEnd = splitValue[1] ? splitValue[1] : undefined; } else { valueBegin = value; } } return { valueBegin, valueEnd }; }, str2UTF8(str) { var bytes = new Array(); var len, c; len = str.length; for (var i = 0; i < len; i++) { c = str.charCodeAt(i); if (c >= 0x010000 && c <= 0x10ffff) { bytes.push(((c >> 18) & 0x07) | 0xf0); bytes.push(((c >> 12) & 0x3f) | 0x80); bytes.push(((c >> 6) & 0x3f) | 0x80); bytes.push((c & 0x3f) | 0x80); } else if (c >= 0x000800 && c <= 0x00ffff) { bytes.push(((c >> 12) & 0x0f) | 0xe0); bytes.push(((c >> 6) & 0x3f) | 0x80); bytes.push((c & 0x3f) | 0x80); } else if (c >= 0x000080 && c <= 0x0007ff) { bytes.push(((c >> 6) & 0x1f) | 0xc0); bytes.push((c & 0x3f) | 0x80); } else { bytes.push(c & 0xff); } } return bytes; }, joinPath(path1, path2) { let path = path1; if (!path.endsWith("/") && !path.endsWith("\\")) { path = path + "/"; } if (path2) { if (path2.startsWith("/") || path.startsWith("\\")) { path = path + path2.slice(1); } else { path = path + path2; } } return path; }, // getRouteProgramCode(pathProps){ // if (pathProps && pathProps.match && pathProps.match.params) { // const {programCode} = pathProps.match.params; // return programCode; // } // }, setProgramCode4RoutePath(pathParams) { const { programCode, applicationCode } = pathParams; this.setProgramCode(programCode); this.setApplicationCode(applicationCode); }, setSessionProgramCode4RoutePath(pathParams) { const { programCode, applicationCode } = pathParams; this.setSessionProgramCode(programCode); this.setSessionApplicationCode(applicationCode); }, getReactKey() { return new Date().getTime().toString(); }, async getUserInfo(programCode?: string, token?: string, applicationCode?: string) { if (currentUser?.name) { return currentUser; } let user = await HcserviceV3.getUser(programCode, token, applicationCode); if (user?.orgGtmplSourceId && !["null"].includes(user.orgGtmplSourceId)) { const { ltmplConfig } = await HcserviceV3.requestLtmplConfig(null, user.orgGtmplSourceId) || {}; const { entities } = await HcserviceV3.requestLtmplQueryTop(null, user.orgGtmplSourceId, { top: 1 }) || {}; const primaryColumnId = ltmplConfig?.extDisplayConfig?.primaryColumn?.id; // 首字段 const mainPictureId = ltmplConfig?.extDisplayConfig?.mainPicture?.id; // 主图字段 const orgName = entities?.[0]?.fieldMap?.[primaryColumnId]; const homeImg = entities?.[0]?.fieldMap?.[mainPictureId]; const orgCode = entities?.[0]?.code; // 租户Code user = { ...user, orgName, homeImg, orgCode } } currentUser = user; return currentUser; }, getCurrentUserInfo() { return currentUser; }, // 低代码拖拽页面-自定义组件 setCustomComponent(key_: string, name: object) { let key = key_; if (!key) { return; } CUSTOM_COMPONENT_MAP[key] = name; }, getCustomComponent(key: string) { if (!key) { return null; } return CUSTOM_COMPONENT_MAP[key]; }, getAllThemes() { // 主题风格-路径配置 const themes = { v2: { path: "v2", loginPath: "login2" }, v3: { path: "v3", loginPath: "login3" }, v4: { path: "v4", loginPath: "login4" }, v5: { path: "v5", loginPath: "login2" }, }; return themes; }, toDefaultTheme(defTheme?: string) { const temTheme = defTheme || ProgramConfig.getDefaultTheme(); let hash = window.location.hash; if (regexTheme.test(hash)) { hash = hash.replace(regexTheme, `${temTheme}/home`); window.location.hash = hash; } else { const localVersion = localStorage.getItem("version"); if (!localVersion) { window.location.hash = `#/${temTheme}/home`; } } }, async getThemeConfig(serverKey?: string) { if (themeConfig) { return themeConfig; } const programCode = this.programCode(); const applicationCode = this.applicationCode(); const server = this.api(serverKey); const { themeConfig: temConfig } = await HcserviceV3.getThemeConfig(serverKey, programCode) || {}; const loginMainPicture = temConfig?.loginMainPicture ? this.joinPath(server, `/v3/theme-files/${temConfig?.loginMainPicture}?@programToken=${programCode}&@applicationToken=${applicationCode}`) : null; const programIcon = temConfig?.programIcon ? this.joinPath(server, `/v3/theme-files/${temConfig?.programIcon}?@programToken=${programCode}&@applicationToken=${applicationCode}`) : null; themeConfig = { ...temConfig, loginMainPicture, programIcon }; return themeConfig; }, getThemeConfigInfo() { return themeConfig; }, coverUserPageConfig(setting: { [key: string]: any }) { // 页面配置覆盖 const currentUser = this.getCurrentUserInfo(); if (!setting || !currentUser) return; const programCode = this.programCode(); const applicationCode = this.applicationCode(); const localKey = `${currentUser.id}-${programCode}${applicationCode ? `-${applicationCode}` : ""}-userPageConfig`; localStorage.setItem(localKey, JSON.stringify(setting)); }, setUserPageConfig(key: string, setting: { [key: string]: any }) { // 页面配置(视图、列、分页等)存本地 const currentUser = this.getCurrentUserInfo(); if (!key || !setting || !currentUser) return; const programCode = this.programCode(); const applicationCode = this.applicationCode(); const localKey = `${currentUser.id}-${programCode}${applicationCode ? `-${applicationCode}` : ""}-userPageConfig`; const userPageConfig = localStorage.getItem(localKey) || "{}"; let config = {}; try { config = JSON.parse(userPageConfig); } catch { config = {}; } config[key] = { ...(config[key] || {}), ...setting }; localStorage.setItem(localKey, JSON.stringify(config)); return config[key]; }, async getUserPageConfig(key: string) { // 获取当前页面配置本地缓存 const currentUser = await this.getUserInfo(); if (!key || !currentUser) return; const programCode = this.programCode(); const applicationCode = this.applicationCode(); const localKey = `${currentUser.id}-${programCode}${applicationCode ? `-${applicationCode}` : ""}-userPageConfig`; const userPageConfig = localStorage.getItem(localKey) || "{}"; try { const config = JSON.parse(userPageConfig); return config[key]; } catch { return; } }, resetUserPageConfig(key: string) { // 重置当前页面配置本地缓存 const currentUser = this.getCurrentUserInfo(); if (!key || !currentUser) return; const programCode = this.programCode(); const applicationCode = this.applicationCode(); const localKey = `${currentUser.id}-${programCode}${applicationCode ? `-${applicationCode}` : ""}-userPageConfig`; const userPageConfig = localStorage.getItem(localKey) || "{}"; try { const config = JSON.parse(userPageConfig); config[key] = undefined; localStorage.setItem(localKey, JSON.stringify(config)); } catch { return; } }, async getPageConfigCommon(menuCode: string, type?: "default" | "refresh") { // type == refresh 请求新数据,不使用缓存 if ((!type || type === "default") && pageConfigCommons[menuCode]) { return pageConfigCommons[menuCode]; } const configs = await HcserviceV3.getPageConfigCommon(menuCode); pageConfigCommons[menuCode] = configs; return configs; }, async getPageConfigDefault() { // 拉取用户默认配置 const configs = await HcserviceV3.getPageConfigDefault(); const defUserPageConfig = configs.reduce((total, cur) => { total[cur.menuCode] = cur.content ? JSON.parse(cur.content) : undefined; return total; }, {}); this.coverUserPageConfig(defUserPageConfig); // 覆盖本地缓存 return configs; }, findItemByIdIterative(tree: any[], value: string | number, key = "id") { // 查找树级数组中的指定项 if (!tree?.length) { return undefined; } // 使用一个栈来存储待遍历的节点 const stack = [...tree]; while (stack.length > 0) { const node = stack.pop(); if (node[key] === value) { return node; } if (node.children && node.children.length > 0) { stack.push(...node.children); } } return undefined; }, async get2DComponent(groups: string[]) { // 获取2D组件数据 const temGroups = groups.filter(r => !components2DMap[r]); if (!temGroups?.length) { return components2DMap; } const res = await HcserviceV3.get2DComponent(temGroups); const temObj = Object.keys(res).reduce((total, next) => { total[next] = res[next] || []; return total; }, {}); components2DMap = { ...components2DMap, ...temObj }; return components2DMap; }, get2DComponentByType(type: string) { // 获取指定类型组件 if (!type) { return; } const item = Object.values(components2DMap).flat(Infinity).find((r: any) => r.type === type); return item; }, setCrossProjectCode(codes: { [key: string]: string }) { // 设置全局跨项目code Cross_Project_Code = codes; }, getCrossProjectCode(sourceId: string) { // 获取全局跨项目code return Cross_Project_Code[sourceId]; }, arrayToMap(arr: any[], key: string) { // 对象数组转Map if (arr?.length) { return new Map(arr.map(item => [item[key], item])); } else { return arr; } }, formatDuration(totalSeconds, level = 'second-daysecond', translate?: Function) { // 时长格式化显示 if (typeof totalSeconds !== 'number' || isNaN(totalSeconds) || totalSeconds <= 0) { return `0${translate ? translate("秒") : "秒"}`; } const units = [ { label: '年', base: 31536000 }, { label: '天', base: 86400 }, { label: '时', base: 3600 }, { label: '分', base: 60 }, { label: '秒', base: 1 } ]; const levelConfig = { 'second-daysecond': 4, // 显示到 秒 (下标4) 'second-dayminute': 3, // 显示到 分 (下标3) 'second-dayhour': 2, // 显示到 时 (下标2) 'second-day': 1 // 显示到 天 (下标1) }; const maxIndex = levelConfig[level] || 4; // 当前允许显示的最大层级下标 let remaining = Math.floor(totalSeconds); const allParts = []; for (let i = 0; i < units.length; i++) { const count = Math.floor(remaining / units[i].base); remaining %= units[i].base; if (count > 0) { allParts.push({ label: units[i].label, count: count, index: i }); } } const validParts = allParts.filter(p => p.index <= maxIndex); if (validParts.length === 0) { if (allParts.length > 0) { const fallback = allParts[allParts.length - 1]; return `${fallback.count}${fallback.label}`; } return `0${translate ? translate("秒") : "秒"}`; } return validParts.map(p => `${p.count}${translate ? translate(p.label) : p.label}`).join(''); }, compressString(value: string) { // 压缩字符串 // 1. 将普通字符串转换为 Uint8Array const dataBuffer = strToU8(value); // 2. 压缩为 ByteArray const content = gzipSync(dataBuffer, { level: 9 }); // 3. 将 Uint8Array 转为 16进制字符串 const hexString = uint8ArrayToHex(content); return hexString; }, decompressString(value: string) { // 解压字符串 const temByteArray = hexToUint8Array(value.replace(/^0x/i, "")); // 1. 将压缩的 ByteArray 解压回原始的 Uint8Array const decompressedBuffer = gunzipSync(temByteArray); // 2. 将 Uint8Array 转换回普通字符串 const data = strFromU8(decompressedBuffer); return data; } };