<%_
const oneToOneNotOwnerSide =[];
let hasUseJPADerivedIdentifier = false;
const { formFieldLines, showInOneRelationships, showInOneImportComponents, showInOneContainerConfig } = (bcEntityData || { formFieldLines: [], showInOneRelationships: [], showInOneImportComponents: {}});
_%>
<template>
  <div :class="containerType === 'page' ? ['pb-44px'] : []"<% if (cypressTests) { %> data-cy="<%= entityAngularName %>CreateUpdateHeading"<% } %>>
  <%_ if (showInOneRelationships && showInOneRelationships.length) { _%>
    <%_ if (!showInOneContainerConfig.showBaseInfo) { _%>
    <basic-form ref="formRef" v-bind="formProps">
      <template #resetBefore>
        <teleport to='[data-teleport="<%= entityModelFileName %>-edit-append-button"]' defer>
          <a-space>
            <basic-button v-for="operation in operations" :type="operation.type" @click="operation.click" v-bind="operation.attrs">
              <Icon :icon="operation.icon" v-if="operation.icon" />
              {{ operation.title }}
            </basic-button>
          </a-space>
        </teleport>
      </template>
    </basic-form>
    <%_ } _%>
  <<%= showInOneContainerConfig.componentName %> v-model:active-key="relationTables.activeKey" @change="changeActiveKey">
    <%_ if (showInOneContainerConfig.showBaseInfo) { _%>
    <<%= showInOneContainerConfig.subComponentName %> <%= showInOneContainerConfig.subLabelName %>="基本信息" key="baseInfo">
    <basic-form ref="formRef" v-bind="formProps">
      <template #resetBefore>
        <teleport to='[data-teleport="<%= entityModelFileName %>-edit-append-button"]' defer>
          <a-space>
            <basic-button v-for="operation in operations" :type="operation.type" @click="operation.click" v-bind="operation.attrs">
              <Icon :icon="operation.icon" v-if="operation.icon" />
              {{ operation.title }}
            </basic-button>
          </a-space>
        </teleport>
      </template>
    </basic-form>
    </<%= showInOneContainerConfig.subComponentName %>>
    <%_ } _%>
    <%_ showInOneRelationships.forEach(relationship => { _%>
    <<%= showInOneContainerConfig.subComponentName %> :<%= showInOneContainerConfig.subLabelName %>="relationTables.<%= relationship.relationTableKey %>.title" :key="relationTables.<%= relationship.relationTableKey %>.name"<% if (showInOneContainerConfig.subComponentName === 'a-tab-pane') { %> :disabled="relationTables.<%= relationship.relationTableKey %>.disabled()"<% } else { %>:collapsible="relationTables.<%= relationship.relationTableKey %>.disabled() ? 'disabled' : undefined"<% } %>>
      <<%= relationship.componentTypeName %> ref="<%= relationship.relationTableKey %>Ref" v-bind="relationTables.<%= relationship.relationTableKey %>.props()" v-on="relationTables.<%= relationship.relationTableKey %>.events">
        <%_ if (relationship.source?.annotationOnSource?.includes('editByDescList')) { _%>
        <template #default="{ item }">
          <<%= relationship.otherEntity.entityNameCapitalized %>Desc :entity-id="item.<%= relationship.otherEntity.primaryKey.name %>"<% if (!anyFieldIsBlobDerived) { %> :columns="3"<% } %><% if (extendAbstractAuditingEntity) { %> :hide-columns="['createdBy', 'createdDate', 'lastModifiedBy', 'lastModifiedDate'<% if (relationship.otherRelationship?.relationshipName) { %>, '<%= relationship.otherRelationship.relationshipName + '.' + relationship.otherRelationship.otherEntityField %>'<% } %>]"<% } %> />
        </template>
        <%_ } _%>
      </<%= relationship.componentTypeName %>>
    </<%= showInOneContainerConfig.subComponentName %>>
    <%_ }); _%>
  </<%= showInOneContainerConfig.componentName %>>
  <%_ } else { _%>
    <basic-form ref="formRef" v-bind="formProps">
      <template #resetBefore>
        <teleport to='[data-teleport="<%= entityModelFileName %>-edit-append-button"]' defer>
          <a-space>
            <basic-button v-for="operation in operations" :type="operation.type" @click="operation.click" v-bind="operation.attrs">
              <Icon :icon="operation.icon" v-if="operation.icon" />
              {{ operation.title }}
            </basic-button>
          </a-space>
        </teleport>
      </template>
    </basic-form>
  <%_ } _%>
  </div>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue';
import config from '../config/edit-config';
import { <%= entityAngularName %>, I<%= entityAngularName %> } from '@/models/<%= entityModelFileName %>.model';
import ServerProvider from '@/api-service/index';
<%_ if (showInOneImportComponents && Object.keys(showInOneImportComponents).length) { _%>
  <%_ Object.values(showInOneImportComponents).forEach(importLine => { _%>
<%- importLine %>
  <%_ });_%>
<%_  } _%>
<%_ if (addCustomMethod.indexOf('updateTemplate') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'componentImport'}); -%>
<%_ } _%>

<%_
let apiModuleName = this._.camelCase(clientRootFolder || microserviceName);
const componentName = this._.upperFirst((moduleName || clientRootFolder) ? (moduleName || clientRootFolder) + entityAngularName : entityAngularName) + 'Edit';
_%>
// begcode-please-regenerate-this-file 如果您不希望重新生成代码时被覆盖，将please修改为don't ！！！
defineOptions({
  name: '<%= componentName %>',
  inheritAttrs: false,
});

const props = defineProps({
  entityId: {
    type: [String, Number] as PropType<string | number>,
    default: '',
  },
  containerType: {
    type: String,
    default: 'page',
  },
  formButtons: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
  baseData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(['cancel', 'update-save-button']);

const operations = ref<any[]>([]);

const ctx = getCurrentInstance()?.proxy;
const formRef = ref<any>(null);
<%_ showInOneRelationships && showInOneRelationships.forEach(relationship => { _%>
const <%= relationship.relationTableKey %>Ref = ref<any>(null);
<%_ }); _%>
const apiService = ctx?.$apiService as typeof ServerProvider;
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 <%= entityInstance %>Id = ref<any>(null);
const <%= entityInstance %> = reactive<I<%= entityAngularName %>>(new <%= entityAngularName %>());
const getEntityData = async (entityId: string | number) => {
    if (entityId) {
      <%= entityInstance %>Id.value = entityId;
      const data = await apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.find(<% if (tsKeyType === 'number') { %>Number(entityId)<% } else { %>entityId<% } %>).catch(() => null);
      if (data) {
        Object.assign(<%= entityInstance %>, data);
      }
    } else {
      Object.assign(<%= entityInstance %>, props.baseData);
    }
  };
watch(
  () => props.entityId,
  getEntityData,
  { immediate: true },
);
const formItemsConfig = config.fields(relationshipApis);
<%_ if (addCustomMethod.indexOf('editComponent') !== -1) { _%>
<%- include(`../../common/entity-custom/${entityClass}.editComponent.ejs`, {position: 'fieldsConfig'}); -%>
<%_ } _%>
<%_ if (addCustomMethod.indexOf('updateTemplate') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'componentField'}); -%>
<%_ } _%>

const isEdit = computed(() => { return true;});

const submitButtonTitlePrefix = props.entityId ? '更新' : '保存';
const saveOrUpdateApi = props.entityId
  ? apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.update
  : apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.create;
const submit = async (config = {submitToServer: true}) => {
  const result = await validate()
    .catch(err => {
      console.log('validate.error:', err);
      return { success: false, data: {}};
    });
  if (result.success) {
    Object.assign(<%= entityInstance %>, result.data);
    <%_ if (addCustomMethod.indexOf('updateTemplate') !== -1) { _%>
    <%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'before-save'}); -%>
    <%_ } _%>
    if (!config.submitToServer) {
      return <%= entityInstance %>;
    }
    const saveData = await saveOrUpdateApi(<%= entityInstance %>).catch(() => false);
    if (saveData) {
      Object.assign(<%= entityInstance %>, saveData);
      message.success(submitButtonTitlePrefix + '成功！');
      return saveData;
    } else {
      message.error(submitButtonTitlePrefix + '失败！');
      return false;
    }
  } else {
    message.error('数据验证失败！');
    return false;
  }
};
  const validate = async () => {
    const result = {
      success: true,
      data: {},
      errors: [] as any[],
    };
    const formValidResult = await formRef.value?.validate();
    if (!formValidResult) {
      result.success = false;
      result.errors.push('表单校验未通过！');
    } else {
      result.data = { ...result.data, ...formValidResult };
    }
    <%_ showInOneRelationships && showInOneRelationships.forEach(relationship => { _%>
    if (<%= relationship.relationTableKey %>Ref.value) {
      const <%= relationship.relationTableKey %>Result = await <%= relationship.relationTableKey %>Ref.value?.validate();
      if (!<%= relationship.relationTableKey %>Result) {
        result.success = false;
        result.errors.push('<%= relationship.bcTitle %>校验未通过！');
      } else {
        <%_ if (relationship.bcConfig?.leftEditByFormList || relationship.bcConfig.leftEditByDescList) { _%>
        result.data = { ...result.data, ...<%= relationship.relationTableKey %>Result };
        <%_ } else { _%>
        result.data = { ...result.data, ...{ <%= relationship.relationshipName %>: <%= relationship.relationTableKey %>Result} };
        <%_ } _%>
      }
    }
    <%_ }); _%>
    return result;
  };

  const formProps = reactive({
    labelWidth: '120px',
    compact: true,
    alwaysShowLines: 1,
    fieldMapToTime: [],
    size: 'default',
    showAdvancedButton: false,
    showResetButton: props.formButtons.includes('reset'),
    showSubmitButton: props.formButtons.includes('submit'),
    showActionButtonGroup: props.formButtons.length > 0,
    model: <%= entityInstance %>,
    schemas: formItemsConfig,
    disabled: !isEdit.value,
    resetButtonOptions: {
      type: 'default',
      size: 'default',
      text: '重置',
      preIcon: null,
    },
    actionColOptions: {
      span: 24,
      style: {
        textAlign: 'right',
        borderTop: '1px solid #e8e8e8',
        paddingTop: '10px',
      },
    },
    submitButtonOptions: {
      type: 'primary',
      size: 'default',
      text: submitButtonTitlePrefix,
      preIcon: null,
    },
    resetFunc: () => {
      emit('cancel', { update: false, containerType: props.containerType });
    },
    submitFunc: submit,
  });
  <%_
  let sortModelName = '';
  _%>
  <%_ if (showInOneRelationships && showInOneRelationships.length) { _%>
  const relationTables = reactive({
    <%_ if (showInOneContainerConfig.showBaseInfo) { _%>
    activeKey: 'baseInfo',
    <%_ } else { _%>
    activeKey: '<%= showInOneRelationships[0].relationTableKey %>',
    <%_ } _%>
    <%_ showInOneRelationships.forEach(relationship => { _%>
      <%_ if (relationship.source?.annotationOnSource?.includes('editByList')) { _%>
    <%= relationship.relationTableKey %>: {
      name: '<%= relationship.relationTableKey %>',
      title: '<%= relationship.bcTitle%>',
      props: () => ({
        cardSlots: [''],
        deleteRelationType: '<%= relationship.source?.annotationOnSource?.includes('unidirectional') && relationship.relationshipManyToMany && relationship.relationshipLeftSide ? 'cancel' : 'delete'%>',
        <%_ if (relationship.options?.source?.annotationOnSource?.includes('relateByIdEntity')) { _%>
        query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
        <%_ } else { _%>
        query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
        <%_ } _%>
        editIn: 'modal',
        <%_ if (relationship.source?.annotationOnSource?.includes('relateByIdEntity')) { _%>
        baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
        <%_ } else { _%>
        baseData: { <%= relationship.otherRelationship.relationshipName%>: {<%= relationship.otherEntity.primaryKey.name %>: <%= entityInstance %>Id.value } },
        <%_ } _%>
        gridOptions: {
          toolbarConfig: {
            import: true,
            print: true,
            export: true,
          },
        },
        searchFormOptions: {
          disabled: false,
          allowSwitch: false,
        },
        gridCustomConfig: {
          tools: [''],
          hideOperations: false,
          hideSlots: [],
          columnsName: '',
        },
        modelName: '<%= relationship.otherEntity.entityNameCapitalized %>List',
      }),
      disabled: () => {
        return !<%= entityInstance %>.id;
      },
      events: {},
    },
          <%_ } else　if (relationship.source?.annotationOnSource?.includes('editByFormList') || relationship.destination?.annotationOnDestination?.includes('editByFormList')) { _%>
      <%= relationship.relationTableKey %>: {
          name: '<%= relationship.relationTableKey %>',
          title: '<%= relationship.bcTitle%>',
          props: () => ({
            cardSlots: [''],
            <% if (relationship.relationshipOneToOne) { %>multiple: false,<% } else { %>multiple: true,<% } %>
            deleteRelationType: '<%= relationship.source?.annotationOnSource?.includes('unidirectional') && relationship.relationshipManyToMany && relationship.relationshipLeftSide ? 'cancel' : 'delete'%>',
              <%_ if (relationship.source?.annotationOnSource?.includes('relateByIdEntity')) { _%>
            query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
              <%_ } _%>
            editIn: 'modal',
              <%_ if (relationship.source?.annotationOnSource?.includes('relateByIdEntity')) { _%>
            baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            baseData: { <%= relationship.otherRelationship.relationshipName%>: {<%= relationship.otherEntity.primaryKey.name %>: <%= entityInstance %>Id.value } },
              <%_ } _%>
            formConfig: { schemas: config.<%= relationship.relationshipName %>Columns() },
            fieldName: '<%= relationship.relationshipName %>',
            fieldData: <% if (relationship.relationshipOneToOne) { %>[<%= entityInstance %>.<%= relationship.relationshipName %>]<% } else { %><%= entityInstance %>.<%= relationship.relationshipName %><% } %>,
            modelName: 'FormList',
          }),
          disabled: () => {
            return !<%= entityInstance %>.id;
          },
          events: {},
        },
          <%_ } else　if (relationship.source?.annotationOnSource?.includes('editByDescList')) { _%>
      <%= relationship.relationTableKey %>: {
          name: '<%= relationship.relationTableKey %>',
          title: '<%= relationship.bcTitle%>',
          props: () => ({
            cardSlots: [''],
            deleteRelationType: '<%= relationship.source?.annotationOnSource?.includes('unidirectional') && relationship.relationshipManyToMany && relationship.relationshipLeftSide ? 'cancel' : 'delete'%>',
              <%_ if (relationship.source?.annotationOnSource?.includes('relateByIdEntity')) { _%>
            query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
              <%_ } _%>
            editIn: 'modal',
              <%_ if (relationship.source?.annotationOnSource?.includes('relateByIdEntity')) { _%>
            baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            baseData: { <%= relationship.otherRelationship.relationshipName%>: {<%= relationship.otherEntity.primaryKey.name %>: <%= entityInstance %>Id.value } },
              <%_ } _%>
            configData: [
              {
                formConfig: config.<%= relationship.relationshipName %>Columns,
                data: {},
              }
            ],
            fieldName: '<%= relationship.relationshipName %>',
            data: toRaw(<%= entityInstance %>.<%= relationship.relationshipName %>),
            toolButtons: [],
            editComponentPath: '@/views/<%= relationship.otherEntity.entityFolderName%>/components/form-component.vue',
            modelName: 'DescList',
          }),
          events: {
            refresh: async () => {
              await getEntityData(<%= entityInstance %>Id.value);
            },
            delete: async <%= relationship.otherEntity.entityInstance %> => {
              <%_ let otherApiModuleName = this._.camelCase(relationship.otherEntity.clientRootFolder || relationship.otherEntity.microserviceName); _%>
              await apiService.<%= otherApiModuleName ? otherApiModuleName + '.' : '' %><%= relationship.otherEntity.entityInstance %>Service.delete(<%= relationship.otherEntity.entityInstance %>.<%= relationship.otherEntity.primaryKey.name %>);
              await getEntityData(<%= entityInstance %>Id.value);
            },
          },
          disabled: () => {
            return !<%= entityInstance %>.<%= primaryKey.name %>;
          },
        },
          <%_ } else {
              sortModelName = relationship.relationshipName;
          _%>
      <%= relationship.relationTableKey %>: {
          name: '<%= relationship.relationTableKey %>',
          title: '<%= relationship.bcTitle%>',
          props: () => ({
            cardSlots: [''],
            modelName: '<%= relationship.relationshipName%>',
            relationData: toRaw(<%= entityInstance %>['<%= relationship.relationshipName%>']),
            deleteRelationType: '<%= relationship.bcConfig?.leftUnidirectional && relationship.relationshipManyToMany && relationship.relationshipLeftSide ? 'cancel' : 'delete'%>',
            columns: config.<%= relationship.relationshipName%>Columns(),
            <%_ if (!(relationship.bcConfig?.leftUnidirectional && relationship.relationshipManyToMany && relationship.relationshipLeftSide)) { _%>
              <%_ if (relationship?.bcConfig?.leftRelateByIdEntity) { _%>
            query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
              <%_ } _%>
            <%_ } _%>
            <%_ if (!(relationship.bcConfig?.leftUnidirectional && relationship.relationshipManyToMany && relationship.relationshipLeftSide)) { _%>
              <%_ if (relationship?.bcConfig?.leftRelateByIdEntity) { _%>
            baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            baseData: { <%= relationship.otherRelationship.relationshipName%>: {<%= relationship.otherEntity.primaryKey.name %>: <%= entityInstance %>Id.value}, },
              <%_ } _%>
            <%_ } _%>
            editConfig: {
              trigger: 'click',
              mode: 'row',
              beforeEditMethod({ row, rowIndex, column, columnIndex }) {
                console.log('beforeEditMethod', row, rowIndex, column, columnIndex);
                return true;
              },
            },
            onEditClosed: ({ $table, row, column }) => {
              console.log('$table', $table);
              if ($table.isUpdateByRow(row)) {
                row.loading = true;
                apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service
                  .update({ id: row.id, [column.field]: row[column.field] }, [row.id], [column.field])
                  .then(data => {
                    $table.reloadRow(row, data, column.field);
                    message.success('保存成功！');
                  })
                  .finally(() => {
                    row.loading = false;
                  });
              }
            },
            fieldMapToTime: [],
            size: 'default',
            disabled: !isEdit.value,
            <%_
                const otherEntityCreateBySelf = relationship.otherEntity.features?.includes('createBySelf');
                let updateType = 'emitSelected';
                if (!relationship.bcConfig.leftUnidirectional && relationship.relationshipLeftSide && relationship.relationshipManyToMany) {
                    updateType = 'remoteApi';
                } else if (relationship.bcConfig.leftUnidirectional && relationship.relationshipLeftSide && relationship.relationshipOneToMany && relationship.bcConfig.leftRelateByIdEntity && otherEntityCreateBySelf) {
                    updateType = 'remoteApi';
                }
            _%>
            updateType: '<%= updateType %>',
            gridOptions: {
              toolbarConfig: {
                // buttons未配置表示使用组件原有的，如果配置了，以配置为主。通过code进行比较
                // buttons: [],

                import: false,
                export: false,
                print: false,
                custom: false,
                // 表格右上角自定义按钮, tools未配置表示使用组件原有的，如果配置了，以配置为主。通过code进行比较
                tools: [<% if (relationship.relationshipManyToMany || relationship.relationshipOneToMany && relationship.bcConfig?.leftUnidirectional && relationship.otherEntity.features?.includes('copy')) { %>'add', <% } %>'new'],
              },
            },
          }),
          slots: {},
          events: {
            updateRelationData: (data) => {
              <%= entityInstance %>.<%= relationship.relationshipName %> = data;
            },
          },
          disabled: () => {
            return !<%= entityInstance %>.id;
          },
        },
          <%_ } _%>
      <%_}); _%>
  });
function changeActiveKey(activeKey: string) {
  relationTables.activeKey = activeKey;
    <%_ if (showInOneContainerConfig.componentName === 'a-tabs') { _%>
      <%_ if (showInOneContainerConfig.showBaseInfo) { _%>
  emit('update-save-button', activeKey === 'baseInfo');
      <%_ } else { _%>
  emit('update-save-button', true);
      <%_ } _%>
    <%_ } else { _%>
  emit('update-save-button', true);
    <%_ } _%>
}
  <%_ } _%>
watch(<%= entityInstance %>, (val) => {
  formRef.value?.setFieldsValue(val);
});

<%_ if (addCustomMethod.indexOf('updateTemplate') !== -1) { _%>
<%- include(`../common/entity-custom/${entityClass}.updateTemplate.ejs`, {position: 'componentMethod'}); -%>
<%_ } _%>

defineExpose({
  validate,
  submit,
});
</script>
<style scoped>
  .pb-44px {
    padding-bottom: 44px;
  }
</style>
