import { formatCode } from './../codeformat'; import { GeneratorConfig } from '../../model/generator/generatorConfig'; import { camelCase, cloneDeep, upperFirst } from 'lodash-es'; import { ColumnType } from '/@/model/generator/tableInfo'; import { ComponentConfigModel, ComponentOptionModel, FrontCodeModel, } from '/@/model/generator/codeGenerator'; import { QueryConfig } from '/@/model/generator/listConfig'; import { FormProps } from '/@/components/Form'; import { TableInfo } from '/@/components/Designer'; import { camelCaseString } from '/@/utils/event/design'; import { handleAppSearchForm, handleSearchForm } from './exportHelper'; import { PrintButton } from '/@/enums/printEnum'; import { AppFormProps } from '/@/model/generator/appFormConfig'; import { GeneratorAppModel } from '/@/api/system/generator/model'; import { buildAppComponentType, setApiConfig } from './designHelper'; import { getWorkflowPermissionConfig } from '/@/hooks/web/useWorkFlowForm'; const isOutputDirLowerName=false; /** * 构建代码 * @param model 配置 * @param tableInfo 后端数据库表信息 */ export function buildCode( model: GeneratorConfig, tableInfo: TableInfo[], formProps: FormProps, ): FrontCodeModel { const frontCode: FrontCodeModel = { listCode: buildListCode(model), formCode: buildFormCode(model, tableInfo), apiCode: buildApiCode(model, tableInfo), modelCode: buildModelCode(model, tableInfo), configJsonCode: buildConfigJsonCode(model, formProps), workflowPermissionCode: buildWorkflowPermissionConfigJsonCode(formProps), //工作流权限配置 simpleFormCode: buildSimpleFormCode(model, tableInfo), //simpleForm页面 }; return frontCode; } /** * 构建代码 * @param model 配置 * @param tableInfo 后端数据库表信息 */ export function buildAppCode( model: GeneratorConfig, formProps: AppFormProps, designType: string, ): GeneratorAppModel { const frontCode: GeneratorAppModel = { className: model.outputConfig.className, outputArea: model.outputConfig.outputArea, outputValue: model.outputConfig.outputValue, listCode: buildAppListCode(model), formCode: buildAppFormCode(model), containerCode: buildAppContainerCode(), apiCode: buildAppApiCode(model), tagString: buildTagStringCode(model), configJsonCode: buildAppConfigJsonCode(model, formProps, designType), }; return frontCode; } /** * 构建api代码 * @param model 配置 */ export function buildApiCode(model: GeneratorConfig, _tableInfo: TableInfo[]): string { const className = model.outputConfig.className; // const lowerClassName = lowerCase(className); const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; const pascalClassName = upperFirst(camelCase(className)); let mainTable; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName)); const hasSetUserIdButton = hasButton(model.listConfig.buttonConfigs, 'batchSetUserId'); const hasExportButton = hasButton(model.listConfig.buttonConfigs, 'export'); const code = ` import { ${pascalMainTableName}PageModel, ${pascalMainTableName}PageParams, ${pascalMainTableName}PageResult } from './model/${pascalClassName}Model'; import { defHttp } from '/@/utils/http/axios'; import { ErrorMessageMode } from '/#/axios'; enum Api { Page = '/${model.outputConfig.outputValue}/${lowerClassName}/page', List = '/${model.outputConfig.outputValue}/${lowerClassName}/list', Info = '/${model.outputConfig.outputValue}/${lowerClassName}/info', ${pascalMainTableName} = '/${model.outputConfig.outputValue}/${lowerClassName}', ${ hasSetUserIdButton ? ` DataAuth = '/${model.outputConfig.outputValue}/${lowerClassName}/data-auth',` : '' } ${ hasExportButton ? ` Export = '/${model.outputConfig.outputValue}/${lowerClassName}/export',` : '' } } /** * @description: 查询${pascalMainTableName}分页列表 */ export async function get${pascalMainTableName}Page(params: ${pascalMainTableName}PageParams, mode: ErrorMessageMode = 'modal') { return defHttp.get<${pascalMainTableName}PageResult>( { url: Api.Page, params, }, { errorMessageMode: mode, }, ); } /** * @description: 获取${pascalMainTableName}信息 */ export async function get${pascalMainTableName}(id: String, mode: ErrorMessageMode = 'modal') { return defHttp.get<${pascalMainTableName}PageModel>( { url: Api.Info, params: { id }, }, { errorMessageMode: mode, }, ); } /** * @description: 新增${pascalMainTableName} */ export async function add${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') { return defHttp.post( { url: Api.${pascalMainTableName}, params: ${camelCaseMainTableName}, }, { errorMessageMode: mode, }, ); } /** * @description: 更新${pascalMainTableName} */ export async function update${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') { return defHttp.put( { url: Api.${pascalMainTableName}, params: ${camelCaseMainTableName}, }, { errorMessageMode: mode, }, ); } /** * @description: 删除${pascalMainTableName}(批量删除) */ export async function delete${pascalMainTableName}(ids: string[], mode: ErrorMessageMode = 'modal') { return defHttp.delete( { url: Api.${pascalMainTableName}, data: ids, }, { errorMessageMode: mode, }, ); } ${ hasSetUserIdButton ? ` /** * @description: 修改权限${pascalMainTableName} */ export async function setDataAuth${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') { return defHttp.put( { url: Api.DataAuth, params: ${camelCaseMainTableName}, }, { errorMessageMode: mode, }, ); } ` : '' } ${ hasExportButton ? ` /** * @description: 导出${pascalMainTableName} */ export async function export${pascalMainTableName}( params?: object, mode: ErrorMessageMode = 'modal' ) { return defHttp.download( { url: Api.Export, method: 'GET', params, responseType: 'blob', }, { errorMessageMode: mode, }, ); } ` : '' } `; return code; } /** * 构建类型代码 * @param model 配置 * @param tableInfo 后端数据库表信息 */ export function buildModelCode(model: GeneratorConfig, tableInfo: TableInfo[]): string { let mainTable; let childTables; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); childTables = model.tableConfigs?.filter((item) => !item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); childTables = model.tableStructureConfigs?.filter((item) => !item.isMain); mainTable.pkField = 'id'; } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCaseMainTableName); const code = ` import { BasicPageParams, BasicFetchResult } from '/@/api/model/baseModel'; ${ model.listConfig.queryConfigs.length > 0 ? ` /** * @description: ${pascalMainTableName}分页参数 模型 */ export interface ${pascalMainTableName}PageParams extends BasicPageParams { ${model.listConfig.queryConfigs .map((item) => { const table = tableInfo?.find((x) => x.isMain); //找到主表信息 const field = table?.fields.find((x) => x.name === item.fieldName); //找到当前字段信息 if (field?.type === ColumnType.DATE) { return ` ${camelCaseString(item.fieldName) + 'Start'}: string; ${camelCaseString(item.fieldName) + 'End'}: string;`; } else { return ` ${camelCaseString(item.fieldName)}: string;`; } }) .join('\n')} } ` : ` /** * @description: ${pascalMainTableName}分页参数 模型 */ export type ${pascalMainTableName}PageParams = BasicPageParams; ` } /** * @description: ${pascalMainTableName}分页返回值模型 */ export interface ${pascalMainTableName}PageModel { ${camelCaseString(mainTable.pkField) + ': string; \n'} ${model.listConfig.columnConfigs .map((item) => { if (item.columnName !== mainTable.pkField) { return ` ${camelCaseString(item.columnName)}: string;`; } }) .join('\n')} } ${ Array.isArray(tableInfo) && tableInfo.length && model.tableConfigs ?.map((item) => { const tableNameFirstUpperCase = upperFirst(camelCase(item.tableName)); //当前遍历的表信息 const thisTableInfo = tableInfo?.find((table) => table.name === item.tableName); const thisTableColumnInfo = thisTableInfo?.fields; // 如果是主表 默认需要加入子表的List字段 if (item.isMain) { return ` /** * @description: ${tableNameFirstUpperCase}表类型 */ export interface ${tableNameFirstUpperCase}Model { ${thisTableColumnInfo ?.map((column) => { return ` ${camelCaseString(column.name)}: ${column.type === ColumnType.NUMBER ? 'number' : 'string'};`; }) .join('\n')} ${ childTables && childTables .map((childTable) => { const childTablePascalName = upperFirst(camelCaseString(childTable.tableName)); return ` ${camelCaseString(childTable.tableName) + 'List?'} : ${childTablePascalName}Model;`; }) .join('\n') } } `; } else { return ` /** * @description: ${tableNameFirstUpperCase}表类型 */ export interface ${tableNameFirstUpperCase}Model { ${thisTableColumnInfo ?.map((column) => { return ` ${camelCaseString(column.name)}: ${column.type === ColumnType.NUMBER ? 'number' : 'string'};`; }) .join('\n')} } `; } }) .join('\n') } /** * @description: ${pascalMainTableName}分页返回值结构 */ export type ${pascalMainTableName}PageResult = BasicFetchResult<${pascalMainTableName}PageModel>; \n `; return formatCode(code); } /** * 构建列表页代码 * @param model 配置 */ export function buildListCode(model: GeneratorConfig): string { const className = model.outputConfig.className; const formType = model.formJson.config.formType; // const lowerClassName = lowerCase(className); const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; const pascalClassName = upperFirst(camelCase(className)); // //是否有左侧菜单 // const isMenu = model.listConfig.isLeftMenu; // //左侧占比 // const treeFlex = model.listConfig.leftMenuConfig?.leftWidth; let mainTable; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); mainTable.pkField = 'id'; } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName)); const componentArray = [] as string[]; model.listConfig.columnConfigs.map((config) => { componentArray.push(config.componentType!); }); let btnEvent = `{`; model.listConfig.buttonConfigs .filter((x) => x.isUse && x.isDefault) .forEach((x) => { btnEvent += `${x.code} : handle${upperFirst(x.code)},`; }); btnEvent += '}'; const hasFilterButton = model.listConfig.columnConfigs.some((item) => item.isFilter); const buttonConfigs = model.listConfig.buttonConfigs; buttonConfigs.map((item, index) => { if (item.code === 'delete') { //删除按钮放在最后 buttonConfigs.splice(index, 1); buttonConfigs.push(item); return; } }); const hasAddButton = hasButton(buttonConfigs, 'add'); const hasEditButton = hasButton(buttonConfigs, 'edit'); const hasRefreshButton = hasButton(buttonConfigs, 'refresh'); const hasViewButton = hasButton(buttonConfigs, 'view'); const hasBatchDeleteButton = hasButton(buttonConfigs, 'batchdelete'); const hasDeleteButton = hasButton(buttonConfigs, 'delete'); const hasImportButton = hasButton(buttonConfigs, 'import'); const hasExportButton = hasButton(buttonConfigs, 'export'); const hasSetUserIdButton = hasButton(buttonConfigs, 'batchSetUserId'); const hasStartWorkButton = hasButton(buttonConfigs, 'startwork'); const hasFlowRecordButton = hasButton(buttonConfigs, 'flowRecord'); const hasPrintButton = hasButton(buttonConfigs, 'print'); const hasCopyDataButton = hasButton(buttonConfigs, 'copyData'); const hasTemplatePrint = hasButton(buttonConfigs, PrintButton.CODE); const isSetDataAuth = model.outputConfig.isDataAuth; //判断是否有用到数据源数据字典的组件 const code = ` `; return code; } /** * 构建SimpleForm页面 * @param model * @returns {string} */ export function buildSimpleFormCode(model: GeneratorConfig, _tableInfo: TableInfo[]): string { const className = model.outputConfig.className; // const lowerClassName = lowerCase(className); const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; let mainTable; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); mainTable.pkField = 'id'; } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName)); const code = ` \n `; return code; } /** * 构建表单页面 * @param model * @returns {string} */ export function buildFormCode(model: GeneratorConfig, _tableInfo: TableInfo[]): string { const formType = model.formJson.config.formType; const formWidth = model.formJson.config.formWidth; const code = ` \n `; return code; } /** * 构建表单页面FormSchema 与 列表页面BasicColumn * @param model * @param formSchema */ export function buildConfigJsonCode(model: GeneratorConfig, formProps: FormProps): string { let mainTable; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); } const findUpload = (component) => { const hasSubComponent = ['tab', 'grid', 'card', 'form', 'one-for-one']; return component?.some((info) => { if (hasSubComponent.includes(info.type!)) { if (info.type === 'form') { return info.componentProps.columns?.some((childInfo) => { return childInfo.componentType === 'Upload'; }); } else if (info.type === 'one-for-one') { return info.componentProps.childSchemas?.some((childInfo) => { if (childInfo.children) { return childInfo.children?.some((childSubInfo) => { let hasUpload = childSubInfo.list.some((com) => com.type === 'upload'); if (hasUpload) return true; hasUpload = findUpload(childSubInfo.list); return hasUpload; }); } else { return childInfo.type === 'upload'; } }); } else { return info.children?.some((childInfo) => { let hasUpload = childInfo.list.some((com) => com.type === 'upload'); if (hasUpload) return true; hasUpload = findUpload(childInfo.list); return hasUpload; }); } } else if (info.type === 'table-layout') { return info.children?.some((childSubInfo) => { return childSubInfo.list.some((com) => { return findUpload(com.children); }); }); } else { return info.type === 'upload'; } }); }; if (!mainTable) { throw new Error('请设置主表'); } //将表名转为驼峰命名 首字母小写驼峰 //将表名转为帕斯卡命名 首字母大写的驼峰 const code = ` import { FormProps, FormSchema } from '/@/components/Form'; import { BasicColumn } from '/@/components/Table'; ${findUpload(formProps.schemas) ? `import { uploadApi } from '/@/api/sys/upload';` : ''} export const searchFormSchema: FormSchema[] = [ ${model.listConfig.queryConfigs .map((item) => { const schema = findSchema(formProps.schemas, camelCaseString(item.fieldName)); const [isNeedTrans, option] = whetherNeedToTransform(item, model.formJson.list); return handleSearchForm(option, schema, item, isNeedTrans); }) .join('\n')} ]; export const columns: BasicColumn[] = [ ${model.listConfig.columnConfigs .map((item) => { return ` { dataIndex: '${camelCaseString(item.columnName)}', title: '${item.label}', componentType:'${item.componentType}', ${item.alignType ? `align: '${item.alignType}',` : ''} ${item.isTotal ? 'total: true,' : ''} ${!item.autoWidth && item.columnWidth ? `width:${item.columnWidth},` : ''} ${ item.componentProps?.datasourceType === 'staticData' ? ` customRender: ({ record }) => { const staticOptions = ${JSON.stringify(item.componentProps?.staticOptions)}; return staticOptions.filter((x) => x.value === record.${camelCaseString( item.columnName, )})[0]?.label; },` : '' } ${ item.isFilter ? `onFilter: (value: string, record) => record.${camelCaseString( item.columnName, )} === value,` : '' } sorter: true, }, `; }) .join('\n')} ]; //表单事件 export const formEventConfigs = ${JSON.stringify(model.formEventConfig)}; export const formProps: FormProps = ${JSON.stringify(formProps, (key, value) => { if (key === 'api') { //TODO 后续新增API 这里也要修改 if (value.toString().includes('uploadApi')) { return `#{upload}#`; } else { return value; } } return value; })};\n `; return formatCode(code.replace(`"#{upload}#"`, 'uploadApi')); } /** * 构建工作流权限配置文件 * @param formProps */ export function buildWorkflowPermissionConfigJsonCode(formProps: FormProps | AppFormProps): string { const workFlowConfigJson = getWorkflowPermissionConfig(formProps.schemas); const code = ` export const permissionList = ${JSON.stringify(workFlowConfigJson)};\n `; return formatCode(code); } /** * 构建app 的api代码 * @param model 配置 * @param _tableInfo * @returns */ export function buildAppApiCode(model: GeneratorConfig): string { const className = model.outputConfig.className; const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; let mainTable; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); mainTable.pkField = 'id'; } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName)); const code = ` import { http } from '@/common/request/index.js'; // 局部引入 const api = { Page : '/${model.outputConfig.outputValue}/${lowerClassName}/page', List : '/${model.outputConfig.outputValue}/${lowerClassName}/list', Info : '/${model.outputConfig.outputValue}/${lowerClassName}/info', ${pascalMainTableName} : '/${model.outputConfig.outputValue}/${lowerClassName}' } /** * 根据参数 查询${pascalMainTableName}分页列表 * @param {Object} params - 查询参数 */ export const get${pascalMainTableName}Page = (params) => { return http.get(api.Page, { params }) } /** * 根据参数 查询${pascalMainTableName}列表 * @param {Object} params - 查询参数 */ export const get${pascalMainTableName}List = (params) => { return http.get(api.List, { params }) } /** * 获取${pascalMainTableName}信息 * @param {Object} params - id */ export const get${pascalMainTableName} = (id) => { return http.get(api.Info, { params: { id }, }) } /** * 新增${pascalMainTableName} * @param {Object} params - 表单数据 */ export const add${pascalMainTableName} = (formData) => { return http.post(api.${pascalMainTableName}, formData) } /** * 修改${pascalMainTableName} * @param {Object} params - 表单数据 */ export const update${pascalMainTableName} = (formData) => { return http.put(api.${pascalMainTableName}, formData) } /** * 删除${pascalMainTableName}(批量删除) * @param {Object} params - 表单数据 */ export const delete${pascalMainTableName} = (ids) => { return http.delete(api.${pascalMainTableName}, ids) } `; return code; } /** * 构建表单页面FormSchema 与 列表页面BasicColumn * @param model * @param formSchema */ export function buildAppConfigJsonCode( model: GeneratorConfig, formProps: AppFormProps, designType: string, ): string { const className = model.outputConfig.className; // const lowerClassName = lowerCase(className); const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; // const pascalClassName = upperFirst(camelCase(className)); let mainTable; if (designType == 'data') { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName)); //将表名转为驼峰命名 首字母小写驼峰 //将表名转为帕斯卡命名 首字母大写的驼峰 let categoryConfigs: any = ''; if (model.listConfig.isLeftMenu) { const { datasourceType, listFieldName, childIcon, parentIcon, menuName } = model.listConfig.leftMenuConfig!; categoryConfigs = { datasourceType: datasourceType, listFieldName: listFieldName ? camelCaseString(listFieldName) : '', childIcon: childIcon, parentIcon: parentIcon, menuName: menuName, }; if (datasourceType == 'dic') { categoryConfigs.dictionaryItemId = model.listConfig.leftMenuConfig?.dictionaryItemId; } else if (datasourceType == 'static') { categoryConfigs.staticData = model.listConfig.leftMenuConfig?.staticData; } else if (datasourceType == 'api') { categoryConfigs.apiConfig = setApiConfig(model.listConfig.leftMenuConfig?.apiConfig); } } const code = ` import { get${pascalMainTableName}Page, delete${pascalMainTableName} } from '@/common/api/${model.outputConfig.outputValue}/${lowerClassName}/index.js'; import { componentType, datasourceTypeEnum } from '@/components/simple-form/types/form.js' export const listProps = { rowKey:'${designType == 'data' ? camelCase(mainTable.pkField) : 'id'}', //列表请求接口 api: get${pascalMainTableName}Page, // 请求之前处理参数 (params) => {} beforeFetch: (params) => { for(let key in params){ if(key.includes(',')){ delete params[key] } } params.PK='${designType == 'data' ? camelCase(mainTable.pkField) : 'id'}' params.FormId='${model.formId}' return params }, // 自定义处理接口返回参数 afterFetch: (data) => { return data }, //数据源 静态 datasource: [], workflowConfig:{ Pk:'${designType == 'data' ? camelCase(mainTable.pkField) : 'id'}', Formid:'${model.formId}' }, //列配置 columnConfigs: [ ${model.listConfig.columnConfigs .map((item) => { return `{ title: '${item.label}', mainField:${item.mainField}, showLabel:${item.showLabel}, componentType:'${buildAppComponentType(item.componentType!)}', field: '${camelCaseString(item.columnName)}', }`; }) .join(',')} ], //是否启用搜索 isSearch: true, //是否分页 isPage: true, //分类筛选配置 categoryConfigs:${JSON.stringify(categoryConfigs)}, //搜索配置 searchConfigs: [${model.listConfig.queryConfigs .map((item) => { const schema = findAppSchema(formProps.schemas, camelCaseString(item.fieldName)); const [isNeedTrans, option] = whetherNeedToTransform(item, model.formJson.list); return handleAppSearchForm(option, schema, item, isNeedTrans); }) .join('\n')}], //表单页面地址 formUrl: '/pages/${model.outputConfig.outputValue}/${lowerClassName}/container', //列表页面地址 listUrl: '/pages/${model.outputConfig.outputValue}/${lowerClassName}/list', //按钮配置 otherButtons:[${model.listConfig.buttonConfigs .filter((item) => item.code !== 'edit' && item.code !== 'delete') .map((item) => { return ` { text: '${item.name}', isUse:${item.isUse}, code:'${item.code}', }`; }) .join(',')}], buttonConfigs: [${getButtonConfigs(model.listConfig.buttonConfigs, pascalMainTableName).join( ',', )}], formEventConfig:${JSON.stringify(getFormEvents(cloneDeep(model.formEventConfig)))} } export const formProps = ${JSON.stringify(formProps, (key, value) => { if (key === 'api') { //TODO 后续新增API 这里也要修改 if (value.toString().includes('uploadApi')) { return `#{upload}#`; } else { return value; } } return value; })};\n `; return code.replace(`"#{upload}#"`, 'uploadApi'); } function getFormEvents(formEvents) { for (const item in formEvents) { formEvents[item] = formEvents[item].filter( (x) => x.nodeInfo && x.nodeInfo.processEvent?.length > 0, ); } return formEvents; } function getButtonConfigs(buttonConfigs, pascalMainTableName) { const codes = ['refresh', 'view', 'add', 'edit', 'delete']; const buttons = buttonConfigs.filter((item) => item.isUse); const others = buttons.filter((item) => !codes.includes(item.code)); const temp: any[] = []; buttons.forEach((item) => { if (item.code === 'edit') { temp.push(`{ code: '${item.code}', icon: 'ant-design:edit-square', color:'#5E95FF', text: '${item.name}', action: (record) =>{ uni.navigateTo({ url: listProps.formUrl + '?type=edit&id=' + record[listProps.rowKey], }); } }`); } if (item.code === 'delete') { temp.push(`{ code: '${item.code}', icon: 'ant-design:delete-outlined', color:'#EF6969', text: '${item.name}', action: async (record, { reload }) => { await delete${pascalMainTableName} ([record[listProps.rowKey]]); reload() //请求删除接口 uni.showToast({ title: "删除成功" }) } }`); } }); if (others.length > 0) { temp.push(`{ code: 'more', icon: 'ant-design:lipsis-outlined', color: '#5E95FF', text: '更多', buttons: ${JSON.stringify(others)}, action: async (record, { showMoreButton }) => { showMoreButton(record[listProps.rowKey]) }, }`); } return temp; } /** * 构建app列表代码 * @param model */ export function buildAppListCode(_model: GeneratorConfig): string { const code = ` `; return code; } /** * 构建app表单页代码 * @param model * @param _tableInfo * @returns */ export function buildAppFormCode(model: GeneratorConfig): string { const className = model.outputConfig.className; // const lowerClassName = lowerCase(className); const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; // const pascalClassName = upperFirst(camelCase(className)); let mainTable; if (model.tableConfigs && model.tableConfigs.length) { //数据优先 mainTable = model.tableConfigs?.find((item) => item.isMain); } else { //界面优先、简易模板 mainTable = model.tableStructureConfigs?.find((item) => item.isMain); mainTable.pkField = 'id'; } if (!mainTable) { throw new Error('请设置主表'); } const mainTableName = mainTable?.tableName; //将表名转为驼峰命名 首字母小写驼峰 const camelCaseMainTableName = camelCase(mainTableName); //将表名转为帕斯卡命名 首字母大写的驼峰 const pascalMainTableName = upperFirst(camelCase(camelCaseMainTableName)); const code = ` `; return code; } // 构建表单菜单页容器页面 export function buildAppContainerCode(): string { return ` `; } // 生成tag export function buildTagStringCode(model: GeneratorConfig): string { const className = model.outputConfig.className; const lowerClassName = isOutputDirLowerName?(className?.toLowerCase()):className; return ` `; } /** * 当前搜索项 是否需要转换 * @param model 配置 */ export function whetherNeedToTransform( queryConfig: QueryConfig, components: ComponentOptionModel[], ): [boolean, ComponentConfigModel | undefined] { const layoutComponents = ['tab', 'grid', 'card']; let returnTransform: [boolean, ComponentConfigModel | undefined] = [false, undefined]; components?.some((info) => { if (layoutComponents.includes(info.type!)) { const hasComponent = info?.layout?.some((childInfo) => { const layoutChildOption = childInfo.list.find( (com) => com.bindField === queryConfig.fieldName, ); if (!!layoutChildOption) { returnTransform = transformComponent.includes(layoutChildOption.type) ? [true, layoutChildOption.options] : [false, undefined]; return true; } if (!childInfo.list.length) return false; const transformCom = whetherNeedToTransform(queryConfig, childInfo.list); if (!!transformCom[0]) { returnTransform = transformCom; return true; } return false; }); return hasComponent; } else if (info.type === 'table-layout') { let hasComponent = false; info?.layout?.map((childInfo) => { childInfo.list.map((child) => { const layoutChildOption = child.children?.find( (com) => com.bindField === queryConfig.fieldName, ); if (!!layoutChildOption) { returnTransform = transformComponent.includes(layoutChildOption.type) ? [true, layoutChildOption.options] : [false, undefined]; hasComponent = true; } if (!child.children?.length) hasComponent = false; const transformCom = whetherNeedToTransform(queryConfig, child.children!); if (!!transformCom[0]) { returnTransform = transformCom; hasComponent = true; } hasComponent = false; }); }); return hasComponent; } else { const option = components.find((item) => item?.bindField === queryConfig.fieldName); if (!!option) { returnTransform = transformComponent.includes(option.type) ? [true, option?.options] : [false, undefined]; } return !!option; } }); return returnTransform; } export function findSchema(schemaArr, fieldName) { let schema; const formListComponent = ['tab', 'grid', 'card']; schemaArr?.some((info) => { if (formListComponent.includes(info.type!)) { const hasComponent = info.children.some((childInfo) => { schema = childInfo.list.find((com) => com.field === fieldName); if (!!schema) return true; schema = findSchema(childInfo.list, fieldName); return !!schema; }); return !!hasComponent; } else if (info.type == 'table-layout') { const hasComponent = info.children.some((childInfo) => { return childInfo.list.some((child) => { schema = child.children.find((com) => com.field === fieldName); if (!!schema) return true; schema = findSchema(child.children, fieldName); return !!schema; }); }); return !!hasComponent; } else { schema = info.field === fieldName ? info : null; return !!schema; } }); return schema; } export function findAppSchema(schemaArr, fieldName) { let schema; const formListComponent = ['Tab', 'Segmented', 'Collapse', 'TableLayout']; schemaArr?.some((info) => { if (formListComponent.includes(info.component)) { const hasComponent = info.layout.some((childInfo) => { schema = childInfo.children.find((com) => com.field === fieldName); if (!!schema) return true; schema = findAppSchema(childInfo.children, fieldName); return !!schema; }); return !!hasComponent; } else { schema = info.field === fieldName ? info : null; return !!schema; } }); return schema; } const hasButton = (list, code) => { return list.filter((x) => x.code === code && x.isUse).length > 0; }; /** * 判断是否存在远程组件 使用 数据字典 * @param components 判断是否存在远程组件 使用 数据字典 * @param type dic datasource api * @returns */ // export function existRemoteComponent(components: ComponentOptionModel[], type: string): boolean { // const idx = components.findIndex( // (item) => transformComponent.includes(item.type) && item.options.datasourceType === type, // ); // if (idx > -1) { // return true; // } // const tabComponents = components.filter((item) => item.type === 'tab'); // if (tabComponents && tabComponents.length > 0) { // let layoutChildOption; // for (const tabComp of tabComponents) { // if (tabComp.layout) { // for (const ly of tabComp.layout) { // layoutChildOption = ly.list.find( // (item) => // transformComponent.includes(item.type) && item.options.datasourceType === type, // ); // break; // } // } // } // if (layoutChildOption && transformComponent.includes(layoutChildOption.type)) { // return true; // } else { // return false; // } // } // const gridComponents = components.filter((item) => item.type === 'grid'); // if (gridComponents && gridComponents.length > 0) { // let layoutChildOption; // for (const gridComp of gridComponents) { // if (gridComp.layout) { // for (const ly of gridComp.layout) { // layoutChildOption = ly.list.find( // (item) => // transformComponent.includes(item.type) && item.options.datasourceType === type, // ); // break; // } // } // } // if (layoutChildOption && transformComponent.includes(layoutChildOption.type)) { // return true; // } else { // return false; // } // } // return false; // } //需要转换为非输入框的组件 const transformComponent = [ 'number', 'radio', 'checkbox', 'select', 'cascader', 'associate-select', 'associate-popup', 'multiple-popup', 'area', 'switch', 'time', 'date', 'slider', 'rate', 'computational', 'money-chinese', 'info', 'organization', 'picker-color', 'user', ];