UNPKG

sunmao-sdk

Version:

榫卯-开箱即用赋能-sdk

739 lines (704 loc) 22.1 kB
import { getDicDetails, getNew } from "../net/request"; import * as Api from "../net/api"; import CP from "../config"; import * as commonUtils from "./commonUtils"; import { isArray, isEmpty } from "lodash"; import QuestionCircle from "../component/QuestionCircle"; import { isJSON } from "validator"; import moment from "moment"; const DEFAULTFORMITEM = { key: "", // 传参名 、、 字段名 label: "", // 显示名 type: "5fba5336e126bfe143d7c75e", // 表单类型 columns: 1, // 占列数,默认1 isRequired: "5fb8b922e2559fcd82cad4d3", // 是否必选 selectTrue: "5fb8b91ae2559fcd82cad4d2", // 默认显示 dicSource: "38", // 字典来源 dic: "", // 选择 枚举 父id level: 5, // 联级、树形 选择 多少层级 changeOnSelect: "5fb8b922e2559fcd82cad4d3", // 联级选择是否 记录父级 dicStatic: null, // 静态字典数据 dicDefault: null // 默认选中,匹配不上则默认选择首项 }; const DEFAULTFORMSCHEMAITEM = { // "title": "label显示名", type: "string", //默认string,还有对象、数字、数组等等 ,需动态配置 ;range 区间 需要与format: date dateTime 一起使用 "ui:width": "100%" // "ui:className": "scale-label", ///配置样式,不常使用 // 'ui:hidden': (value, rootValue) => rootValue.fixedSwitch, //是否隐藏,后面为联动操作 //default: //配置默认值 // 'ui:widget': 'selectCascader', //自定义组件配置 // commonProps: { //自定义组件配置 // url: Api.getDictionaries, // params: { level: 5, id: '5fc755cdd36820f941198b21' }, // requestFunc: getNew, // }, // "ui:options": { //透传配置,一般为antd组件透传使用 // fieldNames: { label: 'name', value: 'id', children: 'children' }, // changeOnSelect: true // }, // pattern: '^((?!(dev.|.wapa.|.waptest.|pre-|.pre.|daily)).)*$',//添加正则 // format: 'email' //校验判断 参考 https://yuque.antfin-inc.com/zht/collect/divnm5 date。dateTime // "ui:width": "66%" //设置宽度,需动态配置,做成最外层配置最好 }; const DEFAULTFORMSCHEMA = { // labelWidth: 135, label宽度 :默认120 TODO 需可动态配置 displayType: "row", formData: {}, propsSchema: { type: "object", required: [], // 必填项判断:只能判断null undefined,不能判断空数组,需要注意【】 TODO 需可动态配置 properties: {} //具体表单内容,基本为封装该对象内容 } }; const DEFAULTFORMINFO = { formItems: [] }; export function defaultItem() { return JSON.parse(JSON.stringify(DEFAULTFORMITEM)); } export function defaultFormSchemaItem() { return JSON.parse(JSON.stringify(DEFAULTFORMSCHEMAITEM)); } export function defaultFormSchema() { return JSON.parse(JSON.stringify(DEFAULTFORMSCHEMA)); } export function defaultFormInfo() { return JSON.parse(JSON.stringify(DEFAULTFORMINFO)); } export function itemTranslSchema(item, columnWidth) { const itemSchema = defaultFormSchemaItem(); // 默认为输入框 itemSchema.title = item.label; // label提示 if (item.remark) { itemSchema.description = item.remark; itemSchema["ui:showDescIcon"] = true; } // 计算宽度 : "50%", itemSchema["ui:width"] = `${columnWidth * (item.columns || 1)}%`; // 添加提示语 let antdProps = {}; try { antdProps = JSON.parse(item.antdProps); } catch (e) {} itemSchema["ui:options"] = antdProps; const isSelected = item.isSelected ?? true; itemSchema["ui:hidden"] = !isSelected; switch (item.type) { case "5fba5336e126bfe143d7c75f": // 下拉单选 itemSchema["ui:widget"] = "selectCommon"; itemSchema.commonProps = setDicSchema(item, itemSchema); itemSchema.commonProps.labelInValue = item.labelInValue; break; case "5fba5336e126bfe143d7c760": // 下拉多选 itemSchema["ui:widget"] = "selectCommon"; itemSchema["ui:options"] = { mode: "multiple", ...antdProps }; itemSchema.commonProps = setDicSchema(item, itemSchema); break; case "checkbox_duoxuanbiaodan": // 点击多选 itemSchema["ui:widget"] = "checkboxCommon"; itemSchema.commonProps = setDicSchema(item, itemSchema); break; case "radio_dianjidanxuan": // 点击单选 itemSchema["ui:widget"] = "radioCommon"; itemSchema.commonProps = setDicSchema(item, itemSchema); break; case "5fd9ae46a28bd54e44773290": // 树形多选 itemSchema.default = "该组件还在酝酿中。。。"; break; case "5fba5336e126bfe143d7c761": // 级联选择 itemSchema["ui:widget"] = "selectCascader"; itemSchema["ui:options"] = { ...antdProps, // 组件内 续统一处理为通用fieldNames // fieldNames: { // label: item.dicApi?.text || "preName", // value: item.dicApi?.key || "id", // children: item.children || "children" // }, changeOnSelect: getDicTrue(item.changeOnSelect) }; itemSchema.commonProps = setDicSchema(item, itemSchema); break; case "5fba535ce126bfe143d7c763": //时间区间 itemSchema.type = "range"; case "5fba535ce126bfe143d7c762": //时间单选 itemSchema.format = "time"; break; case "5fd9ab0fa28bd54e4477328b": //日期区间 itemSchema.type = "range"; case "5fd9ab0fa28bd54e4477328a": //日期单选 itemSchema.format = "date"; break; case "5fd9ab0fa28bd54e4477328d": //日期时间区间 itemSchema.type = "range"; case "5fd9ab0fa28bd54e4477328c": //日期时间 itemSchema.format = "dateTime"; break; case "5fd9ab71a28bd54e4477328e": //数字输入框 itemSchema.type = "number"; break; case "5fd9ab71a28bd54e4477328f": //数字区间输入框 itemSchema["ui:widget"] = "inputInterval"; break; case "gudingcanshu_xianshibukexiugai": // 固定参数,显示不隐藏 itemSchema["ui:widget"] = "smText"; break; case "gudingcanshu_yincangbuxianshi": // 固定参数,隐藏不显示 itemSchema["ui:hidden"] = true; case "gudingcanshu_bukebianji": // 固定参数,显示不可编辑 itemSchema["ui:disabled"] = true; case "5fba5336e126bfe143d7c75e": // 输入框 default: // 默认为输入框 break; } // 初始化默认值 itemSchema.default = getDefault( item.dicDefault, itemSchema.type, itemSchema.format ); return itemSchema; } function setDicSchema(item, itemSchema) { let commonProps = {}; try { switch (item.dicSource) { case "39": // 请求 参数配置暂不支持 ,暂时支持get请求 commonProps = { ...item.dicApi, url: commonUtils.getUrl(item.dicApi.url), requestFunc: CP.getCPInfo().requestFunc || getNew, params: commonUtils.isObj(item.dicApi?.params) ? item.dicApi.params : {} }; break; case "40": // 静态 commonProps.list = item.dicStatic; break; case "38": // 平台 default: // 是否为新字典数据源 const isNewNet = !itemSchema["ui:options"]?.isOldDic; // 平台请求接口统一走网关 commonProps.requestFunc = isNewNet ? getDicDetails : getNew; commonProps.url = isNewNet ? Api.getDictionaries : Api.getDictionariesOld; commonProps.params = { level: item.level, pid: item.dic[item.dic.length - 1], code: item.dic[item.dic.length - 1] // 新接口 所需参数 code }; commonProps.okPath = "data"; break; } } catch (error) { commonUtils.log("setDicSchema", error); } return commonProps; } export function listTranslSchema(formList, formColumn = 1, formData = {}) { const formSchema = defaultFormSchema(); formSchema.formData = formData; const columnWidth = parseInt(100 / formColumn); if (Array.isArray(formList)) { for (const i of formList) { // TODO 需要计算宽度 formSchema.propsSchema.properties[i.key] = itemTranslSchema( i, columnWidth ); if (i.labelInValue) { formSchema.propsSchema.properties[i.labelInValue] = itemTranslSchema( { type: "gudingcanshu_yincangbuxianshi" }, columnWidth ); } getDicTrue(i.isRequired) && formSchema.propsSchema.required.push(i.key); } } return formSchema; } /** * 从formList获取总initData * @param {FR的schema} formList * @returns 初始值对象 */ export function getInitData(formList) { const ret = {}; for (const item of formList) { const defaultValue = getDefault(item.dicDefault, item.type, item.format); defaultValue && (ret[item.key] = item.dicDefault); } return ret; } /** * 从formList获取固定传参initData * @param {FR的schema} formList * @returns 初始值对象 */ export function getDefaultInitData(formList) { // 获取固定传参list const defaultList = formList.filter( i => i.type === "gudingcanshu_yincangbuxianshi" || i.type === "gudingcanshu_bukebianji" ); return getInitData(defaultList); } /** * 从FR的schema获取总initData * @param {FR的schema} frSchema * @returns 初始值对象 */ export function getFRInitData(frSchema) { const ret = { ...frSchema.formData }; let tmpDefault; try { for (let key in frSchema.propsSchema.properties) { try { tmpDefault = frSchema.propsSchema.properties[key].default; if (!isEmpty(tmpDefault)) { ret[key] = frSchema.propsSchema.properties[key].default; } } catch {} } } catch {} return ret; } /** * json格式数据快速转为form数组对象 * @param {json} json * @param {默认类型} type * @returns */ export function jsonToListOfForm(json, type) { try { const forms = JSON.parse(json); const formItems = []; for (const key in forms) formItems.push(_.assign(defaultItem(), { type, key, label: forms[key] })); return formItems; } catch (e) { console.error("JSON格式错误-------:", json); throw e; } } /** * ************************************* * 以上是Form * ***分割线*** * 以下是Column * ************************************* */ const DEFAULTCOLUMNITEM = { isSort: "5fb8b922e2559fcd82cad4d3", // 是否支持排序 selectTrue: "5fb8b91ae2559fcd82cad4d2", // 默认显示 dataIndex: "", // key title: "", // 列名 width: 150, // 列宽 align: "left" // 对齐方式 }; const DEFAULTCOLUMNINFO = { columnItems: [] }; export function defaultColumn() { return JSON.parse(JSON.stringify(DEFAULTCOLUMNITEM)); } export function defaultColumnSchema() { return JSON.parse(JSON.stringify([])); } export function defaultColumnInfo() { return JSON.parse(JSON.stringify(DEFAULTCOLUMNINFO)); } export async function getTableColumns(list = []) { let lastEnum, result; const _list = []; const len = list.length; for (let i = 0; i < len; i++) { lastEnum = null; result = list[i]; const { label, title, remark, // 备注 isSort, // 是否排序 默认否 noEllipsis, // 是否换行展示(不省略) 默认true renderType, // 筛选类型 filterMultiple // 是否多选 } = result; result.label = label || title; result.ellipsis = !getDicTrue(noEllipsis); try { // 判断存在筛选 设置筛选组件 switch (renderType) { case "column_enum": // 获取 枚举配置信息 const { dicStatic, requestFunc, url, params, okPath, key, text, children } = setDicSchema(c, {}); lastEnum = dicStatic; // 静态枚举 if (!isArray(lastEnum) && requestFunc) { // 动态枚举 const req = await requestFunc( url, showSearch ? _params : params, okPath ); lastEnum = commonUtils.getFirstList(req); } lastEnum = getCPDicList(lastEnum, key, text, children); if (lastEnum) { result.filters = lastEnum; result.filterMultiple = getDicTrue(filterMultiple); } break; case "column_search": // 输入框选择 break; default: // // 默认 //TODOdev // const { // dicStatic = [ // { // title: "已发布", // id: "1" // }, // { // title: "测试中", // id: "2" // }, // { // title: "开发中", // id: "3" // }, // { // title: "待排期", // id: "4" // } // ], // requestFunc = getDicDetails, // url = Api.getDictionaries, // params = { level: 1, code: "29" }, // okPath = "data", // key, // text, // children // } = {}; // lastEnum = dicStatic; // 静态枚举 // if (!isArray(lastEnum) && requestFunc) { // // 动态枚举 // const req = await requestFunc(url, params, okPath); // lastEnum = commonUtils.getFirstList(req); // } // lastEnum = getCPDicList(lastEnum, key, text, children); // if (lastEnum) { // result.filters = lastEnum; // result.filterMultiple = !!(i % 2); // } } } catch {} // 添加备注提示 if (remark) { result.title = () => ( <> <QuestionCircle title={remark} style={{ marginRight: "4px" }} /> {label || title} </> ); } // 添加排序 if (getDicTrue(isSort)) { result.sorter = true; result.sortDirections = ["descend", "ascend"]; } _list.push(result); } return _list; } export function getTableWidth(columns) { let tableWidth = 0; columns.forEach(item => { tableWidth += item.width || 150; }); return tableWidth; } export function jsonToListOfColumn(json) { try { const jsonObj = JSON.parse(json); const columns = Array.isArray(jsonObj) ? jsonObj[0] : jsonObj; const columnItems = []; for (const key in columns) columnItems.push( _.assign(defaultColumn(), { dataIndex: key, title: columns[key] }) ); return columnItems; } catch (e) { console.error("JSON格式错误-------:", json); throw e; } } /** * ************************************* * 以上是Column * ***分割线*** * 以下是Table-Handle * ************************************* */ const DEFAULTHANDLEINFO = { rowSelection: "5fb8b922e2559fcd82cad4d3", rowKey: "id", handleItems: [] }; export function defaultHandleInfo() { return JSON.parse(JSON.stringify(DEFAULTHANDLEINFO)); } // 获取表行操作按键 差异在action export function getTableHandle(handleItems) { const ret = { btn: false, acl: [] }; if (!handleItems) return ret; ret.btn = []; for (const action of handleItems) { if (action.aclPermissionCode) ret.acl.push(action.aclPermissionCode); ret.btn.push({ ...action, text: action.label, action: `$func.${ action.funcType && "33" !== action.funcType ? "onSdkTableHandle" : action.funcName }`, content: action.content, funcType: action.funcType }); } return ret; } // 获取表头操作按键 差异在action export function getTableBtn(handleItems) { const ret = { btn: false, acl: [], openCustomColumns: false // 用户自定义表头开关 }; if (!handleItems) return ret; ret.btn = []; for (const action of handleItems) { if (action.aclPermissionCode) ret.acl.push(action.aclPermissionCode); const btnItem = { ...action, text: action.label, action: `$func.${ action.funcType && "33" === action.funcType ? action.funcName : "onSdkTableBtn" }`, renderFunc: action.renderFunc ? `$func.${action.renderFunc}` : "", // 自定义组件展示函数 content: action.content, funcType: action.funcType }; if ("37" === action.funcType) { try { // 下拉按键需对子按键进行处理 const { btn: tableHandle, acl: tableAcl, openCustomColumns: customColumns } = getTableBtn(action.content.handleItems); action.content.handleItems = tableHandle; ret.acl = ret.acl.concat(tableAcl); if (!ret.openCustomColumns && customColumns) { ret.openCustomColumns = true; } } catch {} } else if (!ret.openCustomColumns && "38" === action.funcType) { ret.openCustomColumns = "38" === action.funcType; } ret.btn.push(btnItem); } return ret; } // 获取表Tab操作按键 差异在action export function getTableTab(handleItems, actionStr) { const ret = { btn: false, acl: [] }; if (!handleItems) return ret; ret.btn = []; for (const action of handleItems) { if (action.aclPermissionCode) ret.acl.push(action.aclPermissionCode); ret.btn.push({ ...action, text: action.label, action: actionStr, content: action.content, funcType: action.funcType }); } return ret; } /** * ************************************* * 以上是Table-Handle * ***分割线*** * 以下是Page --- 包含Form、Column、Table-Handle * ************************************* */ const DEFAULTPAGE = { appId: "", // 应用id projectId: "", // 项目id form: DEFAULTFORMINFO, // 表单信息 table: DEFAULTCOLUMNINFO, // 表格信息 tableBtn: DEFAULTHANDLEINFO, // 表格操作区信息 handle: DEFAULTHANDLEINFO // 表格操作区信息 // 还需完善 }; export function defaultPageInfo() { return JSON.parse(JSON.stringify(DEFAULTPAGE)); } /** * ************************************* * 以上是 Page --- 包含Form、Column、Table-Handle * ***分割线*** * 以下是 平台静态字典生成 * ************************************* */ export function getCPDic({ key, text, children, labels }) { const listJson = labels?.trim(); let ret; try { const list = JSON.parse(listJson); return getCPDicList(list, key, text, children); } catch (e) { console.error("JSON格式错误-------:", listJson); throw e; } } export function getCPDicList(list, key, text, children) { let ret; if (Array.isArray(list) && list.length) { ret = []; let realData; for (const i of list) { realData = getCPDicItem(i, key, text, children); realData && ret.push(realData); } } return ret; } function getCPDicItem(item, key, name, children) { if (!item) return false; const ret = {}; ret.id = getId(item, key); ret.title = getName(item, name); ret.value = ret.id; ret.label = ret.title; ret.text = ret.title; ret.disabled = item.disabled; // 暂时添加disabled const son = getCPDicList(getChildren(item, children), key, name, children); son && (ret.children = son); return ret.id ? ret : false; } export function getId(item, key) { // 自定义key优先 // 旧数据结构 key优先 // 新增 新数据结构 code return (item[key] || item.key || item.code || item.id || item.type) + ""; } export function getName(item, key) { // 自定义key优先 // 新增 新数据结构 code // 旧数据结构 preName兜底 return item[key] || item.value || item.title || item.name || item.preName; } export function getDisabled(item, key) { // 自定义key优先 // 新增 新数据结构 code // 旧数据结构 disabled return item[key] || item.disabled; } export function getChildren(item, key) { let son = item[key] || item.children; // 可以考虑配置首个list为children return son; } export function getDicTrue(key) { return key === "5fb8b91ae2559fcd82cad4d2"; } export function getDefault(dicDefault, type, format) { try { // 当初始值为json时,进行转化 对dicDefault优化处理 if (dicDefault && isJSON(dicDefault)) { // 如果有 today开始的时间区间 则进行转化 return getDefaultRangeToday(format, JSON.parse(dicDefault)); } // 暂时支持日期 区间特殊情况 如取最近多少天 const day = parseInt(dicDefault); if (day && type === "range") { if (format === "date") { return [ moment() .subtract(day, "days") .format("YYYY-MM-DD"), moment().format("YYYY-MM-DD") ]; } else if (format === "dateTime") { return [ moment() .subtract(day, "days") .format("YYYY-MM-DD HH:mm:ss"), moment().format("YYYY-MM-DD HH:mm:ss") ]; } } } catch (e) { console.log(e); } // 后期扩展类型转换 return dicDefault; } /** * * @param {日期格式} format * @param {默认值} defaultValue * @returns */ export function getDefaultRangeToday(format, defaultValue) { try { // 命中 today时间区间 // 是日期 format // 数组长度 为2 // 有today 需要转化 if ( format.includes("date") && defaultValue.length === 2 && (defaultValue[0] === "today" || defaultValue[1] === "today") ) { // 后续可支持 today前后 n 天的配置 if (format === "date") { if (defaultValue[0] === "today") defaultValue[0] = moment().format("YYYY-MM-DD"); if (defaultValue[1] === "today") defaultValue[1] = moment().format("YYYY-MM-DD"); } else if (format === "dateTime") { if (defaultValue[0] === "today") defaultValue[0] = moment().format("YYYY-MM-DD 00:00:00"); if (defaultValue[1] === "today") defaultValue[1] = moment().format("YYYY-MM-DD 23:59:59"); } } } catch (e) { console.log(e); } return defaultValue; }