import { defineComponent, reactive, ref, getCurrentInstance, h, onMounted } from 'vue';
import { Alert, message, Modal, Space, Card, Divider, Row, Col, Tree, Input, Dropdown, Menu, MenuItem } from 'ant-design-vue';
import { DownOutlined, UpOutlined, UserOutlined } from '@ant-design/icons-vue';
import { VxeGridInstance, VxeGridListeners, VxeGridProps, Grid } from 'vxe-table';
import { mergeWith, isArray, isObject, isString, debounce } from 'lodash-es';
import { getSearchQueryData } from '@/utils/jhipster/entity-utils';
import { Button, Icon, useModalInner, BasicModal, useDrawerInner, BasicDrawer, SearchForm } from '@begcode/components';
import { useGo } from '@/hooks/web/usePage';
import ServerProvider from '@/api-service/index';
import { useRootSetting } from '@/hooks/setting/useRootSetting';
import <%= entityClass %>Edit from './<%= entityFileName %>-edit.vue';
import <%= entityClass %>Detail from './<%= entityFileName %>-detail.vue';

<%_ if (!useCommonTable) { _%>
import config from './config/list-config';
<%_ } else { _%>
import { xGenerateFilterTree, xGenerateSearchFormList, xGenerateTableColumns } from '@/utils/jhipster/entity-list-utils';
<%_ } _%>
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'import'}); -%>
<%_ } _%>
<%_
let apiModuleName = this._.camelCase(clientRootFolder || microserviceName);
_%>

// begcode-please-regenerate-this-file 如果您不希望重新生成代码时被覆盖，将please修改为don't ！！！

export default defineComponent({
  components: {
    Card,
    Button,
    Divider,
    SearchForm,
    DownOutlined,
    UpOutlined,
    UserOutlined,
    Icon,
    BasicModal,
    BasicDrawer,
    Space,
    Row,
    Col,
    Tree,
    Input,
    Dropdown,
    Menu,
    MenuItem,
    Grid,
    <%= entityClass%>Edit,
    <%= entityClass%>Detail,
  },
  props: {
    query: {
      type: Object,
      default: () => ({}),
    },
    editIn: {
      type: String,
      default: '',
    },
    baseData: {
      type: Object,
      default: () => ({}),
    },
    cardExtra: {
      type: Array,
      default: ['import', 'export', 'print'],
    },
    gridOptions: {
      type: Object,
      default: () => ({}),
    },
    searchFormOptions: {
      type: Object,
      default: () => ({
        disabled: false,
      }),
    },
    gridCustomConfig: {
      type: Object,
      default: () => ({
        hideOperations: false,
        hideSlots: [],
        hideColumns: [],
      }),
    },
  },
  async setup(props) {
    const [registerModal, { closeModal, setModalProps }] = useModalInner(data => {
      console.log(data);
    });
    const [registerDrawer, { closeDrawer, setDrawerProps }] = useDrawerInner(data => {
      console.log(data);
    });
    const modalComponentRef = ref<any>(null);
    const drawerComponentRef = ref<any>(null);
    const ctx = getCurrentInstance()?.proxy;
    const go = useGo();
    const apiService = ctx?.$apiService as typeof ServerProvider;
    const { getPageSetting } = useRootSetting();
    const relationshipApis: any = {
    <%_ for (relationship of relationships) {
        const relationApiModuleName = this._.camelCase(relationship.otherEntity.clientRootFolder || relationship.otherEntity.microserviceName);
    _%>
      <%= relationship.relationshipName %>: apiService<%= relationApiModuleName ?  '.' + relationApiModuleName : ''%>.<%= relationship.otherEntity.entityInstance%>Service.<%= relationship.otherEntity.fieldsContainParentAndChildren ? 'tree' : 'retrieve'%>,
    <%_ } _%>
    }
    const apis = {
      <%= entityInstance %>Service: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service,
      find: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.<%= fieldsContainParentAndChildren ? 'tree' : 'retrieve'%>,
      deleteById: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.delete,
      deleteByIds: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.deleteByIds,
      update: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.update,
    <%_ if (softDelete && !skipSoftDelete) { _%>
      recycleBin: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.recycleBin,
      restoreByIds: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.restoreByIds,
      reallyDelete: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.reallyDelete,
      emptyRecycleBin: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.emptyRecycleBin,
      findInRecycleBin: apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.findInRecycleBin,
    <%_ } _%>
    };
    const pageConfig = {
      title: '<%= bcTitle %>列表',
      baseRouteName: '<%= (moduleName || clientRootFolder) ? (moduleName || clientRootFolder) + entityAngularName : entityInstance %>',
    };
    <%_ if (useCommonTable) { _%>
    const commonTableData = await apiService.modelConfig.commonTableService.findByEntityName('<%= entityNameCapitalized %>')
    const columns = xGenerateTableColumns(commonTableData);
    // const editInModal = commonTableData.editInModal;
    const searchFormFields = xGenerateSearchFormList(commonTableData, relationshipApis);
    <%_ } else { _%>
    const columns = config.columns();
    const searchFormFields = config.searchForm();
    if (columns && columns.length && Object.keys(relationshipApis).length) {
      columns
        .filter(item => item.field && Object.keys(relationshipApis).includes(item.field))
        .forEach(item => {
          item.editRender = {
            ...item.editRender,
            props: {
              ...item.editRender?.props,
              api: relationshipApis[item.field!],
            },
          };
        });
    }
    if (props.gridCustomConfig?.hideColumns?.length > 0) {
      const filterColumns = columns
        .filter(column => !props.gridCustomConfig.hideColumns.includes(column.field));
      columns.length = 0;
      columns.push(...filterColumns);
    }
    <%_ } _%>
    <%_ if (softDelete && !skipSoftDelete) { _%>
    const showRecycleBin = ref<Boolean>(false);
    <%_ } _%>
    const xGrid = ref({} as VxeGridInstance);
    const searchInputRef = ref(null);
    const searchFormConfig = reactive(Object.assign({
      fieldList: searchFormFields,
      toggleSearchStatus: false,
      useOr: false,
      disabled: false,
      allowSwitch: true,
    }, props.searchFormOptions));
    const batchOperations = [];
    let rowOperations = [
      {
        disabled: false,
        name: 'save',
        type: getPageSetting.value.buttonType || 'link',
      },
      <%_ if (fieldsContainParentAndChildren) { _%>
      {
        title: '下级',
        name: 'addChildren',
        containerType: 'modal',
        type: getPageSetting.value.buttonType || 'link',
      },
      <%_ } _%>
      {
        name: 'delete',
        type: getPageSetting.value.buttonType || 'link',
      },
      {
        title: '详情',
        name: 'detail',
        containerType: 'drawer',
        type: getPageSetting.value.buttonType || 'link',
      },
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'rowOperations'}); -%>
<%_ } _%>
    ];
    if (props.gridCustomConfig?.rowOperations && isArray(props.gridCustomConfig.rowOperations)) {
      if (props.gridCustomConfig.rowOperations.length === 0) {
        rowOperations = [];
      } else {
        rowOperations = rowOperations
          .filter(item =>
            props.gridCustomConfig.rowOperations.some(rowItem =>
              isObject(rowItem) ? item.name === rowItem['name'] : item.name === rowItem
            )
          );
      }
    }
    const tableRowOperations = reactive<any[]>([]);
    const tableRowMoreOperations = reactive<any[]>([]);
    const saveOperation = rowOperations.find(operation => operation.name === 'save');
    if (rowOperations.length > 4 || (saveOperation && rowOperations.length > 3)) {
    if (saveOperation) {
      tableRowOperations.push(...rowOperations?.slice(0, 3));
      tableRowMoreOperations.push(...rowOperations.slice(3));
    } else {
      tableRowOperations.push(...rowOperations?.slice(0, 4));
      tableRowMoreOperations.push(...rowOperations.slice(4));
    }
    } else {
    tableRowOperations.push(...rowOperations);
    }
    const selectedRows = reactive<any>([]);
    const loading = ref(false);
    const searchFormRef = ref<any>(null);
    const searchValue = ref('');
    const mapOfFilter = reactive({});
    const mapOfSort: { [key: string]: any } = reactive({});
    columns?.forEach(column => {
      if (column.sortable && column.field) {
        mapOfSort[column.field] = false;
      }
    });
  const sort= () => {
    const result: any[] = [];
    Object.keys(mapOfSort).forEach(key => {
      if (mapOfSort[key] && mapOfSort[key] !== false) {
        if (mapOfSort[key] === 'asc') {
          result.push(key + ',asc');
        } else if (mapOfSort[key] === 'desc') {
          result.push(key + ',desc');
        }
      }
    });
    return result;
  };
    const treeFilterData = <% if (useCommonTable) { %>xGenerateFilterTree(commonTableData, relationshipApis)<% } else { %>[]<% } %>;
    const filterTreeConfig = reactive({
      filterTreeSpan: treeFilterData && treeFilterData.length > 0 ? 6 : 0,
      treeFilterData,
      expandedKeys: [],
      checkedKeys: [],
      selectedKeys: [],
      autoExpandParent: true,
    });
    const modalConfig = reactive<any>({
      componentName: '',
      entityId: '',
      containerType: 'modal',
      baseData: props.baseData,
      width: '80%',
      destroyOnClose: true,
    });
    const drawerConfig = reactive<any>({
      componentName: '',
      containerType: 'drawer',
      entityId: '',
      baseData: props.baseData,
      width: '30%',
      destroyOnClose: true,
    });
    const gridOptions = reactive<VxeGridProps>({
      ...config.baseGridOptions(),
      customConfig: {
        storage: true,
        checkMethod({ column }) {
          return !['nickname', 'role'].includes(column.field);
        },
      },
      proxyConfig: {
        enabled: true,
        autoLoad: true,
        seq: true,
        sort: true,
        filter: true,
        props: {
          result: 'records',
          total: 'total',
        },
        ajax: {
          query: async ({ filters, page, sort, sorts }) => {
            console.log('filters', filters);
            console.log('sorts', sorts);
            const queryParams: any = {<% if (useCommonTable) { %>listModelName: '<%= entityClass %>'<% } else { %>...props.query<% } %>};
            queryParams.page = page?.currentPage > 0 ? page.currentPage - 1 : 0;
            queryParams.size = page?.pageSize;
            if (sort && sort.field) {
              queryParams.sort = [sort.field + ',' + (sort.order === 'desc' ? 'DESC' : 'ASC')];
            }
            if (searchValue.value) {
              queryParams['jhiCommonSearchKeywords'] = searchValue.value;
            } else {
              Object.assign(queryParams, getSearchQueryData(searchFormConfig));
            }
            <%_ if (softDelete && !skipSoftDelete) { _%>
            if (showRecycleBin.value) {
              return await apis.recycleBin(queryParams);
            } else {
              return await apis.find(queryParams);
            }
            <%_ } else { _%>
            return await apis.find(queryParams);
            <%_ } _%>
          },
          queryAll: async () => await apis.find({ size: -1 }),
          <%_ if (softDelete && !skipSoftDelete) { _%>
          delete: async (records) => {
            if (showRecycleBin.value) {
              return await apis.reallyDelete(records.body.removeRecords.map(record => record.<%= primaryKey.name %>));
            } else {
              return await apis.deleteByIds(records.body.removeRecords.map(record => record.<%= primaryKey.name %>));
            }
          },
          <%_ } else { _%>
          delete: async (records) => await apis.deleteByIds(records.body.removeRecords.map(record => record.<%= primaryKey.name %>)),
          <%_ } _%>
        },
      },
      toolbarConfig: {
        custom: true,
        import: false,
        print: false,
        export: false,
        slots: {
          buttons: 'toolbar_buttons',
        },
        // 表格左上角自定义按钮
        buttons: [
          { name: '批量操作', circle: false, icon: 'vxe-icon-add', status: 'primary',
            dropdowns: [
              { code: 'batchDelete', name: '删除', circle: false, icon: 'ant-design:delete-filled', status: 'primary' },
            ],
          },
        ],
        // 表格右上角自定义按钮
        tools: [
        <%_ if (skipWebButton.indexOf('listAdd') === -1) { _%>
          { code: 'new', name: '新增', circle: false, icon: 'vxe-icon-add'},
        <%_ } _%>
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'tools'}); -%>
<%_ } _%>
        ],
      },
      columns,
    });
    gridOptions!.pagerConfig!.slots = {
      left: () => {
        return h(Alert, {type: 'warning', banner: true, message: `已选择 ${selectedRows.length} 项`, style: 'height: 30px'});
      },
    };
    mergeWith(gridOptions, props.gridOptions, (objValue: any, srcValue: any, key: any) => {
      if (isArray(objValue) && ['buttons', 'tools'].includes(key)) {
        if (!srcValue) {
          return objValue;
        } else if (isArray(srcValue) && srcValue.length === 0) {
          return srcValue;
        } else if (isArray(srcValue) && srcValue.length > 0) {
          const newObjValue: any[] = [];
          srcValue.forEach((srcItem: any) => {
            if (isObject(srcItem)) {
              const objItem = objValue.find(item => item.code === srcItem['code']) || {};
              newObjValue.push(Object.assign(objItem, srcItem));
            } else if (isString(srcItem)) {
              const objItem = objValue.find(item => item.code === srcItem);
              objItem && newObjValue.push(objItem);
            }
          })
          return newObjValue;
        }
      }
    });
    const gridEvents = reactive<VxeGridListeners>({
      checkboxAll: () => {
        const $grid = xGrid.value
        selectedRows.length = 0;
        selectedRows.push(...$grid.getCheckboxRecords());
      },
      checkboxChange: () => {
        const $grid = xGrid.value;
        selectedRows.length = 0;
        selectedRows.push(...$grid.getCheckboxRecords());
      },
      pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
          gridOptions.pagerConfig.currentPage = currentPage;
          gridOptions.pagerConfig.pageSize = pageSize;
        }
      },
      radioChange() {
        const $grid = xGrid.value;
        selectedRows.length = 0;
        selectedRows.push($grid.getRadioRecord());
      },
      // 表格左上角按钮事件
      toolbarButtonClick ({ code }) {
        const $grid = xGrid.value;
        switch (code) {
          case 'batchDelete': {
            const records = $grid.getCheckboxRecords(true);
            if (records?.length > 0) {
              const ids = records.map(record => record.<%= primaryKey.name %>);
              Modal.confirm({
                title: `操作提示`,
                content: `是否删除ID为【${ids.join(',')}】的${records.length}项数据？`,
                onOk() {
                  apis.deleteByIds(ids).then(() => {
                    formSearch();
                  });
                },
              });
            }
            break;
          }
          case 'mySave': {
            break
          }
          case 'myExport': {
            break
          }
        }
      },
      // 表格右上角自定义按钮事件
      toolbarToolClick({ code }) {
        switch (code) {
          <%_ if (skipWebButton.indexOf('listAdd') === -1) { _%>
          case 'new':
            if (props.editIn === 'modal') {
              modalConfig.componentName = '<%= entityFileName %>-edit';
              modalConfig.entityId = '';
              setModalProps({ open: true });
            } else if (props.editIn === 'drawer') {
              drawerConfig.componentName = '<%= entityFileName %>-edit';
              drawerConfig.entityId = '';
              setDrawerProps({ open: true });
            } else {
              <%_ if (skipMenu) { _%>
                console.log('未定义方法');
              <%_ } else { _%>
              if (pageConfig.baseRouteName) {
                go({ name: `${pageConfig.baseRouteName}New` });
              } else {
                console.log('未定义方法');
              }
              <%_ } _%>
            }
            break;
          <%_ } _%>
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'toolbarToolClick'}); -%>
<%_ } _%>
        }
      },
      editClosed({ row, column }) {
        const field = column.property;
        const cellValue = row[field];
        // 判断单元格值是否被修改
        if (xGrid.value.isUpdateByRow(row, field)) {
          const entity = { id: row.id };
          entity[field] = cellValue;
          apis
            .update(entity, [row.id],[field])
            .then(() => {
              message.success({
                content: `信息更新成功。 ${field}=${cellValue}`,
                duration: 1,
              });
              xGrid.value.reloadRow(row, null, field);
            })
            .catch(error => {
              console.log('error', error);
              message.error({
                content: `信息保存可能存在问题！ ${field}=${cellValue}`,
                onClose: () => {},
              });
            });
        }
      },
    });
    const okModal = () => {
      if (modalConfig.containerType === 'modal') {
        if (modalComponentRef.value) {
          modalComponentRef.value.saveOrUpdate();
          formSearch();
        }
      }
    };
    const okDrawer = () => {
      if (drawerConfig.containerType === 'drawer') {
        if (drawerComponentRef.value) {
          drawerComponentRef.value.saveOrUpdate();
          formSearch();
        }
      }
    };
    const formSearch = () => {
      xGrid.value.commitProxy('reload');
    };
    const inputSearch = debounce(formSearch, 700);
    onMounted(() => {
      const $grid: HTMLElement = (xGrid.value.$el) as HTMLElement;
      const myElement = $grid.querySelector('.vxe-toolbar .vxe-custom--wrapper .vxe-button.type--button');
      if (myElement?.className) {
        myElement.className = myElement.className.replace('is--circle', '')
        myElement.setAttribute('style', 'border-radius: 4px !important;')
      }

      const parent = myElement?.parentElement;
      if (parent) {
        parent.className = parent.className + ' begcode'
      }
      const text = document.createElement('span');
      text.className = 'vxe-button--content'
      text.innerText = '列配置'
      myElement?.appendChild(text);
    })
    return {
      sort,
      searchFormConfig,
      selectedRows,
      loading,
      mapOfFilter,
      mapOfSort,
      filterTreeConfig,
      searchValue,
      xGrid,
      searchInputRef,
      tableRowOperations,
      tableRowMoreOperations,
      modalConfig,
      registerModal,
      closeModal,
      closeDrawer,
      setModalProps,
      drawerConfig,
      registerDrawer,
      setDrawerProps,
      go,
      gridEvents,
      gridOptions,
      batchOperations,
      apis,
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'setupReturn'}); -%>
<%_ } _%>
      pageConfig,
      searchFormRef,
<%_ if (softDelete && !skipSoftDelete) { _%>
      showRecycleBin,
<%_ } _%>
      okDrawer,
      okModal,
      formSearch,
      modalComponentRef,
      drawerComponentRef,
    };
  },
  methods: {
    handleToggleSearch(): void {
      this.searchFormConfig.toggleSearchStatus = !this.searchFormConfig.toggleSearchStatus;
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys);
      this.filterTreeConfig.checkedKeys = checkedKeys;
    },
    showSearchFormSetting() {
      if (this.searchFormRef) {
        this.searchFormRef.showSettingModal();
      }
    },
    onSelect(selectedKeys, info) {
      const filterData = info.node.dataRef;
      if (filterData.type === 'filterGroup') {
        this.mapOfFilter[info.node.dataRef.key].value = [];
      } else if (filterData.type === 'filterItem') {
        this.mapOfFilter[info.node.dataRef.filterName].value = [info.node.dataRef.filterValue];
      }
      this.formSearch();
      this.filterTreeConfig.selectedKeys = selectedKeys;
    },
    switchFilterTree() {
      this.filterTreeConfig.filterTreeSpan = this.filterTreeConfig.filterTreeSpan > 0 ? 0 : 6;
    },
    rowMoreClick(e, row) {
      const { key } = e;
      const operation = this.tableRowMoreOperations.find(operation => operation.name === key);
      this.rowClickHandler(key, operation, row);
    },
    rowClick(name, row) {
      const operation = this.tableRowOperations.find(operation => operation.name === name);
      this.rowClickHandler(name, operation, row);
    },
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'method'}); -%>
<%_ } _%>
    rowClickHandler(name, operation, row) {
      // eslint-disable-next-line @typescript-eslint/no-this-alias
      const _this = this;
      switch (name) {
        case 'save':
          break;
        case 'edit':
          if (operation) {
            if (operation.click) {
              operation.click(row);
            } else {
              const containerType = _this.editIn || operation.containerType;
              switch (containerType) {
                case 'modal':
                  this.modalConfig.componentName = '<%= entityFileName %>-edit';
                  this.modalConfig.entityId = row.<%= primaryKey.name %>;
                  this.setModalProps({ open: true });
                  break;
                case 'drawer':
                  this.drawerConfig.componentName = '<%= entityFileName %>-edit';
                  this.drawerConfig.entityId = row.<%= primaryKey.name %>;
                  this.drawerConfig.title = '编辑';
                  this.setDrawerProps({ open: true });
                  break;
                case 'route':
                default:
                  if (this.pageConfig.baseRouteName) {
                    this.go({ name: `${this.pageConfig.baseRouteName}Edit`, params: { entityId: row.id } });
                  } else {
                    console.log('未定义方法');
                  }
              }
            }
          } else {
            switch (_this.editIn) {
                case 'modal':
                  this.modalConfig.componentName = '<%= entityFileName %>-edit';
                  this.modalConfig.entityId = row.<%= primaryKey.name %>;
                  this.setModalProps({ open: true });
                  break;
                case 'drawer':
                  this.drawerConfig.componentName = '<%= entityFileName %>-edit';
                  this.drawerConfig.entityId = row.<%= primaryKey.name %>;
                  this.setDrawerProps({ open: true });
                  break;
                case 'route':
                default:
                  if (this.pageConfig.baseRouteName) {
                    this.go({ name: `${this.pageConfig.baseRouteName}Edit`, params: { entityId: row.id } });
                  } else {
                    console.log('未定义方法');
                  }
              }
          }
          break;
        case 'detail':
          if (operation) {
            if (operation.click) {
              operation.click(row);
            } else {
              switch (operation.containerType) {
                case 'modal':
                  this.modalConfig.componentName = '<%= entityFileName %>-detail';
                  this.modalConfig.entityId = row.<%= primaryKey.name %>;
                  this.modalConfig.title = '详情';
                  this.setModalProps({ open: true });
                  break;
                case 'drawer':
                  this.drawerConfig.componentName = '<%= entityFileName %>-detail';
                  this.drawerConfig.entityId = row.<%= primaryKey.name %>;
                  this.drawerConfig.title = '详情';
                  this.setDrawerProps({ open: true });
                  break;
                case 'route':
                default:
                  if (this.pageConfig.baseRouteName) {
                    this.go({ name: `${this.pageConfig.baseRouteName}Detail`, params: { entityId: row.id } });
                  } else {
                    console.log('未定义方法');
                  }
              }
            }
          } else {
            if (this.pageConfig.baseRouteName) {
              this.go({ name: `${this.pageConfig.baseRouteName}Detail`, params: { entityId: row.id } });
            } else {
              console.log('未定义方法');
            }
          }
          break;
        <%_ if (fieldsContainParentAndChildren) { _%>
        case 'addChildren':
          if (operation) {
            if (operation.click) {
              operation.click(row);
            } else {
              switch (operation.containerType) {
              case 'modal':
                this.modalConfig.componentName = '<%= entityFileName %>-edit';
                this.modalConfig.entityId = '';
                this.modalConfig.baseData = { parentId: row.id, parent: row };
                this.modalConfig.title = '添加下级';
                this.setModalProps({ open: true });
              break;
              case 'drawer':
                this.drawerConfig.componentName = '<%= entityFileName %>-edit';
                this.drawerConfig.entityId = '';
                this.drawerConfig.baseData = { parentId: row.id, parent: row };
                this.drawerConfig.title = '添加下级';
                this.setDrawerProps({ open: true });
                break;
              case 'route':
              default:
                if (this.pageConfig.baseRouteName) {
                  this.go({ name: `${this.pageConfig.baseRouteName}New`, query: { parentId: row.id, parent: row } });
                } else {
                  console.log('未定义方法');
                }
              }
            }
          } else {
            if (this.pageConfig.baseRouteName) {
              this.go({ name: `${this.pageConfig.baseRouteName}New`, query: { parentId: row.id, parent: row } });
            } else {
              console.log('未定义方法');
            }
          }
          break;
        <%_ } _%>
        case 'delete':
          Modal.confirm({
            title: `操作提示`,
            content: `是否确认删除ID为${row.id}的记录？`,
            onOk() {
              if (operation.click) {
                operation.click(row);
              } else {
                 _this.apis.deleteById(row.id).then(() => {
                  _this.formSearch();
                });
              }
            },
          });
          break;
<%_ if (addCustomMethod.indexOf('listComponent') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.listComponent.ejs`, {position: 'rowClickHandler'}); -%>
<%_ } _%>
        default:
          if (operation) {
            if (operation.click) {
              operation.click(row);
            } else {
              console.log('error', `click方法未定义`);
            }
          } else {
            console.log('error', `${name}未定义`);
          }
      }
    },
  },
});
