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, camelCaseOptionsField, setApiConfig } from './designHelper';
import { getWorkflowPermissionConfig } from '/@/hooks/web/useWorkFlowForm';
import { LIST_MODE } from '/@/enums/formViewEnum';
import { AssignmentTypeToRuleType } from '/@/api/ruleProcess/model';
import { BasicColumn } from '/@/components/Table/src/types/table';

/**
 * 构建代码
 * @param model 配置
 * @param tableInfo 后端数据库表信息
 */
export function buildCode(
  model: GeneratorConfig,
  tableInfo: TableInfo[],
  formProps: FormProps,
  designType?: string,
): FrontCodeModel {
  const frontCode: FrontCodeModel = {
    listCode: buildListCode(model, designType),
    formCode: buildFormCode(model, tableInfo, designType),
    apiCode: buildApiCode(model, tableInfo),
    modelCode: buildModelCode(model, tableInfo),
    configJsonCode: buildConfigJsonCode(model, formProps, designType),
    workflowPermissionCode: buildWorkflowPermissionConfigJsonCode(formProps), //工作流权限配置
    simpleFormCode: buildSimpleFormCode(model, tableInfo, designType), //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 = className?.toLowerCase();
  const pascalClassName = upperFirst(camelCaseString(className!, false));

  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 hasSubformList = getSubFormList(model.formJson.list);
  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',`
      : ''
  }
  ${
    hasSubformList
      ? `
  ListChildren = '/${model.outputConfig.outputValue}/${lowerClassName}/list-children'`
      : ''
  }
}

/**
 * @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<boolean>(
    {
      url: Api.${pascalMainTableName},
      params: ${camelCaseMainTableName},
    },
    {
      errorMessageMode: mode,
    },
  );
}

/**
 * @description: 更新${pascalMainTableName}
 */
export async function update${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') {
  return defHttp.put<boolean>(
    {
      url: Api.${pascalMainTableName},
      params: ${camelCaseMainTableName},
    },
    {
      errorMessageMode: mode,
    },
  );
}

/**
 * @description: 删除${pascalMainTableName}（批量删除）
 */
export async function delete${pascalMainTableName}(ids: string[], mode: ErrorMessageMode = 'modal') {
  return defHttp.delete<boolean>(
    {
      url: Api.${pascalMainTableName},
      data: ids,
    },
    {
      errorMessageMode: mode,
    },
  );
}

${
  hasSetUserIdButton
    ? `
/**
 * @description: 修改权限${pascalMainTableName}
 */
export async function setDataAuth${pascalMainTableName}(${camelCaseMainTableName}: Recordable, mode: ErrorMessageMode = 'modal') {
  return defHttp.put<boolean>(
    {
      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,
    },
  );
}
  `
    : ''
}
${
  hasSubformList
    ? `
/**
 * @description: 查询子表数据
 */
export async function getChildren${pascalMainTableName}(params: Recordable, mode: ErrorMessageMode = 'modal') {
  return defHttp.get(
    {
      url: Api.ListChildren,
      params,
    },
    {
      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, designType?: string): string {
  const className = model.outputConfig.className;
  const formType = model.formJson.config.formType;
  // const lowerClassName = lowerCase(className);
  const lowerClassName = className?.toLowerCase();
  const pascalClassName = upperFirst(camelCaseString(className!, false));
  const isNoTableModel = designType === 'notable';
  // //是否有左侧菜单
  // 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.code !== 'refresh' && (x.isDefault || (!x.isDefault && x.setting?.length)),
    )
    .forEach((x) => {
      btnEvent += `${x.code} : handle${upperFirst(x.code)},`;
    });

  btnEvent += '}';
  const hasSubformList = getSubFormList(model.formJson.list);
  const hasFilterButton = model.listConfig.columnConfigs.some((item) => item.isFilter);
  const rowSpanColumn = model.listConfig.columnConfigs.find((item) => item.rowSpan);
  const buttonConfigs = model.listConfig.buttonConfigs;
  buttonConfigs.map((item, index) => {
    if (item.code === 'delete') {
      //删除按钮放在最后
      buttonConfigs.splice(index, 1);
      buttonConfigs.push(item);
    }
    if (item.code === 'pushorder') {
      //推单按钮放在最后
      buttonConfigs.splice(index, 1);
      buttonConfigs.unshift(item);
    }
  });
  const executeButtons = buttonConfigs.filter((x) => !x.isDefault && x.setting?.length);
  const hasExecuteButton = executeButtons.length > 0;
  const hasTopExecuteButton = executeButtons.filter((x) => x.showType === 'top').length > 0;
  const hasAddButton = hasButton(buttonConfigs, 'add');
  const hasEditButton = hasButton(buttonConfigs, 'edit');
  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 hasPushOrderButton = hasButton(buttonConfigs, 'pushorder');
  const hasTemplatePrint = hasButton(buttonConfigs, PrintButton.CODE);
  const hasCustomBtn = buttonConfigs.some((x) => x.isDefault == false); //是否是自定义按钮
  const isSetDataAuth = model.outputConfig.isDataAuth;
  const isCardList = model.listConfig.listStyle === LIST_MODE.CARD;
  const isVerticalList = model.listConfig.listStyle === LIST_MODE.VERTICAL;
  const isHorizontalList = model.listConfig.listStyle === LIST_MODE.HORIZONTAL;
  let hasExecuteFieldParams = false;
  if (hasExecuteButton) {
    const executeButton = buttonConfigs.filter((x) => !x.isDefault && x.setting?.length);
    const hasFieldParams = executeButton.find((btn) => {
      return btn.setting.find((set) => {
        return set.operateConfig.apiConfig?.apiParams?.find((par) => {
          return par.tableInfo?.find(
            (info) => info.bindType === 'data' && info.value.includes('bindField'),
          );
        });
      });
    });
    hasExecuteFieldParams = !!hasFieldParams;
    if (!hasExecuteFieldParams) {
      const hasExcelFieldParams = executeButton.find((btn) => {
        return btn.setting.find((set) => {
          return set?.ruleConfig?.processParamConfigs.find((info) => {
            return info.assignmentType === AssignmentTypeToRuleType.FORM;
          });
        });
      });
      hasExecuteFieldParams = !!hasExcelFieldParams;
    }
  }
  const hasRowCheck =
    hasBatchDeleteButton ||
    hasTemplatePrint ||
    hasCustomBtn ||
    (hasSetUserIdButton && isSetDataAuth) ||
    (hasExecuteFieldParams && hasTopExecuteButton);
  const actionButtons = buttonConfigs
    .filter(
      (x) =>
        (['view', 'edit', 'copyData', 'delete', 'startwork', 'flowRecord', 'pushorder'].includes(
          x.code,
        ) ||
          (!x.isDefault && x.showType === 'inline')) &&
        x.isUse,
    )
    .map((x) => x.code);
  const getExecuteEvent = () => {
    let temp = '';
    executeButtons.forEach((btn) => {
      temp += `async function handle${upperFirst(btn.code)}(${
        btn.showType === 'inline' ? 'record' : ''
      }) {
      const executeButton = buttonConfigs.value.find((x) => x.code === '${btn.code}');
    ${
      btn.showType === 'top' ? 'let res=' : ''
    } executeEvent(executeButton?.setting, get${pascalMainTableName}${
        hasExecuteButton
          ? btn.showType === 'inline'
            ? ',[record.id],[record]'
            : ',selectedKeys.value,selectedRowsData.value'
          : ''
      });
      ${btn.showType === 'top' ? 'if(res)' : ''} setTimeout(() => {reload()}, 500);
    }
        `;
    });
    return temp;
  };
  //判断是否有用到数据源数据字典的组件
  const code = `
<template>
${
  isVerticalList
    ? `<div>
    <a-tabs v-if="!onlyShowAddForm"
      type="editable-card"
      hide-add
      class="mode-tabs"
      v-model:activeKey="modeActiveKey"
      :tabBarGutter="0"
      :tabBarStyle="{
        background: 'white',
        borderRadius: '16px',
        margin: '10px 0 0',
        border: '1px solid #EEE',
        height: '52px',
        padding:'0 16px',
      }"
      @edit="handleTabsEdit"
      @change="handleTabsClick"
    >
      <a-tab-pane
        v-for="item in modePanes"
        :key="item.key"
        :tab="item.title"
        :closable="item.closable"
      />
    </a-tabs>`
    : ''
}
${isHorizontalList ? `<div class="relative">` : ''}
<ResizePageWrapper ${
    isHorizontalList
      ? `class="w-1/2 mr-10px ${model.listConfig.isLeftMenu ? 'listmode-horizontal-tree' : ''}" ${
          model.listConfig.isLeftMenu
            ? `:class="leftTreeShow ? 'block' : ''" 
            :searchHeight="searchHeight"`
            : ''
        }`
      : ''
  } ${isVerticalList ? ':listPageMode="listPageMode"' : ''} ${
    model.listConfig.isLeftMenu ? ':hasLeft="true" :formLeftWidth="300"' : ':hasLeft="false"'
  }>
 ${
   model.listConfig.isLeftMenu
     ? `<template #resizeLeft>
 ${
   model?.listConfig?.leftMenuConfig!.length > 1
     ? `
      <a-tabs
        v-model:activeKey="leftMenuIndex"
        @change="leftTabChange"
        v-if="leftMenuConfig!.length > 1"
        class="left-menu-box"
      >
        <a-tab-pane
          :key="index"
          :tab="config.title || index + 1"
          v-for="(config, index) in leftMenuConfig"
        >
          <LeftTree
            :config="config"
            :treeData="treeData"
            @handleSelect="handleSelect"
            @handleSelectTree="handleSelectTree"
          />
        </a-tab-pane>
      </a-tabs>`
     : model?.listConfig?.leftMenuConfig![0]!.datasourceType === 'tree'
     ? `
        <TreeStructure :treeConfig="treeConfig" @select="handleSelectTree"/>
        `
     : `
        <BasicTree
          title="${model.listConfig.leftMenuConfig![0]!.menuName || ``}"
          toolbar
          search
          switcher
          :clickRowToExpand="true"
          :treeData="treeData"
          :fieldNames="{ key: '${
            model.listConfig.leftMenuConfig![0]!.datasourceType === 'static' ? `key` : `value`
          }', title: '${
         model.listConfig.leftMenuConfig![0]!.datasourceType === 'dic'
           ? `name`
           : model.listConfig.leftMenuConfig![0]!.datasourceType === 'api'
           ? `label`
           : model.listConfig.leftMenuConfig![0]!.showFieldName || `title`
       }' }"
          @select="handleSelect"
        >
          <template #title="item">
          ${
            model.listConfig.leftMenuConfig![0]!.parentIcon
              ? `<template v-if="item.renderIcon === 'parentIcon'">
                  <Icon icon="${model.listConfig.leftMenuConfig![0]!.parentIcon}" />
                </template>`
              : ''
          }
          ${
            model.listConfig.leftMenuConfig![0]!.childIcon
              ? `<template v-if="item.renderIcon === 'childIcon'">
                  <Icon icon="${model.listConfig.leftMenuConfig![0]!.childIcon}" />
                </template>`
              : ''
          }
            &nbsp;&nbsp;{{ ${
              model.listConfig.leftMenuConfig![0]!.datasourceType === 'dic'
                ? `item.name`
                : model.listConfig.leftMenuConfig![0]!.datasourceType === 'api'
                ? `item.label`
                : `item.${model.listConfig.leftMenuConfig![0]!.showFieldName || 'title'}`
            } }}
          </template>
        </BasicTree>
        `
 }
 </template>`
     : ``
 }
 
 <template #resizeRight>
<BasicTable @register="registerTable" isMenuTable ref="tableRef" ${
    model.listConfig.isLeftMenu && isHorizontalList ? `@tree-show-change="handleTreeChange"` : ''
  } ${
    hasRowCheck && !isCardList
      ? `:row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectChange }"`
      : ''
  }${hasSubformList ? ' @expand="expandedRowsChange" ' : ''}
  ${isCardList ? ' @columns-change="handleColumnChange" ' : ''} 
  ${isNoTableModel ? ' @redo="handleRedo" @change="handleTableChange"' : ''}>
       ${
         hasFilterButton
           ? `<template #customFilterIcon="{ filtered, column }" >
          <Icon icon="ant-design:filter-filled"  @click="handleFilterClick(column)" :class="filterClass(column,filtered)" :style="{ color: filtered ? '#108ee9' : undefined }"/>
        </template>`
           : ''
       }
        <template #toolbar>
          <template v-for="button in tableButtonConfig" :key="button.code">
            <a-button v-if="button.isDefault" type="primary" @click="buttonClick(button.code)">
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
            <CustomButtonModal v-else-if="button.buttonType == 'modal'" :info="button" />
            <a-button v-else :type="button.buttonType === 'danger' ? 'default' : button.buttonType || 'primary'" :danger="button.buttonType === 'danger'" ${
              hasExecuteButton && hasTopExecuteButton ? '@click="buttonClick(button.code)"' : ''
            }>
              <template #icon><Icon :icon="button.icon" /></template>
              {{ button.name }}
            </a-button>
          </template>
        </template>
        ${
          isCardList
            ? `
        <template #emptyText>
        ${
          hasRowCheck
            ? `<a-checkbox-group v-model:value="selectedKeys" class="data-list" v-if="datasource.length">`
            : `<div class="data-list" v-if="datasource.length">`
        }
              <div
                v-for="(data, idx) in datasource"
                :key="data.id"
                ${
                  hasRowCheck
                    ? `
                :class="[
                  'box-container',
                  selectedKeys.includes(data.id) ? 'selected-box' : 'unselected-box',
                ]"`
                    : `
                class="box-container unselected-box"`
                }
              >
                <div class="box-title">
                  <div>
                    <a-checkbox :value="data.id" class="!mr-1" v-if="hasListCheckbox"/>
                    <span class="text-black" v-if="isShowIndex">#{{ idx + 1 }}</span>
                  </div>
                  <div>
                    <a-tooltip v-for="(item, index) in getActions(data)" :key="index">
                      <template #title>{{ item.tooltip }} </template>
                      <Icon
                        :icon="item.icon"
                        v-auth="item.auth"
                        :class="['icon-box', item.color === 'error' ? 'icon-delete' : '']"
                        :style="{ height: '24px', width: '24px' }"
                        @click="item.onClick()"
                      />
                    </a-tooltip>
                    ${
                      hasPushOrderButton
                        ? `
                    <div class="btn-box" ref="pushBtnRef" v-if="isShowBtn && pushFormId === data.id">
                      <a-button
                        type="primary"
                        v-for="info in pushorderInfo!.setting.formInfo"
                        :key="info.formId"
                        @click="openPushorder(info)"
                      >
                        {{ info.formType === 0 ? info.functionName : info.formName }}
                      </a-button>
                    </div> `
                        : ''
                    }
                  </div>
                </div>
                <div class="flex-box">
                  <div 
                    v-for="(key, value, index) in getData(data)" 
                    :key="index" 
                    :class="\`flex-item text-\${ key.align || 'left' } \${ key.aRow ? '!basis-full' : '' }\`"
                  >
                    <div :class="['title', key.textBold ? 'font-bold' : '']">{{ value }}</div>
                    <div class="value">{{ key.value }}</div>
                  </div>
                </div>
              </div>
        ${hasRowCheck ? `</a-checkbox-group>` : `</div>`}
          <div v-else>
            <a-empty />
          </div>
        </template>`
            : `<template #bodyCell="{ column, record }">
          ${
            componentArray.includes('switch')
              ? `<template v-if="column.componentType === 'switch'">
                  <a-switch
                    v-model:checked="record[column.dataIndex]"
                    :unCheckedValue="0"
                    :checkedValue="1"
                    :disabled="true"
                  />
                </template>`
              : ''
          }
          ${
            componentArray.includes('picker-color')
              ? `<template v-if="column.componentType === 'picker-color'">
                  <ColorPicker
                    v-model:value="record[column.dataIndex]"
                    :disabled="true"
                  />
                </template>`
              : ''
          }
         ${
           componentArray.includes('labelComponent')
             ? `<template v-if="column.componentType === 'labelComponent'">
                  <XjrLabelComponentInfo
                   :value="record[column.dataIndex]"
                  :styleConfig="column.styleConfig"
                  />
                </template>`
             : ''
         }
          <template v-if="column.dataIndex === 'action'">
          ${
            hasPushOrderButton
              ? `
            <div class="btn-box" ref="pushBtnRef" v-if="isShowBtn && pushFormId === record.id">
              <a-button
                type="primary"
                v-for="item in pushorderInfo!.setting.formInfo"
                :key="item.formId"
                @click="openPushorder(item)"
              >
                {{ item.formType === 0 ? item.functionName : item.formName }}
              </a-button>
            </div>`
              : ''
          }
           <TableAction
              :actions="getLessActions(record)"
              :dropDownActions="getMoreActions(record)"
            />
          </template>
          ${
            componentArray.includes('money-chinese')
              ? ` <template v-else-if="column.componentType === 'money-chinese'">
                    <span :style="executeListStyle(record, column?.listStyle)">
                      {{ moneyChineseData(record[column.dataIndex]) }}
                    </span>
                  </template>`
              : ''
          }
          <template v-else-if="column.dataIndex && column?.listStyle">
            <span :style="executeListStyle(getValue(record, column, 'style'), column?.listStyle)">{{
              getValue(record, column, 'value')
            }}</span>
          </template>
        </template>
        ${
          hasSubformList
            ? `
        <template #expandedRowRender="{ record }">
          <a-table
            v-for="item in subFormList"
            :key="item.key"
            :columns="innerColumns[item.field]"
            :data-source="getInnerDataSource(record.id, item.field)"
            :pagination="false"
            :scroll="{ x: 'max-content' }"
          >
            <template #bodyCell="{ column, record: innerRecord }">
              <template v-if="column.componentType === 'picker-color'">
                <ColorPicker v-model:value="innerRecord[column.dataIndex]" :disabled="true" />
              </template>
                <template v-else-if="column.componentType === 'labelComponent'">
                  <XjrLabelComponentInfo
                    :value="innerRecord[column.dataIndex]"
                    :styleConfig="column.styleConfig"
                  />
                </template>
              <template v-else-if="column.componentType === 'money-chinese'">
                {{ moneyChineseData(innerRecord[column.dataIndex]) }}
              </template>
            </template>
          </a-table>
        </template>`
            : ''
        }
           `
        }
        
      </BasicTable>
 </template>
 
  ${
    hasStartWorkButton
      ? `
      <LookProcess
        v-if="visibleLookProcessRef"
        :taskId="taskIdRef"
        :processId="processIdRef"
        @close="visibleLookProcessRef = false"
        :visible="visibleLookProcessRef"
      />
      <LaunchProcess
        v-if="visibleLaunchProcessRef"
        :schemaId="schemaIdRef"
        :form-data="formDataRef"
        :form-id="formIdComputedRef"
        :rowKeyData="rowKeyData"
        :draftsId="draftsId"
        @close="handleCloseLaunch"
      />
      <ApprovalProcess
        v-if="visibleApproveProcessRef"
        :taskId="taskIdRef"
        :processId="processIdRef"
        :schemaId="schemaIdRef"
        @close="handleCloseApproval"
        :visible="visibleApproveProcessRef"
      />
      ${
        hasFlowRecordButton
          ? `<BasicModal
      v-if="visibleFlowRecordModal"
      :visible="visibleFlowRecordModal"
      :title="t('查看流转记录')"
      :paddingRight="15"
      :showOkBtn="false"
      :width="1200"
      @visible-change="
        (v) => {
          visibleFlowRecordModal = v;
        }
      "
      :bodyStyle="{ minHeight: '400px !important' }"
    >
      <FlowRecord :processId="processIdRef" />
    </BasicModal>`
          : ''
      }`
      : ''
  }
  ${
    hasTemplatePrint
      ? ` <PrintPreview
    v-if="printData.visible"
    :id="printData.id"
    :request-params-configs="printData.requestParamsConfigs"
    :request-body-configs="printData.requestBodyConfigs"
    :request-header-configs="printData.requestHeaderConfigs"
     @close="handleClosePrintPreview"
  />`
      : ''
  }
  ${
    formType === 'modal'
      ? ` <${pascalClassName}Modal @register="registerModal" @success="handleFormSuccess"   @cancel="handleFormCancel"/>`
      : ` <${pascalClassName}Drawer @register="registerDrawer" @success="handleFormSuccess"   @cancel="handleFormCancel"/>`
  }
  ${
    hasPushOrderButton
      ? `
    <PushOrderModal @register="registerPushModal" />`
      : ''
  }
  ${
    hasImportButton
      ? ` <ImportModal @register="registerImportModal" importUrl="/${model.outputConfig.outputValue}/${lowerClassName}/import" @success="handleImportSuccess"/>`
      : ''
  }
   ${
     hasExportButton && !isNoTableModel
       ? `<ExportModal
      v-if="visibleExport"
      @close="visibleExport = false"
      :columns="columns"
      @success="handleExportSuccess"
    />`
       : ''
   }
  ${
    hasSetUserIdButton && isSetDataAuth
      ? ` <SetRuleUserModal @register="registerRuleUserModal" @success="handleSuccess" />`
      : ''
  }
  ${
    isVerticalList
      ? `<div class="absolute z-1000 inset-0" v-show="(modeActiveKey !== 1 &&
            !(
              schemaInitConfig &&
              schemaInitConfig.enabled &&
              schemaInitConfig.enabledAddApprove
            )) || onlyShowAddForm" >
        <${pascalClassName}${formType === 'modal' ? 'Modal' : 'Drawer'}
          ref="FormNormalRef"
          @success="handleSuccess(false)"
          formType="normal"
          :onlyShowAddForm="onlyShowAddForm"
           :listPageMode="listPageMode"
           :isShowBtn="${model.listConfig.listStyleConfig?.isShowBtn}"
          @form-model-change="handleModelChange"
        />
      </div>`
      : ''
  }
</ResizePageWrapper>
${isVerticalList ? `</div>` : ''}
${
  isHorizontalList
    ? `<div class="form-horizontal-modal" style="height: calc(100vh - 149px)">
      <EmptyBox
        v-if="horizontalEmpty"
        :title="t('当前无相关数据')"
        :desc="t('请点击左侧${hasAddButton ? '新增或' : ''}编辑按钮来操作数据')"
      />
      <div class="h-full" v-show="!horizontalEmpty">
        <div class="form-horizontal-title">{{ horizontalTitle }}</div>
        <${pascalClassName}${formType === 'modal' ? 'Modal' : 'Drawer'}
          ref="FormNormalRef"
          @success="handleSuccess()"
          formType="normal"
           :listPageMode="listPageMode"
          :form-id="formIdComputedRef"
        />
      </div>
    </div>
  </div>`
    : ''
}
</template>
<script lang="ts" setup>
  import { ref, computed,provide,Ref,${isVerticalList ? 'unref,' : ''} ${
    model.listConfig.isLeftMenu || hasSubformList || isNoTableModel || hasStartWorkButton
      ? 'onMounted,'
      : ''
  }${
    hasBatchDeleteButton || hasDeleteButton || (hasSetUserIdButton && !isSetDataAuth)
      ? 'createVNode,'
      : ''
  }${
    model.listConfig.isLeftMenu &&
    model.listConfig.leftMenuConfig?.some((x) => x.datasourceType === 'api')
      ? 'getCurrentInstance,'
      : ''
  } 
${hasTemplatePrint ? ' reactive, ' : ''}${
    hasPushOrderButton || isVerticalList ? 'nextTick,' : ''
  }} from 'vue';
  ${
    hasDeleteButton ||
    hasBatchDeleteButton ||
    (hasSetUserIdButton && !isSetDataAuth) ||
    hasPushOrderButton
      ? `
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined${
    hasSetUserIdButton ? ', CloseCircleOutlined' : ''
  } } from '@ant-design/icons-vue';`
      : ''
  }
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  ${
    !isNoTableModel
      ? `import { get${pascalMainTableName}Page, delete${pascalMainTableName}${
          hasSetUserIdButton && isSetDataAuth ? `, setDataAuth${pascalMainTableName}` : ''
        }${hasExportButton ? `, export${pascalMainTableName}` : ''}${
          hasSubformList ? `, getChildren${pascalMainTableName}` : ''
        }${
          hasPushOrderButton || hasStartWorkButton || hasExecuteButton
            ? `, get${pascalMainTableName}`
            : ''
        }} from '/@/api/${model.outputConfig.outputValue}/${lowerClassName}';`
      : ''
  }
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
    import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  import { executeListStyle, getValue } from '/@/hooks/web/useListStyle';//列表样式配置
  import { useRouter } from 'vue-router';
  ${hasExecuteButton ? `import { executeEvent } from '/@/utils/event/data';` : ''}
  ${
    model?.listConfig?.isLeftMenu && model?.listConfig?.leftMenuConfig!.length > 1
      ? `
  import LeftTree from '/@/views/form/template/components/LeftTree.vue';
    `
      : ''
  }
  ${
    hasPrintButton
      ? `
  import printJS from 'print-js';`
      : ''
  }
  ${
    hasTemplatePrint
      ? `
		import { getPrintConfigInfo } from '/@/api/system/generator/print';
		import PrintPreview from '/@/views/generator/print/Preview.vue'; 
	  import { PrintButton } from '/@/enums/printEnum';
	  import { InputParamItem } from '/@/components/ApiConfig/src/interface';
    `
      : ''
  }
  ${
    formType === 'modal'
      ? `
  import { useModal${hasFlowRecordButton ? `,BasicModal` : ''} } from '/@/components/Modal';`
      : `
  import { useDrawer } from '/@/components/Drawer';`
  }
  ${
    (hasImportButton || (hasSetUserIdButton && isSetDataAuth) || hasFlowRecordButton) &&
    formType !== 'modal'
      ? `import { useModal${hasFlowRecordButton ? `,BasicModal` : ''} } from '/@/components/Modal';`
      : ''
  }
  ${
    hasStartWorkButton
      ? `
  import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
  import LaunchProcess from '/@/views/workflow/task/components/LaunchProcess.vue';
  import ApprovalProcess from '/@/views/workflow/task/components/ApprovalProcess.vue';
  import { getDraftInfo } from '/@/api/workflow/process';`
      : ''
  }
  ${
    formType === 'modal'
      ? `
  import ${pascalClassName}Modal from './components/${pascalClassName}Modal.vue';
  `
      : `
  import ${pascalClassName}Drawer from './components/${pascalClassName}Drawer.vue';//
  `
  }
  ${
    hasPushOrderButton
      ? `
  import PushOrderModal from '/@/views/form/template/components/PushOrderModal.vue';`
      : ''
  }
  ${
    hasSetUserIdButton && isSetDataAuth
      ? `
  import SetRuleUserModal from '/@/components/Designer/src/components/generateComponent/SetRuleUserModal.vue';`
      : ''
  }
  ${hasImportButton ? `import { ImportModal } from '/@/components/Import';` : ''}
  ${
    hasExportButton && !isNoTableModel
      ? `
  import { downloadByData } from '/@/utils/file/download';
  import ExportModal from '/@/views/form/template/components/ExportModal.vue';
    `
      : ''
  }
  ${
    componentArray.includes('picker-color') || hasSubformList
      ? `import { ColorPicker } from '/@/components/ColorPicker';`
      : ''
  }
  ${
    componentArray.includes('labelComponent') || hasSubformList
      ? `  import { XjrLabelComponentInfo } from '/@/components/LabelComponent';`
      : ''
  }
  import { searchFormSchema, ${
    model?.listConfig.isHeaderMerging ? 'headerMergingData' : 'columns'
  } ${hasSubformList ? ', formProps' : ''}${isNoTableModel ? ', apiConfig' : ''} ${
    model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig!.length > 1
      ? `, leftMenuConfig`
      : ''
  }} from './components/config';
  ${
    model.listConfig.leftMenuConfig!.length === 1 &&
    model.listConfig.leftMenuConfig![0].treeConfig?.id
      ? `import { treeConfig } from './components/config';  
         import {TreeStructure} from '/@/components/TreeStructure';`
      : ``
  }
  ${
    model.listConfig.buttonConfigs.filter((x) => x.isUse).length > 0 ||
    model.listConfig.leftMenuConfig?.some((x) => x.childIcon || x.parentIcon)
      ? `import Icon from '/@/components/Icon/index';`
      : ``
  }
  ${
    model.listConfig.isLeftMenu &&
    model.listConfig.leftMenuConfig?.some((x) => x.datasourceType === 'datasource')
      ? `import { listToTree } from '/@/utils/helper/treeHelper';`
      : ``
  } 
  ${model.listConfig.isLeftMenu ? `import { BasicTree, TreeItem } from '/@/components/Tree';` : ``} 
  ${
    model.listConfig.isLeftMenu &&
    model.listConfig.leftMenuConfig?.some((x) => x.datasourceType === 'dic')
      ? `import { getDicDetailList } from '/@/api/system/dic';`
      : ``
  }
  ${
    model.listConfig.isLeftMenu &&
    model.listConfig.leftMenuConfig?.some((x) => x.datasourceType === 'datasource')
      ? `import { getDatasourceData } from '/@/api/system/datasource';`
      : ``
  }
  ${
    (model.listConfig.isLeftMenu &&
      model.listConfig.leftMenuConfig?.some((x) => x.datasourceType === 'api')) ||
    hasPrintButton ||
    hasStartWorkButton ||
    hasPushOrderButton ||
    componentArray.includes('money-chinese') ||
    hasSubformList ||
    isNoTableModel
      ? `import { ${
          (model.listConfig.isLeftMenu &&
            model.listConfig.leftMenuConfig?.some((x) => x.datasourceType === 'api')) ||
          hasPushOrderButton ||
          isNoTableModel
            ? 'apiConfigFunc,'
            : ''
        }${hasPrintButton ? 'generateTableJson,' : ''}${hasStartWorkButton ? 'isValidJSON,' : ''}${
          componentArray.includes('money-chinese') || hasSubformList ? 'moneyChineseData,' : ''
        }${
          hasSubformList ||
          isNoTableModel ||
          (model.listConfig.isLeftMenu && model.listConfig.leftMenuConfig!.length > 1)
            ? 'camelCaseString,'
            : ''
        } } from '/@/utils/event/design';`
      : ``
  }
  ${
    hasFlowRecordButton
      ? `import FlowRecord from '/@/views/workflow/task/components/flow/FlowRecord.vue';`
      : ''
  }
  ${
    hasSubformList
      ? `
  import { FormSchema } from '/@/components/Form/src/types/form';`
      : ''
  }
  ${
    isNoTableModel
      ? `
  import XLSX from 'xlsx-js-style';`
      : ''
  }

  ${
    isHorizontalList
      ? `import EmptyBox from '/@/views/workflow/task/components/flow/EmptyBox.vue';`
      : ''
  }
   const listSpliceNum = ref(3); //操作列最先展示几个
   ${
     isVerticalList || isHorizontalList
       ? `  
    import { LIST_MODE } from '/@/enums/formViewEnum'; `
       : ''
   }
  ${
    isVerticalList
      ? `   
      import { baseHandler } from '/@/layouts/default/setting/handler';
  import { HandlerEnum } from '/@/layouts/default/setting/enum';
  import { cloneDeep } from 'lodash-es';`
      : ''
  }
  ${hasStartWorkButton ? ` import {getFormSchemaId } from '/@/api/form/design'; ` : ''}


 
  import { useConcurrentLock } from '/@/hooks/web/useConcurrentLock';

  ${
    isNoTableModel
      ? `
    const listApiConfig = ${JSON.stringify(model.listConfig.apiConfig)};
    const dataSource = ref<any[]>([]);`
      : 'const pageParamsInfo = ref<any>({});'
  }
  const { enableLockeData,handleOpenFormEnableLockeData, handleCloseFormEnableLocke, handleHasEnableLocke } =
    useConcurrentLock();
${
  isHorizontalList
    ? `  const listPageMode = ref<string>(LIST_MODE.HORIZONTAL);
    const horizontalTitle = ref('新增');
  const horizontalEmpty = ref(true);
  const FormNormalRef = ref();  ${
    model.listConfig.isLeftMenu ? '  const leftTreeShow = ref(false);' : ''
  }`
    : ''
}
  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);
  const { ${
    model?.listConfig.isHeaderMerging ? 'filterHeaderColumnAuth' : 'filterColumnAuth'
  }, filterButtonAuth, hasPermission } = usePermission();
${
  isVerticalList
    ? `  const listPageMode = ref<string>(LIST_MODE.VERTICAL);
  const modeActiveKey = ref(1);
  const FormNormalRef = ref();
  const tabChangeIsReload = ref(false);

  const modePanes = ref<{ title: string; content?: any; key: number; closable?: boolean }[]>([
${
  hasAddButton
    ? `{
      key: 0,
      title: '新增',
      closable: false,
      content: {
        isUpdate: false,
        formModal: {},
      },
    },`
    : ''
}
    {
      key: 1,
      title: '列表页',
      closable: false,
    },
  ]);`
    : ''
}
  const filterColumns = ${
    model?.listConfig.isHeaderMerging ? 'filterHeaderColumnAuth' : 'filterColumnAuth'
  }(${model?.listConfig.isHeaderMerging ? 'headerMergingData' : 'columns'});
  const tableRef = ref();
  ${
    model?.listConfig?.isLeftMenu && model?.listConfig?.leftMenuConfig!.length > 1
      ? `const leftMenuIndex = ref(0);
  const treeMenuSeleceted = ref({});
      `
      : ''
  }

  ${
    hasSubformList
      ? ` const innerColumns = ref({});
  const innerDataSource = ref({});
  const subFormList = ref<any[]>([]);`
      : ''
  }
  ${hasExportButton && !isNoTableModel ? `const visibleExport = ref(false);` : ''}

  ${
    hasFilterButton
      ? `const isShowFilter = ref(false)
  const showColumnIndex = ref<string>('')
  const clickColumnIndex = ref<string>('')
  const filterClass = (column,filtered) => {
    return (isShowFilter.value && column.dataIndex === showColumnIndex.value) || column.dataIndex === clickColumnIndex.value || filtered ? 'show' : 'hide'
  }`
      : ''
  }
  //展示在列表内的按钮
  const actionButtons = ref<string[]>(${JSON.stringify(actionButtons)});
  const buttonConfigs = computed(()=>{
    const list = ${JSON.stringify(model.listConfig.buttonConfigs.filter((x) => x.isUse))}
    return filterButtonAuth(list);
  })

  const tableButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => !actionButtons.value.includes(x.code));
  });

  const actionButtonConfig = computed(() => {
    return buttonConfigs.value?.filter((x) => actionButtons.value.includes(x.code));
  });

  const btnEvent = ${btnEvent}

  ${
    hasPushOrderButton
      ? `
  const pushFormId = ref();
  const pushBtnRef = ref(); 
  const pushbtnleft = ref(); 
  const isShowBtn = ref(false);
  const pushorderInfo = buttonConfigs.value.find((x) => x.code === 'pushorder');`
      : ''
  }
  const { currentRoute } = useRouter();
  ${
    isVerticalList
      ? `const { query } = unref(currentRoute);
      const onlyShowAddForm = computed(() => {
    if (query.onlyShowAddForm) {
      baseHandler(HandlerEnum.FULL_CONTENT, true);
      nextTick(() => {
        handleAdd();
      });
      return true;
    } else {
      return ${model.listConfig.listStyleConfig?.onlyShowForm ? true : false};
    }
  });`
      : ''
  }
  ${
    hasTemplatePrint
      ? `const printMenuId = computed(() => currentRoute.value.meta.menuId as string);`
      : ''
  }
  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);
  provide<Ref<string>>('currentFormId', formIdComputedRef);
  ${
    hasStartWorkButton
      ? `
  const visibleLookProcessRef = ref(false);
  const processIdRef = ref('');

  const visibleLaunchProcessRef = ref(false);
  const schemaIdRef = ref('');
  const formDataRef = ref();
  const rowKeyData = ref();
  const draftsId = ref();

  const visibleApproveProcessRef = ref(false);
  const taskIdRef = ref('');


  
  ${hasFlowRecordButton ? `const visibleFlowRecordModal = ref(false);` : ''}
  `
      : ''
  }
  ${model.listConfig.isLeftMenu ? `const selectId = ref('');` : ``} 
  ${model.listConfig.isLeftMenu ? `const treeData = ref<TreeItem[]>([]);` : ``} 
  ${
    hasRowCheck
      ? `
  const selectedKeys = ref<string[]>([]);
  const selectedRowsData = ref<any[]>([]);`
      : ''
  }
  ${
    isCardList
      ? `
    const datasource = ref<any>([]);
    const listDataSource = ref<any>([]);
    const isShowIndex = ref(true);
    const hasListCheckbox = ref(${hasRowCheck})`
      : ''
  }
   ${
     hasStartWorkButton
       ? `
      const schemaInitConfig = ref();
      onMounted(async () => {
       // 获取发起审批按钮配置信息
        let startWorkArr = buttonConfigs.value?.find((x) => x.code === 'startwork');
        if (startWorkArr) {
          schemaInitConfig.value = startWorkArr.schemaInitConfig;
          if (
            schemaInitConfig.value &&
            schemaInitConfig.value.config &&
            schemaInitConfig.value.config.id
          ) {
            let schemeId = await getFormSchemaId(schemaInitConfig.value.config.id);
            if (schemeId) schemaIdRef.value = schemeId;
          }
        }
    });
      `
       : ''
   }
  ${
    hasSetUserIdButton && isSetDataAuth
      ? `const [registerRuleUserModal, { openModal: openRuleUserModal }] = useModal();`
      : ''
  }
  ${
    formType === 'modal'
      ? `const [registerModal, { openModal }] = useModal();`
      : `const [registerDrawer, { openDrawer }] = useDrawer();`
  }
  ${
    hasPushOrderButton
      ? `const [registerPushModal, { openModal: openPushModal }] = useModal();`
      : ''
  }
  ${
    hasImportButton
      ? `const [registerImportModal, { openModal: openImportModal }] = useModal();`
      : ''
  }
  ${
    hasTemplatePrint
      ? `
    // 模板打印 入参参数
    let printData: {
      visible:boolean;
      id: string;
      code:string;
      requestParamsConfigs: Array<InputParamItem>;
      requestHeaderConfigs: Array<InputParamItem>;
      requestBodyConfigs: Array<InputParamItem>;
    
    } = reactive({
      visible:false,
      id: '',
      code:'',
      requestParamsConfigs: [],
      requestHeaderConfigs: [],
      requestBodyConfigs: [],
    });
    `
      : ''
  } 
  ${
    isNoTableModel
      ? `const getDataSource = async (value, pagination?) => {
      setLoading(true);
    let page = { total: 0, ...pagination };
    dataSource.value = await apiConfigFunc(listApiConfig, true, value, null, page);
    if (dataSource.value && !Array.isArray(dataSource.value)) {
      dataSource.value = [];
      return;
    }
    const listConfig = apiConfig.find((item) => item.value === 'view')?.outputConfig;
    dataSource.value?.map((item) => {
      for (let key in item) {
        listConfig?.forEach((config) => {
          if (config.apiField === key) {
            item[camelCaseString(config.bindField)!] = item[key];
          }
        });
      }
    });
    setProps({ dataSource: dataSource.value , pagination: { total: Number(page.total || 0) }});
    setLoading(false);
  };
  function handleTableChange(page) {
    let value = getForm().getFieldsValue();
    getDataSource(value, page);
  }
  onMounted(async () => {
    getDataSource(getForm().getFieldsValue());
  });`
      : ''
  } 
  const [registerTable, { ${!isNoTableModel ? `reload,` : 'getForm, setProps,setLoading '} ${
    hasFilterButton || rowSpanColumn ? 'setColumns,' : ''
  } ${hasPrintButton && !isNoTableModel ? 'getRawDataSource,' : ''} }] = useTable({
    title: '${model.listConfig?.listTitle || pascalClassName + '列表'}',
    ${
      !isNoTableModel
        ? `api: get${pascalMainTableName}Page,`
        : `handleSearchInfoFn(info) {
      getDataSource(info);
    },`
    }
    rowKey: '${camelCaseString(mainTable.pkField)}',
    columns: filterColumns,
    pagination: {
      pageSize: ${model.listConfig.pageSize ? model.listConfig.pageSize : 10},
    },
    formConfig: {
      labelWidth: 100,
      schemas: searchFormSchema,
      fieldMapToTime: [${
        model.listConfig.queryConfigs
          .filter((item) => {
            return !!item.isDate;
          })
          .map(
            (item) =>
              `['${camelCaseString(item.fieldName)}', ['${
                camelCaseString(item.fieldName) + 'Start'
              }', '${camelCaseString(item.fieldName) + 'End'}'], '${
                item.format || 'YYYY-MM-DD HH:mm:ss'
              } ', true],`,
          )
          .join('\n')
        // 案例数据 ['fieldDatetime', ['fieldDatetimeStart', 'fieldDatetimeEnd'], 'YYYY-MM-DD HH:mm:ss', isString],
      }],
      showResetButton: false,
    },
    ${
      !isNoTableModel
        ? ` bordered:${model.listConfig.isHeaderMerging ? 'true' : 'false'},
          beforeFetch: (params) => {
      pageParamsInfo.value = {...params, FormId: formIdComputedRef.value,PK: '${camelCaseString(
        mainTable.pkField,
      )}' }
      return pageParamsInfo.value;
    },
    afterFetch: (res) => {
      ${
        hasFilterButton
          ? `filterColumns.map((column: any) => {
        if (column.onFilter) {
          const info = res.map((item) => item[column.dataIndex!])
          column.filters = [...new Set(info)].map(item => {
            return {
              text: item,
              value: item
            }
          })
          column.customHeaderCell = () => {
              return {
                onmouseenter: () => {
                  isShowFilter.value = true
                  showColumnIndex.value = column.dataIndex
                  clickColumnIndex.value = ''
                }, 
                onmouseleave: () => {
                  isShowFilter.value = false
                  showColumnIndex.value = ''  
                }       
              };
            }
          }
        
      });
      `
          : ''
      }
      ${
        rowSpanColumn
          ? `//处理列表页行合并
      let colName='${camelCaseString(rowSpanColumn.columnName)}';
      let curI = 0;
      let cur = res[curI][colName];
      let arr: number[] = [];
      res.forEach((o, i) => {
        arr.push(1);
        if (i >= 1) {
          if (o[colName] == cur) {
            arr[curI] += 1;
            arr[i] = 0;
          } else {
            curI = i;
            cur = res[curI][colName];
          }
        }
      });
      filterColumns.forEach(item=>{
        if(item.dataIndex==colName){
          item.customCell = (_, index) => {
            let obj = { rowSpan: 1 };
            arr.forEach((o, i) => {
              if (index == i) {
                obj = { rowSpan: o };
              }
            });
            return obj;
          };
        }
      }) 
      `
          : ''
      }
       ${hasFilterButton || rowSpanColumn ? `setColumns(filterColumns);` : ''}
      ${
        hasBatchDeleteButton ||
        hasTemplatePrint ||
        hasCustomBtn ||
        (hasSetUserIdButton && isSetDataAuth)
          ? `
      selectedKeys.value = [];
      selectedRowsData.value = [];`
          : ''
      }
      ${
        isCardList
          ? `
      listDataSource.value = res;
      getDataList(res);
      return [];`
          : ''
      }
    },`
        : ''
    }
    useSearchForm: ${model.listConfig.queryConfigs.length > 0 ? 'true' : 'false'},
    showTableSetting: true,
    ${
      isHorizontalList
        ? `listPageMode: LIST_MODE.HORIZONTAL, ${
            model.listConfig.isLeftMenu ? `hasLeftTree: true, leftTreeShow,` : ``
          }`
        : ''
    }
    ${
      hasFilterButton
        ? `isFilterByDataSoure: true,
      notUseFilterValueSearch: true,`
        : ''
    }
    ${
      isCardList
        ? `
    pagination: {
      pageSizeOptions: ['9', '12', '15', '18'],
      pageSize: 9,
    },`
        : `
    striped: false,
    actionColumn: {
      width: ${
        (actionButtons.length > 3 ? 3 : actionButtons.length) * (hasStartWorkButton ? 130 : 65)
      },
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },`
    }
    tableSetting: {
      size: false,
    },
    customRow,
    isAdvancedQuery:  ${model.listConfig.isAdvancedQuery ? true : false},
    querySelectOption: JSON.stringify(searchFormSchema),
    objectId: formIdComputedRef.value, ////系统表单formId,自定义表单releaseId的id值
  });
${
  hasSubformList
    ? `
   const getSubFormList = (list) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.children!) {
          getSubFormList(child.list);
        }
      } else if (item.type == 'table-layout') {
        for (const child of item.children!) {
          for (const sub of child.list) {
            getSubFormList(sub.children);
          }
        }
      } else if (item.type === 'form') {
        if (item.componentProps.isListView) {
          subFormList.value.push(item);
          innerColumns.value[item.field] = (item.componentProps! as FormSchema)
            .viewList!.filter((sub) => sub.checked)
            .map((sub) => {
              return {
                title: sub.label,
                dataIndex: camelCaseString(sub.field),
                componentType: sub.componentType,
              };
            });
        }
      }
    });
  };`
    : ''
}
  ${
    model.listConfig.isLeftMenu || hasSubformList
      ? `
  
  onMounted(() => {
  ${model.listConfig.isLeftMenu ? 'fetch();' : ''}
  ${hasSubformList ? `getSubFormList(formProps.schemas);` : ''}
    });`
      : ''
  }
  ${
    isCardList
      ? `
  function handleColumnChange(data, checkIndex, checkSelect) {
    isShowIndex.value = checkIndex;
    hasListCheckbox.value = checkSelect;
    const showColumns = data.filter((x) => x.visible).map((x) => x.dataIndex);
    const columns = filterColumns.filter((x) => showColumns.includes(x.dataIndex));
    getDataList(listDataSource.value, columns);
  }
  function getDataList(data, columns?) {
    datasource.value = [];
    if (data?.length) {
      data.forEach((item) => {
        let listData = {
          id: item.id,
          workflowData: item.workflowData,
        };
        for (let key in item) {
          const col = columns || filterColumns;
          col.forEach((col) => {
            if (col.dataIndex === key) {
              let value = item[key];
              ${
                componentArray.includes('money-chinese')
                  ? `
              if (col.componentType === 'money-chinese') {
                value = moneyChineseData(value);
              }`
                  : ''
              }
              listData[col.title as string] = {
                value,
                align: col.align,
                aRow: col.aRow,
                textBold: col.textBold,
              };
            }
          });
        }
        datasource.value.push(listData);
      });
    }
  }
  function getData(data) {
    let dataObj: any = {};
    for (let key in data) {
      if (key !== 'id' && key !== 'workflowData' && key !== 'isCanEdit') {
        dataObj[key] = data[key];
      }
    }
    return dataObj;
  }`
      : ''
  }
${
  isVerticalList
    ? ` async function handleTabsClick(val) {
${
  hasAddButton
    ? `if (val === 0) {
        handleAdd();
      } else`
    : ''
} if (val === 1) {
        if (tabChangeIsReload.value) reload();
        tabChangeIsReload.value = false;
      } else if (val > 1) {
       let idx = ${hasAddButton ? ' val ' : 'val - 1'};
        if (modePanes.value[idx]) { 
          FormNormalRef.value.handleInner(modePanes.value[idx].content); 
        }
      }
    } 
 
   function handleModelChange(val) {
    if (modeActiveKey.value !== 1) {
      modePanes.value[modeActiveKey.value${
        hasAddButton ? '' : '- 1'
      }].content.formModal = cloneDeep(val);
    }
  }`
    : ''
}
  function buttonClick(code) {
    ${
      hasTemplatePrint
        ? `if (code.includes(PrintButton.CODE)) {
      printData.code = code;
    }`
        : ''
    }
    btnEvent[code]();
  }
    ${
      isHorizontalList && model.listConfig.isLeftMenu
        ? `  const searchHeight = ref(0);
  function handleTreeChange(val, headerHeight) {
    searchHeight.value = headerHeight; 
    leftTreeShow.value = val;
  }`
        : ''
    }
  ${
    hasAddButton
      ? `
  function handleAdd() {
  ${
    hasStartWorkButton
      ? ` 
   // 发起审批按钮的配置中 启用并新增即审批 打开发起流程
    if (
      schemaInitConfig.value &&
      schemaInitConfig.value.enabled &&
      schemaInitConfig.value.enabledAddApprove
    ) {
      visibleLaunchProcessRef.value = true;
    } else {
  `
      : ''
  }
 
      ${
        isVerticalList
          ? `modeActiveKey.value = 0;
    FormNormalRef.value.handleInner({
      isUpdate: false,
      formModal: modePanes.value[0].content.formModal, 
    });`
          : isHorizontalList
          ? `horizontalTitle.value = '新增';
    horizontalEmpty.value = false;
    FormNormalRef.value.handleInner({
      isUpdate: false,
    });`
          : `${
              formType === 'modal'
                ? `openModal(true, { isUpdate: false, });`
                : `openDrawer(true, { isUpdate: false, });`
            }
`
      } 
      ${
        hasStartWorkButton
          ? ` }
    }`
          : '}'
      }
      `
      : ''
  }
  ${
    hasEditButton
      ? `
  async function handleEdit(record: Recordable) {
    let field = '${camelCaseString(mainTable.pkField)}';
  try {
      let hasIn = handleHasEnableLocke(buttonConfigs.value, 'edit');
      if (hasIn) { 
        let res = await handleOpenFormEnableLockeData(
          record[field],
          formIdComputedRef.value,
        );
        if (res !== null) {
          return;
        }
      } 
    ${isVerticalList ? `await FormNormalRef.value.handleReset();` : ''}
    let info = {
      id: record[field],
      ${isNoTableModel ? 'record,' : ''}
      isUpdate: true,
      ${isVerticalList ? `formModal: {},` : ''}
    };
    ${
      isVerticalList
        ? `
      if (filterColumns.length > 0) field = filterColumns[0].dataIndex as string;
      modeActiveKey.value = modePanes.value.length${hasAddButton ? '' : `+1`};
      let idx = modePanes.value.findIndex((o) => {
        return o.content?.id == record.${camelCaseString(mainTable.pkField)};
      });
      if (idx >= 0) {
        modeActiveKey.value = idx${hasAddButton ? '' : `+1`};
        if (modePanes.value[idx]) info.formModal = modePanes.value[idx].content.formModal;
        modePanes.value.splice(idx, 1, {
          key: modeActiveKey.value,
          title: record[field],
          closable: true,
          content: info,
        });
      } else {
        if (modePanes.value[modeActiveKey.value])
          info.formModal = modePanes.value[modeActiveKey.value].content.formModal;
        modePanes.value.push({
          key: modeActiveKey.value,
          title: record[field],
          closable: true,
          content: info,
        });
      }

      FormNormalRef.value.handleInner(info);`
        : isHorizontalList
        ? `horizontalTitle.value = '编辑';
    horizontalEmpty.value = false;
    FormNormalRef.value.handleInner(info);`
        : `${
            formType === 'modal'
              ? `
    openModal(true, info);`
              : ` 
    openDrawer(true, info);`
          }`
    }
      } catch (error) {} 
  }`
      : ''
  }
  ${
    hasCopyDataButton
      ? `
  function handleCopyData(record: Recordable) {
    ${
      formType === 'modal'
        ? `
    openModal(true, {
    ${isNoTableModel ? `record,` : `id: record.${camelCaseString(mainTable.pkField)},`}
      isCopy: true,
    });`
        : ` 
    openDrawer(true, {
    ${isNoTableModel ? `record,` : `id: record.${camelCaseString(mainTable.pkField)},`}
      isCopy: true,
    });`
    }
  }`
      : ''
  }
   ${
     hasPushOrderButton
       ? `
  async function handlePushorder(record) {
    if (pushorderInfo?.setting.type === 'form') {
      pushFormId.value = record.id;
      isShowBtn.value = !isShowBtn.value;
      if (isShowBtn.value) {
        nextTick(() => {
          pushbtnleft.value = \`-\${pushBtnRef.value?.offsetWidth}px\`;
        });
      }
    } else {
      Modal.confirm({
        title: '提示信息',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确定需要推单吗？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          try {
            apiConfigFunc(pushorderInfo?.setting.apiConfig, true, record).then(() => {
              notification.success({
                message: 'Tip',
                description: '执行成功',
              });
            });
          } catch (error) {}
        },
      });
    }
  }
  async function openPushorder(record) {
    isShowBtn.value = false;
    ${
      isNoTableModel
        ? `const viewConfig = apiConfig.find((item) => item.value === 'view');
    const rowInfo = await apiConfigFunc(viewConfig, true, selectedRowsData.value[0]);
    const listConfig = apiConfig.find((item) => item.value === 'view')?.outputConfig;
    for (let key in rowInfo) {
      listConfig?.forEach((config) => {
        if (config.apiField === key) {
          rowInfo[camelCaseString(config.bindField!)!] = rowInfo[key];
        }
      });
    }`
        : `const rowInfo = await get${pascalMainTableName}(pushFormId.value); `
    }
    openPushModal(true, {
      info: record,
      rowInfo,
    });
  }`
       : ''
   }
  ${
    hasDeleteButton || hasBatchDeleteButton
      ? `
    ${
      hasDeleteButton
        ? `
  function handleDelete(record: Recordable) {
  ${
    isNoTableModel
      ? `Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        const deleteConfig = apiConfig.find((item) => item.value === 'delete');
        try {
          await apiConfigFunc(deleteConfig, true, record);
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
          getDataSource(getForm().getFieldsValue());
        } catch (error) {
          notification.error({
            message: 'Tip',
            description: t('删除失败！'),
          });
        }
      },
      onCancel() {},
    });`
      : `deleteList([record.${camelCaseString(mainTable.pkField)}]);`
  }
  }`
        : ''
    }
    ${
      hasBatchDeleteButton
        ? `
  function handleBatchdelete() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: 'Tip',
        description: t('请选择需要删除的数据'),
      });
      return;
    }
    ${
      isCardList
        ? `
    selectedRowsData.value = datasource.value.filter((x) => selectedKeys.value.includes(x.id));`
        : ''
    }
    //与工作流相关的数据不能进行批量删除
    const cantDelete = selectedRowsData.value.filter((x) => {
      return (
        (x.workflowData?.enabled && x.workflowData?.status) ||
        (!x.workflowData?.enabled && !!x.workflowData?.processId)
      );
    });
    if (cantDelete.length) {
      notification.warning({
        message: 'Tip',
        description: t('含有不能删除的数据'),
      });
      return;
    }
  ${
    isNoTableModel
      ? `Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        const batchdeleteConfig = buttonConfigs.value.find(
          (item) => item.code === 'batchdelete',
        )?.apiConfig;
        try {
          await apiConfigFunc(batchdeleteConfig, true, selectedRowsData.value);
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
          getDataSource(getForm().getFieldsValue());
        } catch (error) {
          notification.error({
            message: 'Tip',
            description: t('删除失败！'),
          });
        }
      },
      onCancel() {},
    });`
      : 'deleteList(selectedKeys.value);'
  }
  }`
        : ''
    }
  ${
    !isNoTableModel
      ? `function deleteList(ids) {
    Modal.confirm({
      title: '提示信息',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        delete${pascalMainTableName}(ids).then((_) => {
          handleSuccess();
          notification.success({
            message: 'Tip',
            description: t('删除成功！'),
          });
        });
      },
      onCancel() {},
    });
  }`
      : ''
  }`
      : ''
  }
  ${
    model.listConfig.leftMenuConfig!.length > 1
      ? `
  async function leftTabChange() {
    await fetch();
    const value = treeMenuSeleceted.value[leftMenuIndex.value];
    if (!value) {
      reload();
    } else if (leftMenuConfig![leftMenuIndex.value].datasourceType === 'tree') {
      handleSelectTree(value);
    } else {
      handleSelect(value);
    }
  }`
      : ''
  }
  ${
    hasPrintButton
      ? `
  async function handlePrint() {
  ${
    !isNoTableModel
      ? ` const dataSource = Array.isArray(getRawDataSource())
      ? getRawDataSource()
      : getRawDataSource().list;`
      : ''
  }
    const json = generateTableJson(filterColumns, dataSource${isNoTableModel ? '.value' : ''});
    const properties = filterColumns.map((item) => item.title);
    printJS({
      printable: json,
      properties: properties,
      type: 'json',
    });
  }`
      : ''
  }
  ${
    hasTemplatePrint
      ? `
    // 模板打印
		 async function handleTemplateprint() {
		      if (!selectedKeys.value.length) {
		        notification.warning({
		          message: t('提示'),
		          description: t('请选择数据'),
		        });
		        return;
		      }
		      if (selectedKeys.value.length > 1) {
		        notification.warning({
		          message: t('提示'),
		          description: t('只能选择一条数据进行操作'),
		        });
		        return;
		      }
		      try {
  ${
    isNoTableModel
      ? `const viewConfig = apiConfig.find((item) => item.value === 'view');
  const record = await apiConfigFunc(viewConfig, true, selectedRowsData.value[0]);
  const listConfig = apiConfig.find((item) => item.value === 'view')?.outputConfig;
  for (let key in record) {
    listConfig?.forEach((config) => {
      if (config.apiField === key) {
        record[camelCaseString(config.bindField!)!] = record[key];
      }
    });
  }`
      : `let id = selectedKeys.value[0];
		    const record = await get${pascalMainTableName}(id);`
  }
		        let res = await getPrintConfigInfo(printData.code, printMenuId.value);
            if(res.enabledMark==null){
              notification.warning({
                message: t('提示'),
                description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
              });
              return ;
            }
            if(res.enabledMark==0){
              notification.warning({
                message: t('提示'),
                description: t('找不到打印模板，请联系管理员。'),
              });
              return ;
            }
            printData.id = res.schemaId;
		        if (res.apiConfig) {
		          let json = JSON.parse(res.apiConfig);
		          if (json.requestParamsConfigs && json.requestParamsConfigs.length > 0) {
		            printData.requestParamsConfigs = json.requestParamsConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          if (json.requestHeaderConfigs && json.requestHeaderConfigs.length > 0) {
		            printData.requestHeaderConfigs = json.requestHeaderConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          if (json.requestBodyConfigs && json.requestBodyConfigs.length > 0) {
		            printData.requestBodyConfigs = json.requestBodyConfigs.map((ele) => {
		              if (ele.config && record[ele.config] != undefined) {
		                ele.value = record[ele.config];
		              }
		              return ele;
		            });
		          }
		          printData.visible = true;
		        }else{
              notification.warning({
					        message: t('提示'),
					        description: t('当前功能未绑定打印模板，请绑定后再进行模板打印。'),
					      });
            }
		      } catch (error) {}
		    }

    function handleClosePrintPreview() {
      printData.visible = false;
      ${isNoTableModel ? 'getDataSource(getForm().getFieldsValue());' : 'reload();'}
    }

    `
      : ''
  }
  ${
    hasFilterButton
      ? `
  function handleFilterClick(column) {
    clickColumnIndex.value = column.dataIndex
  }`
      : ''
  }
  ${
    hasRowCheck && !isCardList
      ? `
  function onSelectChange(selectedRowKeys: [], selectedRows) {
    selectedKeys.value = selectedRowKeys;
    selectedRowsData.value = selectedRows;
  }`
      : ''
  }
  ${hasExecuteButton ? getExecuteEvent() : ''}
  function customRow(record: Recordable) {
    return {
      ${
        hasRowCheck && !isCardList
          ? `
      onClick: () => {
        let selectedRowKeys = [...selectedKeys.value];
        if (selectedRowKeys.indexOf(record.${camelCaseString(mainTable.pkField)}) >= 0) {
          let index = selectedRowKeys.indexOf(record.${camelCaseString(mainTable.pkField)});
          selectedRowKeys.splice(index, 1);
        } else {
          selectedRowKeys.push(record.${camelCaseString(mainTable.pkField)});
        }
        selectedKeys.value = selectedRowKeys;
      },`
          : ''
      }
      ondblclick: () => {
        if (record.isCanEdit && hasPermission("${lowerClassName}:edit")) {
          handleEdit(record);
        }
      },
    };
  }
  ${
    hasSetUserIdButton
      ? isSetDataAuth
        ? `
  function handleBatchSetUserId() {
    if (!selectedKeys.value.length) {
      notification.warning({
        message: 'Tip',
        description: t('请选择需要设置权限的数据'),
      });
      return;
    }
    openRuleUserModal(true, {
      rowKey: '${camelCaseString(mainTable.pkField)}', 
      columns: filterColumns,
      dataSource: selectedRowsData.value,
      setDataAuthApi: setDataAuth${pascalMainTableName}
    });
  }`
        : `
  function handleBatchSetUserId() {
    Modal.confirm({
      title: '操作失败',
      icon: createVNode(CloseCircleOutlined, { style: 'color: #ed6f6f' }),
      content: createVNode(
        'div',
        { style: 'color: #999' },
        '当前功能未配置数据权限，请配置后再进行操作。',
      ),
      centered: true,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        reload();
      },
      onCancel() {
       reload();
       },
    });
  }`
      : ''
  }
  function handleSuccess(${isVerticalList ? 'isReload?' : ''}) {
    ${
      isVerticalList
        ? `if (isReload === false) {
      tabChangeIsReload.value = true;
    } else {`
        : ''
    }
    ${
      hasRowCheck
        ? `
        selectedKeys.value = [];
        selectedRowsData.value = [];`
        : ''
    }
    ${isNoTableModel ? 'getDataSource(getForm().getFieldsValue());' : 'reload();'}
    ${isVerticalList ? '}' : ''}
  }
    ${isNoTableModel ? `function handleRedo() {  getDataSource(getForm().getFieldsValue()); }` : ''}
  ${
    isVerticalList
      ? `function handleTabsEdit(targetKey) {
    handleTabsRemove(targetKey);
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }
  function handleTabsRemove(targetKey) {
    let lastIndex = 0;
    modePanes.value.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
        enableLockeData.dataId = pane.content.id;
        enableLockeData.formId = formIdComputedRef.value;
      }
    });
    modePanes.value = modePanes.value.filter((pane) => pane.key !== targetKey);
    if (modePanes.value.length && modeActiveKey.value === targetKey) {
      if (lastIndex >= ${hasAddButton ? '1' : '0'}) {
        modeActiveKey.value = modePanes.value[lastIndex].key;
        if (lastIndex > ${
          hasAddButton ? '1' : '0'
        }) FormNormalRef.value.handleInner(modePanes.value[lastIndex].content);
      }
    }
  }`
      : ''
  }
    function handleFormSuccess() {
    handleSuccess();
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }
  function handleFormCancel() {
    handleCloseFormEnableLocke(buttonConfigs.value, 'edit');
  }

  ${
    hasViewButton
      ? `
  function handleView(record: Recordable) {
  let info={
      isView: true,
     ${isNoTableModel ? `record,` : `id: record.${camelCaseString(mainTable.pkField)},`}
    }
${
  isHorizontalList
    ? `horizontalTitle.value = '查看';
      horizontalEmpty.value = false;
      FormNormalRef.value.handleInner(info);`
    : `${
        formType === 'modal'
          ? `
    openModal(true, info);`
          : ` 
    openDrawer(true, info);`
      }`
}    
  }`
      : ''
  }
  ${
    hasExportButton
      ? `
  async function handleExport() {
    ${
      isNoTableModel
        ? `
    const exportValue: Array<string>[] = [];
    const title = columns.map((col) => col.title) as string[];
    exportValue.push(title);

    dataSource.value.forEach((item, index) => {
      columns.forEach((col) => {
        if (!exportValue[index + 1]) {
          exportValue[index + 1] = [];
        }
        exportValue[index + 1].push(item[col.dataIndex as string] || '');
      });
    });

    const dataInfo = XLSX.utils.aoa_to_sheet(exportValue);
    /**设置标题头背景色 */
    for (const key in dataInfo) {
      // 第一行，表头
      if (key.replace(/[^0-9]/gi, '') === '1') {
        dataInfo[key].s = {
          fill: {
            //背景色
            fgColor: {
              rgb: 'C0C0C0',
            },
          },
          font: {
            //字体
            name: '宋体',
            sz: 12,
            bold: true,
          },
          border: {
            //边框
            bottom: {
              style: 'thin',
              color: '#9a9a9a',
            },
            right: {
              style: 'thin',
              color: '#9a9a9a',
            },
          },
          alignment: {
            horizontal: 'center', //水平居中
            vertical: 'center',
          },
        };
      }
    }
    dataInfo['!rows'] = [{ hpx: 25 }];

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表放入工作簿中
    XLSX.utils.book_append_sheet(wb, dataInfo);
    // 生成文件并下载
    XLSX.writeFile(wb, '${model.listConfig?.listTitle || pascalClassName}.xlsx');`
        : 'visibleExport.value = true;'
    }
  }
  ${
    !isNoTableModel
      ? `
  async function handleExportSuccess(cols) {
    const res = await export${pascalMainTableName}({ isTemplate: false, columns: cols.toString(), ...pageParamsInfo.value});
    visibleExport.value = false;
    downloadByData(
      res.data,
      '${model.listConfig?.listTitle || pascalClassName}.xlsx',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    reload();
  }`
      : ''
  }`
      : ''
  }
  ${
    hasImportButton
      ? `
  function handleImport() {
    openImportModal(true, {
      title: '快速导入',
      downLoadUrl:'/${model.outputConfig.outputValue}/${lowerClassName}/export',
    });
  }
  function handleImportSuccess(){
    reload()
  }`
      : ''
  }
  ${
    model.listConfig.leftMenuConfig?.some((x) => x.treeConfig?.id)
      ? `
      function handleSelectTree(treeConditions) {
      ${
        isNoTableModel
          ? `
        let searchInfo = {};
        for (let key in treeConditions[0]) {
          searchInfo[camelCaseString(key)!] = treeConditions[0][key];
        }
        getDataSource(searchInfo);`
          : `
        reload({ searchInfo:{treeConditions:encodeURI(JSON.stringify(treeConditions))} });
        `
      }
        ${
          model.listConfig.leftMenuConfig!.length > 1
            ? `treeMenuSeleceted.value[leftMenuIndex.value] = treeConditions;`
            : ''
        }
      }
      `
      : ''
  }
  ${
    model.listConfig.isLeftMenu
      ? `
  function handleSelect(selectIds) {
    selectId.value = selectIds[0];
    ${
      model.listConfig.leftMenuConfig!.length > 1
        ? `
    reload({
      searchInfo: { [camelCaseString(leftMenuConfig![leftMenuIndex.value]!.listFieldName!) as string]: selectIds[0] },
    });
    treeMenuSeleceted.value[leftMenuIndex.value] = selectIds;`
        : `
        ${
          isNoTableModel
            ? `getDataSource({ ${camelCaseString(
                model.listConfig.leftMenuConfig![0].listFieldName!,
              )}: selectIds[0] });`
            : `
          reload({ searchInfo: { ${camelCaseString(
            model.listConfig.leftMenuConfig![0].listFieldName!,
          )}: selectIds[0] } });`
        }
    `
    }
    ${isHorizontalList ? ' leftTreeShow.value = false;' : ''}
  }
  async function fetch() {
${
  model.listConfig.leftMenuConfig!.length > 1
    ? `    
    //如果是数据字典
    if (leftMenuConfig![leftMenuIndex.value]!.datasourceType === 'dic') {
      treeData.value = (await getDicDetailList({
        itemId: leftMenuConfig![leftMenuIndex.value]!.dictionaryItemId,
      })) as unknown as TreeItem[];
    } else if (leftMenuConfig![leftMenuIndex.value]!.datasourceType === 'static') {
      //如果是静态数据
      treeData.value = leftMenuConfig![leftMenuIndex.value]!.staticData!;
    } else if (leftMenuConfig![leftMenuIndex.value]!.datasourceType === 'api') {
      //如果是api
      treeData.value = (await apiConfigFunc(
        leftMenuConfig![leftMenuIndex.value]!.apiConfig,
        false,
      )) as unknown as TreeItem[];
    }`
    : `    ${
        model.listConfig.leftMenuConfig![0].datasourceType === `dic`
          ? `treeData.value = (await getDicDetailList({
      itemId: '${model.listConfig.leftMenuConfig![0].dictionaryItemId}',
    })) as unknown as TreeItem[];
    `
          : ``
      }
    ${
      model.listConfig.leftMenuConfig![0].datasourceType === `static`
        ? `treeData.value = ${JSON.stringify(model.listConfig.leftMenuConfig![0].staticData)};`
        : ``
    }
    ${
      model.listConfig.leftMenuConfig![0].datasourceType === `api`
        ? `treeData.value = (await apiConfigFunc(${JSON.stringify(
            model.listConfig.leftMenuConfig![0].apiConfig,
          )}, false)) as unknown as TreeItem[];`
        : ``
    }
    ${
      model.listConfig.leftMenuConfig![0].datasourceType === `datasource`
        ? `treeData.value = listToTree(await getDatasourceData('${
            model.listConfig.leftMenuConfig![0].datasourceId
          }'), {
      id: '${model.listConfig.leftMenuConfig![0].relationFieldName}',
      children: 'children',
      pid: '${model.listConfig.leftMenuConfig![0].parentFiledName}',
    });
    `
        : ``
    }`
}
    ${
      model.listConfig.leftMenuConfig?.some((x) => x.childIcon || x.parentIcon)
        ? 'addRenderIcon(treeData.value);'
        : ''
    }
  }
  ${
    model.listConfig.leftMenuConfig?.some((x) => x.childIcon || x.parentIcon)
      ? `
  function addRenderIcon(data) {
    data.map((item) => {
      if (item.children?.length) addRenderIcon(item.children);
      return (item.renderIcon = item.children?.length ? 'parentIcon' : 'childIcon');
    });
  }`
      : ``
  }`
      : ``
  }
  function getLessActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(0, listSpliceNum.value);
  }
  function getMoreActions(record: Recordable) {
    let list = getActions(record);
    return list.slice(listSpliceNum.value);
  }
  function getActions(record: Recordable):ActionItem[] {
    record.isCanEdit = false;
    ${
      hasStartWorkButton
        ? `
    let actionsList: ActionItem[] = [];
    let editAndDelBtn: ActionItem[] = [];
    let pushorderBtn: ActionItem[] = [];
    let orderBtn: ActionItem[] = [];
    let hasStartwork = false;
   ${hasFlowRecordButton ? `let hasFlowRecord = false;` : ''} 
    actionButtonConfig.value?.map((button) => {
      const btns = {
        ...button,
        ${isCardList ? 'icon: button?.icon,' : ''}
        auth: \`${lowerClassName}:\${button.code}\`,
        ${isCardList ? 'tooltip' : 'label'}: button?.name,
        color: button.code === 'delete' ? 'error' : undefined,
        onClick: btnEvent[button.code]?.bind(null, record),
      };

      if (['edit', 'delete'].includes(button.code)) {
        editAndDelBtn.push(btns);
      } else if (!['pushorder', 'startwork', 'flowRecord'].includes(button.code)) {
        orderBtn.push(btns);
      }
      if (button.code === 'pushorder') {
        pushorderBtn.push({
          ${isCardList ? 'icon: button?.icon,' : ''}
          auth: \`${lowerClassName}:\${button.code}\`,
          ${isCardList ? 'tooltip' : 'label'}: button?.name,
          onClick: btnEvent[button.code].bind(null, record),
        });
      }
      if (button.code === 'startwork') hasStartwork = true;
      ${hasFlowRecordButton ? `if (button.code === 'flowRecord') hasFlowRecord = true;` : ''}
    });
    if (record?.workflowData?.enabled) {
      //与工作流有关联的表单
      if (record?.workflowData?.status) {
        //如果是本人需要审批的数据 就会有taskIds  所以需要修改绑定事件
        const act: ActionItem = {};
        if (hasStartwork) {
          if (record?.workflowData?.taskIds) {
            act.${isCardList ? 'tooltip' : 'label'} = '查看流程(待审批)';
            ${isCardList ? "act.icon = 'daishenpi|svg';" : ''}
            act.onClick = handleApproveProcess.bind(null, record);
          } else {
            act.${isCardList ? 'tooltip' : 'label'} =
              '查看流程' + (record.workflowData.status === 'ACTIVE' ? '(审批中)' : '(已完成)');
            ${
              isCardList
                ? "act.icon = record.workflowData.status === 'ACTIVE' ? 'jinshenpi|svg' : 'shenpiwancheng|svg';"
                : ''
            }
            act.onClick = handleStartwork.bind(null, record);
          }
        }
        actionsList.unshift(act);
        ${
          hasFlowRecordButton
            ? `if (hasFlowRecord) {
          actionsList.splice(1, 0, {
          ${isCardList ? 'tooltip' : 'label'}: '查看流转记录',
          ${isCardList ? "icon: 'liuzhuanxinxi|svg'," : ''}  
            onClick: handleFlowRecord.bind(null, record),
          });
        }`
            : ''
        }
       
      } else {
        if (hasStartwork) {
          actionsList.unshift({
            ${isCardList ? "icon: 'faqishenpi|svg'," : ''} 
            ${
              isCardList ? 'tooltip' : 'label'
            }: record?.workflowData?.draftId ? '编辑草稿' : '发起审批' ,
            onClick: handleLaunchProcess.bind(null, record),
          });
        }
        record.isCanEdit = true;
        actionsList = actionsList.concat(editAndDelBtn);
      }
    } else {
      if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        //与工作流没有关联的表单并且在当前页面新增的数据 如选择编辑、删除按钮则加上
        actionsList = actionsList.concat(editAndDelBtn);
      }
    }
    actionsList.unshift(...pushorderBtn, ...orderBtn);
    return actionsList;
  }



    `
        : `
    let actionsList: ActionItem[] = [];  
    actionButtonConfig.value?.map((button) => {
    if (!record?.workflowData?.processId) {
        record.isCanEdit = true;
        actionsList.push({
          ...button,
          ${isCardList ? 'icon: button?.icon,' : ''} 
          auth: \`${lowerClassName}:\${button.code}\`,
          ${isCardList ? 'tooltip' : 'label'}: button?.name,
          color: button.code === 'delete' ? 'error' : undefined,
          onClick: btnEvent[button.code]?.bind(null, record),
        });
      } else {
        if (!['edit', 'delete'].includes(button.code)) {
          actionsList.push({
            ${isCardList ? 'icon: button?.icon,' : ''} 
            auth: \`${lowerClassName}:\${button.code}\`,
            ${isCardList ? 'tooltip' : 'label'}: button?.name,
            onClick: btnEvent[button.code]?.bind(null, record),
          });
        } 
      }
    });
    return actionsList;
  }`
    }
  ${
    hasStartWorkButton
      ? `
  function handleStartwork(record: Recordable) {
    if (record?.workflowData) {
      visibleLookProcessRef.value = true;
      processIdRef.value = record.workflowData?.processId;
    }
  }
  ${
    hasFlowRecordButton
      ? `function handleFlowRecord(record: Recordable) {
    if (record?.workflowData) {
      visibleFlowRecordModal.value = true;
      processIdRef.value = record?.workflowData?.processId;
    }
  }`
      : ''
  }
  
  async function handleLaunchProcess(record: Recordable) {
    try {
      let hasIn = handleHasEnableLocke(buttonConfigs.value, 'startwork');
      if (hasIn) {
        let dataId = record['${camelCaseString(mainTable.pkField)}'];
        await handleOpenFormEnableLockeData(dataId, formIdComputedRef.value);
      }
      if (record?.workflowData) {
        if (record?.workflowData?.draftId) {
          let res = await getDraftInfo(record.workflowData.draftId);
          let data = isValidJSON(res.formData);
          if (data) {
            for (let key in data) {
              if (key.includes(formIdComputedRef.value)) {
                formDataRef.value = data[key];
              }
            }
          }
          draftsId.value = record.workflowData.draftId;
        } else {
          const result = await get${pascalMainTableName}(record['${camelCaseString(
          mainTable.pkField,
        )}']);
          formDataRef.value = result;
        }
        rowKeyData.value = record['${camelCaseString(mainTable.pkField)}'];
        visibleLaunchProcessRef.value = true;
        schemaIdRef.value = record.workflowData.schemaId;
      }
     } catch (error) {}    
   
  }
  async function handleApproveProcess(record: Recordable) {
      try {
        let hasIn = handleHasEnableLocke(buttonConfigs.value, 'startwork');
        if (hasIn) {
          let dataId = record['${camelCaseString(mainTable.pkField)}'];
          await handleOpenFormEnableLockeData(dataId, formIdComputedRef.value);
        }
        visibleApproveProcessRef.value = true;
        schemaIdRef.value = record.workflowData.schemaId;
        processIdRef.value = record.workflowData.processId;
        taskIdRef.value = record.workflowData.taskIds[0];
      } catch (error) {}    
   
  }
  function handleCloseLaunch() {
    visibleLaunchProcessRef.value = false;
    draftsId.value = '';
    ${isVerticalList ? 'modeActiveKey.value = 1;' : ''}
    reload();
     handleCloseFormEnableLocke(buttonConfigs.value, 'startwork');
  }
      ${
        hasTemplatePrint
          ? ` function handleClosePrintPreview() {
              printData.visible = false;
              reload();
            }`
          : ''
      }

 
  function handleCloseApproval() {
    visibleApproveProcessRef.value = false;
    reload();
     handleCloseFormEnableLocke(buttonConfigs.value, 'startwork');
  }
  `
      : ''
  }
  ${
    hasSubformList
      ? `
  function getInnerDataSource(id, field) {
    if (innerDataSource.value[id]) {
      return innerDataSource.value[id][field];
    }
    return [];
  }

  async function expandedRowsChange(isOpen, record) {
    if (!isOpen) return;
    const tableInfo = await getChildren${pascalMainTableName}({
      id: record.id,
    });
    innerDataSource.value[record.id] = tableInfo;
  }`
      : ''
  }
</script>
<style lang="less" scoped>
${
  isCardList
    ? `  :deep(.ant-table) {
    table {
      width: 100% !important;
    }
  }`
    : ''
}
  :deep(.ant-table-selection-col) {
    width: 50px;
  }

  .show{
    display: flex;
  }

  .hide{
    display: none !important;
  }
  ${
    isCardList
      ? `
  :deep(.vben-basic-table) {
    .ant-table .ant-table-body {
      height: 100% !important;
      border-radius: 16px;

      tr td {
        padding: 0 !important;
        border-bottom: none;
      }
    }
  }

  :deep(.ant-table-header) {
    display: none;
  }

  :deep(.ant-table-expanded-row-fixed) {
    margin: 0 !important;
    padding: 0;
  }

  .selected-box {
    border: 1px solid @primary-color;
    background: linear-gradient(to bottom, #88b1ff, #fff 80%);

    .box-title {
      border-bottom: 1px solid #98b7f1;

      .icon-box {
        background: @primary-color;
        color: #fff;
      }

      .icon-delete {
        background: #ed6f6f;
      }
    }
  }

  .unselected-box {
    background: linear-gradient(to bottom, #e7efff, #fff 80%);

    .box-title {
      border-bottom: 1px solid #e3edff;

      .icon-box {
        background: #fff;
        color: @primary-color;
      }

      .icon-delete {
        background: #fff;
        color: #ed6f6f;
      }
    }
  }

  .data-list {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    padding: 0 10px;

    .box-container {
      margin: 0 10px 10px 0;
      flex: 0 0 calc((100% - 20px) / 3);
      height: 270px;
      overflow: auto;
      padding-bottom: 10px;

      &:nth-child(3n) {
        margin-right: 0;
      }

      .box-title {
        width: 100%;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 5px;

        .icon-box {
          padding: 4px;
          border-radius: 50%;
          margin-right: 5px;
          cursor: pointer;
          vertical-align: middle;
        }
      }

      .flex-box {
      ${
        model.listConfig.arrangeType === 'two'
          ? `
        display: flex; 
        flex-wrap: wrap; `
          : ''
      }
        height: calc(100% - 40px);
        overflow: auto;
        padding: 10px 10px 0;

        .flex-item {
          flex: 0 0 50%;
          height: 50px;
          overflow: hidden;

          > div {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }

          .title {
            color: #67676c;
          }

          .value {
            font-weight: bold;
            color: #4a4b4d;
          }
        }
      }
    }
  }  `
      : ''
  }
  ${
    hasPushOrderButton
      ? `
  .btn-box {
    display: grid;
    position: absolute;
    ${
      isCardList
        ? `
    top: 30px;`
        : `
    top: 0;
    left: v-bind(pushbtnleft);`
    }
    z-index: 999;

    .ant-btn {
      margin-top: 5px;
      padding: 0 10px;
    }
  }`
      : ''
  }
  ${
    hasSubformList
      ? `
  :deep(.ant-table-expanded-row) {
    .ant-table {
      margin: 0 !important;
      height: 100%;

      .ant-table-thead {
        height: 40px;
      }

      .ant-empty-normal {
        margin: 16px 0;
      }
    }
    .ant-table-wrapper {
      height: 200px;
    }
  }`
      : ''
  }
  ${
    model.listConfig.leftMenuConfig!.length > 1
      ? `
  .left-menu-box {
    :deep(.ant-tabs-tab) {
      padding: 12px;
      margin: 0;
    }

    :deep(.ant-tabs-nav) {
      margin-bottom: 0;
    }

    :deep(.ant-tabs-content),
    :deep(.ant-tabs-top) {
      height: 100%;
    }
  }`
      : ''
  }
</style>`;
  return code;
}
/**
 * 构建SimpleForm页面
 * @param model
 * @returns {string}
 */
export function buildSimpleFormCode(
  model: GeneratorConfig,
  _tableInfo: TableInfo[],
  designType?: string,
): string {
  const className = model.outputConfig.className;
  const isHorizontalList = model.listConfig.listStyle === LIST_MODE.HORIZONTAL;
  const lowerClassName = className?.toLowerCase();
  const isNoTableModel = designType === 'notable';

  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 = `
<template>
  <div class="pt-4">
    <SimpleForm
      ref="systemFormRef"
      :formProps="data.formDataProps"
      :formModel="state.formModel"
      :isWorkFlow="props.fromPage!=FromPageType.MENU"
      :isCamelCase="true" 
      @model-change="handleChange"
    />
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, onMounted, nextTick, watch } from 'vue';
  import { formProps, formEventConfigs${isNoTableModel ? `, apiConfig` : ''} } from './config';
  import SimpleForm from '/@/components/SimpleForm/src/SimpleForm.vue';
  ${
    !isNoTableModel
      ? `import { add${pascalMainTableName}, get${pascalMainTableName}, update${pascalMainTableName} } from '/@/api/${model.outputConfig.outputValue}/${lowerClassName}';`
      : ''
  }
  import { cloneDeep, isString  } from 'lodash-es';
  import { FormDataProps } from '/@/components/Designer/src/types';
  import { usePermission } from '/@/hooks/web/usePermission';
  import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';
  import { FromPageType } from '/@/enums/workflowEnum';
  import { createFormEvent, getFormDataEvent, loadFormEvent, submitFormEvent,} from '/@/hooks/web/useFormEvent';
  import { changeWorkFlowForm, changeSchemaDisabled } from '/@/hooks/web/useWorkFlowForm';
  import { WorkFlowFormParams } from '/@/model/workflow/bpmnConfig';
  import { useRouter } from 'vue-router';
  ${isNoTableModel ? `import { apiConfigFunc, camelCaseString } from '/@/utils/event/design';` : ''}
  const { filterFormSchemaAuth } = usePermission();

  const RowKey = '${mainTable.pkField ? camelCase(mainTable.pkField) : 'id'}';
  const emits = defineEmits(['changeUploadComponentIds','loadingCompleted', 'update:value']);
  const props = defineProps({
    fromPage: {
      type: Number,
      default: FromPageType.MENU,
    },
  });
  const systemFormRef = ref();
  const data: { formDataProps: FormDataProps } = reactive({
    formDataProps: cloneDeep(formProps),
  });
  const state = reactive({
    formModel: {},
    formInfo:{formId:'',formName:''}
  });
  const { currentRoute } = useRouter();
  watch(
    () => state.formModel,
    (val) => { 
      emits('update:value', val);
    },
    {
      deep: true,
    },
  );
  
  onMounted(async () => {
    try {
      if (props.fromPage == FromPageType.MENU) {
        setMenuPermission();
        if(currentRoute.value.meta){
          state.formInfo.formName = currentRoute.value.meta.title&&isString(currentRoute.value.meta.title)?currentRoute.value.meta.title:'';
          state.formInfo.formId = currentRoute.value.meta.formId&&isString(currentRoute.value.meta.formId)?currentRoute.value.meta.formId:'';
        }
        await createFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：初始化表单
        await nextTick();
        await loadFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：加载表单
      } else if (props.fromPage == FromPageType.FLOW) {
        emits('loadingCompleted'); //告诉系统表单已经加载完毕
        // loadingCompleted后 工作流页面直接利用Ref调用setWorkFlowForm方法
      } else if (props.fromPage == FromPageType.PREVIEW) {
        // 预览 无需权限，表单事件也无需执行
      } else if (props.fromPage == FromPageType.DESKTOP) {
        // 桌面设计 表单事件需要执行
        emits('loadingCompleted'); //告诉系统表单已经加载完毕
        await createFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：初始化表单
        await loadFormEvent(formEventConfigs, state.formModel,
          systemFormRef.value,
          formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：加载表单
      }
    } catch (error) {}
  });
  // 根据菜单页面权限，设置表单属性（必填，禁用，显示）
  function setMenuPermission() {
    data.formDataProps.schemas = filterFormSchemaAuth(data.formDataProps.schemas!);
  }

  // 校验form 通过返回表单数据
  async function validate() {
    let values = [];
    try {
      values = await systemFormRef.value?.validate();
      //添加隐藏组件
      if (data.formDataProps.hiddenComponent?.length) {
        data.formDataProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
    } finally {
    }
    return values;
  }  
  // 根据行唯一ID查询行数据，并设置表单数据   【编辑】
  async function setFormDataFromId(rowId) {
    try {
    ${
      isNoTableModel
        ? `const viewConfig = apiConfig.find((item) => item.value === 'view');
      const listConfig = apiConfig.find((item) => item.value === 'view')?.outputConfig;
      const record = await apiConfigFunc(viewConfig, true, rowId);
      for (let key in record) {
        listConfig?.forEach((config) => {
          const apiFieldArr = config.apiField.split(',');
          const bindFieldArr = camelCaseString(config.bindField)!.split(',');
          if (config.apiField === key) {
            record[camelCaseString(config.bindField!)!] = record[key];
          } else if (apiFieldArr.length > 1) {
            const bindTable = bindFieldArr[0] + 'List';
            record[apiFieldArr[0]].forEach((info, index) => {
              if (!record[bindTable]) record[bindTable] = [];

              if (record[bindTable][index]) {
                record[bindTable][index][bindFieldArr[1]] = info[apiFieldArr[1]];
              } else {
                record[bindTable].push({
                  [bindFieldArr[1]]: info[apiFieldArr[1]],
                });
              }
            });
          }
        });
      }`
        : `const record = await get${pascalMainTableName}(rowId);`
    }
      setFieldsValue(record);
      state.formModel = record;
      await getFormDataEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：获取表单数据
    } catch (error) {
      
    }
  }
  // 辅助返回表单数据
  async function getFieldsValue() {
    let values = [];
    try {
      values = await systemFormRef.value?.getFieldsValue();
      //添加隐藏组件
      if (data.formDataProps.hiddenComponent?.length) {
        data.formDataProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
    } finally {
    }
    return values;
  }
  // 辅助设置表单数据
  function setFieldsValue(record) {
    systemFormRef.value.setFieldsValue(record);
  }
  // 重置表单数据
  async function resetFields() {
    await systemFormRef.value.resetFields();
  }
  //  设置表单数据全部为Disabled  【查看】
  async function setDisabledForm( ${isHorizontalList ? `disabled?` : ''}) {
    data.formDataProps.schemas = changeSchemaDisabled(cloneDeep(data.formDataProps.schemas)${
      isHorizontalList ? `,disabled` : ''
    });
  }
  // 获取行键值
  function getRowKey() {
    return RowKey;
  }
  // 更新api表单数据
  async function update({ values, rowId }) {
    try {
      values[RowKey] = rowId;
      state.formModel = values;
      ${
        isNoTableModel
          ? `const editConfig = apiConfig.find((item) => item.value === 'edit');
      let saveVal = await apiConfigFunc(editConfig, true, values);`
          : `let saveVal = await update${pascalMainTableName}(values);`
      }
      await submitFormEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true,  state.formInfo.formName,state.formInfo.formId); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 新增api表单数据
  async function add(values) {
    try {
      state.formModel = values;
      ${
        isNoTableModel
          ? `const addConfig = apiConfig.find((item) => item.value === 'add');
      let saveVal = await apiConfigFunc(addConfig, true, values);`
          : `let saveVal = await add${pascalMainTableName}(values);`
      }
      await submitFormEvent(formEventConfigs, state.formModel,
        systemFormRef.value,
        formProps.schemas, true,  state.formInfo.formName,state.formInfo.formId); //表单事件：提交表单
      return saveVal;
    } catch (error) {}
  }
  // 根据工作流页面权限，设置表单属性（必填，禁用，显示）
  async function setWorkFlowForm(obj: WorkFlowFormParams) { 
    try {
      if (obj.formId) state.formInfo.formId = obj.formId;
      if (obj.formName) state.formInfo.formName = obj.formName;
      let flowData = await changeWorkFlowForm(cloneDeep(formProps), obj);
      let { buildOptionJson, uploadComponentIds, formModels, isViewProcess } = flowData;
      data.formDataProps = buildOptionJson;
      emits('changeUploadComponentIds', uploadComponentIds); //工作流中必须保存上传组件id【附件汇总需要】
      if (isViewProcess) {
        setDisabledForm(); //查看
      }
      state.formModel = formModels;
      setFieldsValue(formModels);
    } catch (error) {}
    await createFormEvent(formEventConfigs, state.formModel,
      systemFormRef.value,
      formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：初始化表单
    await loadFormEvent(formEventConfigs, state.formModel,
      systemFormRef.value,
      formProps.schemas, true, state.formInfo.formName,state.formInfo.formId); //表单事件：加载表单
  }
  function handleChange(val) { 
    emits('update:value', val);
  }
   async function sendMessageForAllIframe() {
    try {
      if (systemFormRef.value && systemFormRef.value.sendMessageForAllIframe) {
        systemFormRef.value.sendMessageForAllIframe();
      }
    } catch (error) {}
  }
  defineExpose({
    setFieldsValue,
    resetFields,
    validate,
    add,
    update,
    setFormDataFromId,
    setDisabledForm,
    setMenuPermission,
    setWorkFlowForm,
    getRowKey,
    getFieldsValue,
    sendMessageForAllIframe
  });
</script>\n
  `;
  return code;
}
/**
 * 构建表单页面
 * @param model
 * @returns {string}
 */
export function buildFormCode(
  model: GeneratorConfig,
  _tableInfo: TableInfo[],
  designType?: string,
): string {
  const formType = model.formJson.config.formType;
  const formWidth = model.formJson.config.formWidth;
  const formHeight = model.formJson.config.formHeight;
  const formButtons = model.formJson.buttonList || [];
  const isNoTableModel = designType === 'notable';
  const isVerticalList = model.listConfig.listStyle === LIST_MODE.VERTICAL;
  const isHorizontalList = model.listConfig.listStyle === LIST_MODE.HORIZONTAL;

  const code = `
<template>
${
  isVerticalList || isHorizontalList
    ? `<div class="h-full bg-white rounded-2xl ${
        isHorizontalList ? 'pt-60px' : 'pt-4'
      }" v-if="formType == 'normal'">
    <div :style="{height:(listPageMode == LIST_MODE.VERTICAL && isShowBtn) || !state.isView ? 'calc(100% - 76px)' : '100%'}" class="overflow-y-auto">
      <ModalForm v-model:value="state.formModel" ref="formRef" :fromPage="FromPageType.MENU" />
    </div>
    <div class="flex mx-auto justify-between w-54 mt-6 absolute left-0 right-0 bottom-5" v-if="
        (listPageMode == LIST_MODE.VERTICAL&&isShowBtn) ||
        (listPageMode == LIST_MODE.HORIZONTAL && !state.isView)
      ">
      ${
        formButtons.length > 0
          ? `<template v-for="(item, index) in sortBy(formButtons, 'index')" :key="item.key">
          <a-button
            :type="item.style"
            v-if="item.isShow"
            :style="{ marginLeft: index > 0 ? '10px' : 0 }"
            @click="customClick(item)"
          >
            {{ t(item.name) }}
          </a-button>
        </template>`
          : `<a-button @click="handleReset" class="!h-10 w-25">重置</a-button>
      <a-button type="primary" @click="handleSubmit" class="!h-10 w-25">确认</a-button>`
      } 
    </div>
  </div>`
    : ''
}
${
  formType === 'modal'
    ? `
    <BasicModal 
    ${formHeight ? `:height="${formHeight}"` : `:bodyStyle="{ minHeight: '400px !important' }"`}   
     v-bind="$attrs" @register="registerModal" :title="getTitle"
      @ok="handleSubmit" @cancel="handleClose"  >
      <ModalForm ref="formRef" v-model:value="state.formModel" :fromPage="FromPageType.MENU" />
      ${
        formButtons.length > 0
          ? `<template #footer v-if=" !state.isView">
      <template v-for="(item, index) in sortBy(formButtons, 'index')" :key="item.key">
      <template v-if="item.isShow">
          <CustomButtonModal v-if="item.type == CustomButtonModalType.Modal" :info="item" />
          <a-button
            :type="item.style"
            v-else
            :style="{ marginLeft: index > 0 ? '10px' : 0 }"
            @click="customClick(item)"
          >
            {{ t(item.name) }}
          </a-button>
        </template>
      </template>
    </template>`
          : ''
      }
    </BasicModal>`
    : `
    <BasicDrawer :showFooter="!state.isView" v-bind="$attrs" @register="registerDrawer" :title="getTitle" @ok="handleSubmit" @cancel="handleClose">
      <ModalForm ref="formRef" v-model:value="state.formModel" :fromPage="FromPageType.MENU" />
       ${
         formButtons.length > 0
           ? `<template #footer v-if=" !state.isView">
      <template v-for="(item, index) in sortBy(formButtons, 'index')" :key="item.key">
        <template v-if="item.isShow">
          <CustomButtonModal v-if="item.type == CustomButtonModalType.Modal" :info="item" />
          <a-button
            :type="item.style"
          v-else
            :style="{ marginLeft: index > 0 ? '10px' : 0 }"
            @click="customClick(item)"
          >
            {{ t(item.name) }}
          </a-button>
         </template>
      </template>
    </template>`
           : ''
       }
    </BasicDrawer>`
}
  
</template>
<script lang="ts" setup>
  import { ref, computed, reactive, provide, Ref  ${
    isVerticalList || isHorizontalList ? ',watch' : ''
  }} from 'vue';
  ${
    formType === 'modal'
      ? `import { BasicModal, useModalInner } from '/@/components/Modal';`
      : `import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';`
  }
  ${
    formButtons.length > 0
      ? `  
      import { CustomButtonModalType } from '/@/enums/userEnum';
      import CustomButtonModal from '/@/components/Form/src/components/CustomButtonModal.vue';`
      : ``
  }
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { formProps ${formButtons.length > 0 ? `,formButtons` : ''} } from './config';
  import ModalForm from './Form.vue';
  import { FromPageType } from '/@/enums/workflowEnum';
  ${isVerticalList ? `import { cloneDeep } from 'lodash-es';` : ''}
   ${
     formButtons.length > 0
       ? `import { sortBy } from 'lodash-es';  
       import { executeCurFormEvent } from '/@/utils/event/data'; `
       : ''
   }
${
  isVerticalList || isHorizontalList
    ? `  import { LIST_MODE } from '/@/enums/formViewEnum';
    const props = defineProps({
    formType: String,
    onlyShowAddForm: Boolean,
    listPageMode: String,
    isShowBtn: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  });`
    : ''
}
  const emit = defineEmits(['success', 'register'${
    isVerticalList || isHorizontalList ? `, 'formModelChange'` : ''
  }]);

  const { notification } = useMessage();
  const formRef = ref();
  const isCopy = ref<boolean>(false)
  const state = reactive({
    formModel: {},
    isUpdate: true,
    isView: false,
    rowId: '',
  });
  provide<Ref<boolean>>('isCopy', isCopy);

  const { t } = useI18n();
  ${
    formType === 'modal'
      ? `const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await handleInner(data); 
  });`
      : `const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      await handleInner(data); 
    });`
  }

  const getTitle = computed(() => (state.isView ? '查看' : state.isUpdate ? '编辑' : isCopy.value ? '复制数据' : '新增'));

  ${
    isVerticalList || isHorizontalList
      ? `watch(
    () => state.formModel,
    (val) => {
      emit('formModelChange', val);
    },
    {
      deep: true,
    },
  );
    function handleReset() {
    formRef.value.resetFields();
  }`
      : ''
  }
  async function handleInner(data){
    state.isUpdate = !!data?.isUpdate;
    state.isView = !!data?.isView;
    isCopy.value = !!data?.isCopy;
    ${isVerticalList ? `if (props.formType !== 'normal') {` : ''}
    ${formType === 'modal' ? 'setModalProps' : 'setDrawerProps'}({
      destroyOnClose: true,
      maskClosable: false,
      showCancelBtn: ${formButtons.length > 0 ? 'false' : '!state.isView'},
      showOkBtn: ${formButtons.length > 0 ? 'false' : '!state.isView'},
      canFullscreen: true,
      width: ${formWidth || 800}, 
      ${
        formType === 'modal'
          ? 'footer: state.isView ? null : undefined,defaultFullscreen:true,'
          : ''
      }
    });
    ${
      isVerticalList
        ? `}
      if (props.formType == 'normal' && Object.entries(data.formModal).length > 0) {
      let tempModal = cloneDeep(data.formModal);
      if (!state.isUpdate && !state.isView && !isCopy.value){ delete tempModal.id; }
      formRef.value.setFieldsValue(tempModal);
    } else {`
        : ''
    }
    if (state.isUpdate || state.isView || isCopy.value) {
      state.rowId = data.id;
      if (state.isView) {
        await formRef.value.setDisabledForm();
      }
      ${
        isHorizontalList
          ? `else {
        formRef.value.setDisabledForm(false);
      }`
          : ''
      }
      await formRef.value.setFormDataFromId(${isNoTableModel ? 'data.record' : 'state.rowId'});
    } else {
      formRef.value.resetFields();
     ${isHorizontalList ? `formRef.value.setDisabledForm(false); ` : ''}
    }
    ${isVerticalList ? '}' : ''}
  }
  async function saveModal() {
    let saveSuccess = false;
    try {
      const values = await formRef.value?.validate();
      //添加隐藏组件
      if (formProps.hiddenComponent?.length) {
        formProps.hiddenComponent.forEach((component) => {
          values[component.bindField] = component.value;
        });
      }
      if (values !== false) {
        try {
          if (!state.isUpdate || isCopy.value) {
            saveSuccess = await formRef.value.add(values);
          } else {
            saveSuccess = await formRef.value.update({ values, rowId: state.rowId });
          }
          return saveSuccess;
        } catch (error) {}
      }
    } catch (error) {
      return saveSuccess;
    }
  }

  async function handleSubmit() {
    try {
      const saveSuccess = await saveModal();
      ${isVerticalList || isHorizontalList ? `if (props.formType !== 'normal') {` : ''}
      ${
        formType === 'modal'
          ? `setModalProps({ confirmLoading: true });`
          : `setDrawerProps({ confirmLoading: true });`
      }
      ${isVerticalList || isHorizontalList ? `}` : ''}
      if (saveSuccess) {
        if (!state.isUpdate || isCopy.value) {
          //false 新增
          notification.success({
            message: 'Tip',
            description: isCopy.value ? '复制成功' : t('新增成功！'),
          }); //提示消息
        } else {
          notification.success({
            message: 'Tip',
            description: t('修改成功！'),
          }); //提示消息
        }
        ${isVerticalList || isHorizontalList ? `if (props.formType !== 'normal') {` : ''}
        ${formType === 'modal' ? `closeModal();` : `closeDrawer();`}
        ${isVerticalList || isHorizontalList ? `}` : ''}
        formRef.value.resetFields();
        emit('success');
      }
    } finally {
      ${isVerticalList || isHorizontalList ? `if (props.formType !== 'normal') {` : ''}
      ${
        formType === 'modal'
          ? `setModalProps({ confirmLoading: false });`
          : `setDrawerProps({ confirmLoading: false });`
      }
      ${isVerticalList || isHorizontalList ? `}` : ''}
    }
  }
  ${
    formButtons.length > 0
      ? `function customClick(item) {
    if (item.key == 'confirm') {
      handleSubmit();
    } else if (item.key == 'cancel' && props.formType !== 'normal') {
      handleClose();
      ${formType === 'modal' ? `closeModal();` : `closeDrawer();`} 
    } else if (item.key == 'reset') {
      formRef.value.resetFields();
    } else {
      executeCurFormEvent(item.event, state.formModel, true);
    }
  }`
      : ''
  }  
  function handleClose() {
    formRef.value.resetFields();
  }
  ${
    isVerticalList || isHorizontalList
      ? ` defineExpose({
    handleInner,
    handleReset,
  });`
      : ''
  }
</script>\n
  `;
  return code;
}

/**
 * 构建表单页面FormSchema 与 列表页面BasicColumn
 * @param model
 * @param formSchema
 */
export function buildConfigJsonCode(
  model: GeneratorConfig,
  formProps: FormProps,
  designType?: string,
): 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 formButtons = model.formJson.buttonList || [];
  formButtons.forEach((o) => {
    o.event.forEach((item) => {
      camelCaseOptionsField(item.operateConfig, '', true);
    });
  });
  //将表名转为驼峰命名 首字母小写驼峰
  //将表名转为帕斯卡命名 首字母大写的驼峰
  // querySelectOption
  const code = `
  import { FormProps, FormSchema } from '/@/components/Form';
  import { BasicColumn } from '/@/components/Table';
  ${findUpload(formProps.schemas) ? `import { uploadApi } from '/@/api/sys/upload';` : ''}
  ${
    model.listConfig.isAdvancedQuery
      ? `export const searchFormSchema: FormSchema[] = [
    ${JSON.parse(model.listConfig.querySelectOption)
      .map((tempEle) => {
        return {
          fieldName: tempEle.value,
          isDate: ['time', 'date'].includes(tempEle.type) || !!tempEle.isDate,
        };
      })
      .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 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 `
      {
        resizable: true,
        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)};
          ${
            item.componentType === 'checkbox'
              ? `
            const valArr = record.${camelCaseString(item.columnName)}?.split(',');
            return staticOptions
              .filter((x) => valArr.includes(x.value))
              ?.map((x) => x.label)
              .toString();`
              : `
          return staticOptions.filter((x) => x.value == record.${camelCaseString(
            item.columnName,
          )})[0]?.label;`
          }
        },`
            : ''
        }
        ${
          item.isFilter
            ? `onFilter: (value: string, record) => record.${camelCaseString(
                item.columnName,
              )} === value,`
            : ''
        }
        ${item.isFixed ? `fixed: 'left',` : `fixed: false,`}
        sorter: true,
        ${
          model.listConfig.listStyle === 'card'
            ? `
        textBold: ${item.textBold || false},
        aRow: ${item.aRow || false},`
            : ''
        }
        styleConfig:${JSON.stringify(item.componentProps?.styleConfig)},
        listStyle:${JSON.stringify(item.componentProps?.listStyle)}
      },
      `;
      })
      .join('\n')}
  ];
  //表头合并配置
  export const headerMergingData = ${
    model.listConfig.isHeaderMerging
      ? JSON.stringify(changeHeaderMergingData(model.listConfig.headerMergingData))
      : '[]'
  };
  //表单事件
  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
  ${
    model?.listConfig?.isLeftMenu
      ? `
     ${
       model?.listConfig?.leftMenuConfig!.length > 1
         ? `//左侧树结构配置
  export const leftMenuConfig = ${JSON.stringify(model?.listConfig?.leftMenuConfig)};\n`
         : `${
             model?.listConfig?.leftMenuConfig![0].treeConfig
               ? `
        export const treeConfig = ${JSON.stringify(
          model?.listConfig?.leftMenuConfig![0].treeConfig,
        )}`
               : ''
           }`
     }`
      : ''
  }
  ${designType === 'notable' ? `export const apiConfig = ${JSON.stringify(model.apiConfig)};` : ''}
  ${
    formButtons.length > 0
      ? `export const formButtons = ${JSON.stringify(model.formJson.buttonList)};`
      : ''
  }
  `;

  return formatCode(code.replace(`"#{upload}#"`, 'uploadApi'));
}

function changeHeaderMergingData(arr) {
  const result: BasicColumn[] = [];
  arr.forEach((element) => {
    if (element.children && Array.isArray(element.children) && element.children.length > 0) {
      element.children = changeHeaderMergingData(cloneDeep(element.children));
      result.push(element);
    } else {
      if (element.dataIndex) {
        element.dataIndex = camelCaseString(element.dataIndex);
        result.push(element);
      }
    }
  });
  return result;
}
/**
 * 构建工作流权限配置文件
 * @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 = className?.toLowerCase();

  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 = className?.toLowerCase();
  // 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![0];
    categoryConfigs = {
      datasourceType: datasourceType,
      listFieldName: listFieldName ? camelCaseString(listFieldName) : '',
      childIcon: childIcon,
      parentIcon: parentIcon,
      menuName: menuName,
    };
    if (datasourceType == 'dic') {
      categoryConfigs.dictionaryItemId = model.listConfig.leftMenuConfig![0].dictionaryItemId;
    } else if (datasourceType == 'static') {
      categoryConfigs.staticData = model.listConfig.leftMenuConfig![0].staticData;
    } else if (datasourceType == 'api') {
      categoryConfigs.apiConfig = setApiConfig(model.listConfig.leftMenuConfig![0].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,
  pageSize: ${model.listConfig.pageSize ? model.listConfig.pageSize : 10},
  //分类筛选配置
  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:'${model.outputConfig.className?.toLowerCase()}:${item.code}',
        }`;
    })
    .join(',')}],
  buttonConfigs: [${getButtonConfigs(
    model.listConfig.buttonConfigs,
    pascalMainTableName,
    model.outputConfig.className?.toLowerCase(),
  ).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, className) {
  const codes = ['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: '${className}:${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: '${className}:${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;
}

const getSubFormList = (list) => {
  return list?.some((item) => {
    if (['tab', 'grid', 'card'].includes(item.type)) {
      for (const child of item.layout!) {
        return getSubFormList(child.list);
      }
    } else if (item.type == 'table-layout') {
      for (const child of item.layout!) {
        for (const sub of child.list) {
          return getSubFormList(sub.children);
        }
      }
    } else if (item.type === 'form') {
      return !!item.options.isListView;
    }
    return false;
  });
};
/**
 * 构建app列表代码
 * @param model
 */
export function buildAppListCode(_model: GeneratorConfig): string {
  const code = `
<template>
	<SimpleList ref="listRef" :routeTitle="routeTitle"  :listProps="listProps">
    <template v-slot:buttonSlot="{rowData}">
		   <!-- 当前行数据{{rowData}} -->
			 <!-- 自定义按钮
       <view class="uni-select__selector-item"  v-if="auth.buttonAuthCode.includes('自定义按钮权限名称')">
			 	<view class="item-text"> 
			 		自定义按钮
			 	</view>
			 </view> 
       -->
		</template>
  </SimpleList>
</template>

<script setup>
import { ref } from 'vue';
import { onReachBottom, onPullDownRefresh,onShow } from '@dcloudio/uni-app'; //不支持onLoad
import SimpleList from '@/components/simple-list/SimpleList.vue';
import { listProps } from './config/index.js'



onReachBottom(() => {
	// 必须要这个事件 可以不写逻辑 
});
const listRef = ref(); 
const firstLoad = ref(true);
const routeTitle = ref('列表');
let auth=uni.getStorageSync('MenuAuth')
onShow(()=>{
  const pages = getCurrentPages();
	if(pages&&Array.isArray(pages)&&pages.length>0){
		const currentPage = pages[pages.length - 1];
		if(currentPage&&currentPage.$page&&currentPage.$page.meta&&currentPage.$page.meta.navigationBar&&currentPage.$page.meta.navigationBar.titleText){
			const title = currentPage.$page.meta.navigationBar.titleText;
			routeTitle.value = title;
		}
	}
	if (firstLoad.value) {
		firstLoad.value = !firstLoad.value;
		return;
	}
	listRef.value.reload();
}) 
</script>

<style></style>

  
  `;
  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 = className?.toLowerCase();
  // 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 = `
<template>
	<view>
    <SimpleForm ref="formRef" :formProps="formConfig.formProps" :disabled="disabled"  :control="formConfig.type" :options="options"></SimpleForm>
	</view>
</template>

<script setup>
import { ref, reactive,onMounted } from 'vue';
import SimpleForm from '@/components/simple-form/SimpleForm.vue';
import { formProps } from './config/index.js';
import { FromPageType } from "@/common/enums/form.ts";
import { listProps } from './config/index.js'
import { add${pascalMainTableName}, update${pascalMainTableName}, get${pascalMainTableName} } from '@/common/api/${model.outputConfig.outputValue}/${lowerClassName}/index.js';
import { cloneDeep } from '@/utils/helper/utils.js';
import { handlerFormPermission } from "@/common/hooks/form.ts";
import { setFormPropsAuth } from '@/utils/simpleForm/changeJson.js'
const props = defineProps({
  disabled: {
    type:Boolean,
    default:false
  },
  type: {
    type:String,
    default:FromPageType.ADD
  },
  id: {
    type:String,
    default:''
  },
  isWorkFlow:{
    type:Boolean,
    default:false
  },
  formModel: {
    type:Object
  },
  workFlowParams: {
    type:Object
  },
  options:Object
});
const rowKey = listProps.rowKey;
const formConfig = reactive({
  formProps:formProps,
  id:"",
  uploadComponentIds:[],
  type:FromPageType.ADD
});
const formRef = ref();
onMounted(async () => {
  formConfig.id = props.id;
  formConfig.type = props.type;
  if(props.isWorkFlow){
    formConfig.type = props.workFlowParams.type;
    if( props.formModel&&props.formModel[rowKey]){
      formConfig.type = FromPageType.EDIT;
      formConfig.id = props.formModel[rowKey];
    }
    if(props.disabled) formConfig.type = FromPageType.VIEW;
    setWorkflowFormData(formProps);
    await formRef.value.setFormData( props.formModel ) 
  }else{
    let auth=uni.getStorageSync('MenuAuth')
		let formAuth=auth.formAuthCode||[]; 
		setFormPropsAuth(formConfig.formProps.schemas,formAuth)
    await setForm();
  }
})

async function setForm(){
  //  编辑
  if (formConfig.type == FromPageType.EDIT||formConfig.type  == FromPageType.VIEW) { 
      const {
        data
      } = await get${pascalMainTableName}(formConfig.id);
      if (data) {
        await formRef.value.setFormData({...data,...props.formModel})
      }
    }
    //新增
    else if (formConfig.type  == FromPageType.ADD) { 
      await formRef.value.init()
    }
    if(formConfig.type== FromPageType.EDIT){
      //获取表单数据
      if(listProps.formEventConfig&&listProps.formEventConfig[1]){
        formRef.value.executeFormEvent(listProps.formEventConfig[1],false);
      } 
    }

    //初始化表单
    if(listProps.formEventConfig&&listProps.formEventConfig[0]){
      formRef.value.executeFormEvent(listProps.formEventConfig[0],false);
    } 
    //加载表单
    if(listProps.formEventConfig&&listProps.formEventConfig[2]){
      formRef.value.executeFormEvent(listProps.formEventConfig[2],false);
    } 
}
// 工作流设置表单数据
async function setWorkflowForm(){
  if(props.isWorkFlow){
    setWorkflowFormData(formProps);
  }
  // formConfig.type 
  await setForm();
}
// 工作流辅助设置表单数据
function setWorkflowFormData(formProps){
  let options = cloneDeep(formProps);
  let otherParams = {...props.workFlowParams.otherParams,uploadComponentIds:formConfig.uploadComponentIds}
  let  obj = handlerFormPermission(
          options,
          props.workFlowParams.formConfigChildren,
          props.workFlowParams.formConfigKey,
          otherParams
          );
  formRef.value.updateSchema(obj.buildOptionJson.schemas)
  formConfig.uploadComponentIds = obj.otherParams.uploadComponentIds;
}
// 获取上传组件Id集合
function getUploadComponentIds(){
  return formConfig.uploadComponentIds
}
// 校验
async function validate() {
	await formRef.value.validate();
}
// 提交
 async function submit() {
  let formModelIdVal = {};
	try {
		await formRef.value.validate();
    const formData = await formRef.value.getFormData();
		if(formConfig.type == FromPageType.EDIT){
      formData[listProps.rowKey]=formConfig.id;
			await update${pascalMainTableName}(formData);
      formModelIdVal[listProps.rowKey]=formConfig.id;
		}
		else{
			let res  = await add${pascalMainTableName}(formData);
      formModelIdVal[listProps.rowKey]=res.data;
		}
	} catch (err) {
		return;
	}
  //提交表单事件
  if(listProps.formEventConfig&&listProps.formEventConfig[3]){
    formRef.value.executeFormEvent(listProps.formEventConfig[3],false);
  } 
  return formModelIdVal;
}


// 重置
async function reset() {
	await formRef.value.reset();
}
// 表单初始化
 async function init() {
	await formRef.value.init();
}
// 设置表单数据
 async function setFormData(formModels) {
	await formRef.value.setFormData(formModels);
}
// 获取表单数据
async function getFormData() {
	let formModelObj =  await formRef.value.getFormData();
  if(formConfig.type == FromPageType.EDIT||formConfig.type == FromPageType.VIEW){
      formModelObj[listProps.rowKey]=formConfig.id;
	}
  return formModelObj;
}
defineExpose({
    init,
		submit,
    reset,
		setFormData,
		validate,
		getFormData,
    setWorkflowForm,
    getUploadComponentIds
  });
</script>

<style>
page{
  background: #fff;
}
</style>
`;
  return code;
}

// 构建表单菜单页容器页面
export function buildAppContainerCode(): string {
  return `
<template>
  <view>
    <PageHead :title="routeTitle" backUrl=""></PageHead>
    <view  class="form-container">
      <view class="form-box">
        <Form ref="formRef"  :disabled="formConfig.isView" :id="formConfig.id"  :type="formConfig.type" :options="options"></Form>
        <view v-if="!formConfig.isView" class="form-btn-box">
          <button type="default" class="button" @click="reset">重置</button>
          <button type="primary" class="button" @click="submit">确定</button>		
        </view>
      </view>
    </view>
  </view>
</template>
<script setup>
    import { ref, reactive } from 'vue';
    import Form from './form.vue';
    import { onLoad } from '@dcloudio/uni-app'; 
    import PageHead from "@/components/layout/PageHead.vue";
    import { FromPageType } from "@/common/enums/form.ts";
    import { getFormTitle } from "@/common/hooks/form.ts";
    import { listProps } from './config/index.js'
    const formRef = ref(); //表单ref
    const routeTitle = ref('表单信息');
     const options=ref({});
    const formConfig = reactive({
      type:FromPageType.ADD,
      id:'',
      isView:false
    });
    onLoad(async (option) => {
      options.value=option;
      formConfig.id = option.id??'';
      formConfig.type = option.type;
      let title = getFormTitle(formConfig.type);
      routeTitle.value =title;
      uni.setNavigationBarTitle({title:title});
      formConfig.isView = false;
      if(formConfig.type==FromPageType.VIEW){
        formConfig.isView = true;
      }
    });
    async function submit(){
      let saveVal = await formRef.value.submit();
      if(saveVal){
        if(formConfig.type==FromPageType.ADD){
          uni.showToast({
            title: '新增成功'
          });
        }else  if(formConfig.type==FromPageType.EDIT){
          uni.showToast({
            title: '修改成功'
          });
        }
        uni.navigateTo({
          url: listProps.listUrl
        });
      }
    }
    async function reset(){
      formRef.value.reset();
    }
</script>

<style>
  page{
    background: #fff;
  }
</style>
`;
}
// 生成tag
export function buildTagStringCode(model: GeneratorConfig): string {
  const className = model.outputConfig.className;
  const lowerClassName = className?.toLowerCase();
  return `
	<sys-${model.outputConfig.outputValue}-${lowerClassName} ref="systemRef" v-else-if="componentName=='sys-${model.outputConfig.outputValue}-${lowerClassName}'" :disabled="props.disabled"  :isWorkFlow="true"   :workFlowParams="formConfig.workFlowParams"  :formModel="props.formModel"></sys-${model.outputConfig.outputValue}-${lowerClassName}>
  <!--html--> 
  `;
}
/**
 * 当前搜索项 是否需要转换
 * @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',
  'role',
  'tree-select-component',
];
