<%_
const oneToOneNotOwnerSide =[];
let hasUseJPADerivedIdentifier = false;
const { formFieldLines, showInOneRelationships, showInOneImportComponents, showInOneContainerType } = (bcEntityData || { formFieldLines: [], showInOneRelationships: [], showInOneImportComponents: {}});
_%>
<template>
  <div :class="containerType === 'page' ? ['pb-44px'] : []"<% if (cypressTests) { %> data-cy="<%= entityAngularName %>CreateUpdateHeading"<% } %>>
    <BasicForm ref="formRef" v-bind="formProps"></BasicForm>
  <%_ if (showInOneRelationships && showInOneRelationships.length) {
    const subComponentName = showInOneContainerType === 'Tabs' ? 'TabPane' : 'CollapsePanel';
  _%>
  <<%= showInOneContainerType %>>
    <%_ showInOneRelationships.forEach(relationship => { _%>
    <<%= subComponentName %> :tab="relationTables.<%= relationship.relationTableKey %>.title" :key="relationTables.<%= relationship.relationTableKey %>.name">
      <<%= relationship.componentTypeName %> ref="<%= relationship.relationTableKey %>Ref" v-bind="relationTables.<%= relationship.relationTableKey %>.props"></<%= relationship.componentTypeName %>>
    </<%= subComponentName %>>
    <%_ }); _%>
  </<%= showInOneContainerType %>>
  <%_ } _%>
  </div>
</template>
<script lang="ts" setup>
import { getCurrentInstance, reactive, computed, h, ref, watch } from 'vue';
import { message<% if (showInOneRelationships.length && showInOneContainerType === 'Tabs') { %>, Tabs, TabPane<% } %><% if (showInOneRelationships.length && showInOneContainerType === 'Collapse') { %>, CollapsePanel, Collapse<% } %> } from 'ant-design-vue';
import { BasicForm } from '@begcode/components';
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 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 <%= entityInstance %> = reactive<I<%= entityAngularName %>>(new <%= entityAngularName %>());
watch(
  () => props.entityId,
  async (val) => {
    if (val) {
      const data = await apiService.<%= apiModuleName ? apiModuleName + '.' : '' %><%= entityInstance %>Service.find(<% if (tsKeyType === 'number') { %>Number(val)<% } else { %>val<% } %>).catch(() => null);
      if (data) {
        Object.assign(<%= entityInstance %>, data);
      }
    } else {
      Object.assign(<%= entityInstance %>, props.baseData);
    }
  },
  { immediate: true },
);
const formItemsConfig = config.fields();
<%_ 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 () => {
  const result = await validate().catch(() => ({ 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'}); -%>
    <%_ } _%>
    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.componentTypeName === 'Grid') { %>
    const <%= relationship.relationshipName %>validateErrors = await <%= relationship.relationTableKey %>Ref.value.validate(true);
    if (!<%= relationship.relationshipName %>validateErrors) {
      const { fullData } = <%= relationship.relationTableKey %>Ref.value.getTableData();
      fullData.forEach(row => {
        if (typeof row.id === 'string' && row.id.startsWith('row_')) {
          row.id = null;
        }
      });
      result.data['<%= relationship.relationshipName %>'] = fullData;
    } else {
      result.errors.push(<%= relationship.relationshipName %>validateErrors);
      result.success = false;
    }
    <%_ } else if (relationship.componentTypeName === 'FormList') { %>
    const <%= relationship.relationTableKey %>validateResult = await <%= relationship.relationTableKey %>Ref.value.validate();
    if (!<%= relationship.relationTableKey %>validateResult) {
      result.success = false;
      result.errors.push('<%= relationship.bcTitle %>校验未通过！');
    } else {
      result.data = { ...result.data, ...{ <%= relationship.relationshipName %>: <%= relationship.relationTableKey %>validateResult} };
    }
    <%_ } _%>
    <%_ }); _%>
    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: () => {
      ctx?.$emit('cancel', { update: false, containerType: props.containerType });
    },
    submitFunc: submit,
  });
  <%_
  let sortModelName = '';
  _%>
  <%_ if (showInOneRelationships && showInOneRelationships.length) { _%>
  const relationTables = reactive({
        <%_ showInOneRelationships.forEach(relationship => { _%>
          <%_ if (relationship.source?.annotationOnSource?.includes('editByList')) { _%>
        <%= relationship.otherEntity.entityNameCapitalized %>List: {
          name: '<%= relationship.otherEntity.entityNameCapitalized %>List',
          title: '<%= relationship.bcTitle%>列表',
          props: {
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
            query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
              <%_ } _%>
            editIn: 'modal',
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
            baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            baseData: { <%= relationship.otherRelationship.relationshipName%>Id: <%= 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 %>.value.id;
          },
        },
          <%_ } else　if (relationship.source?.annotationOnSource?.includes('editByFormList')) { _%>
      <%= relationship.relationshipName %>GridFormList: {
          name: 'FormList',
          title: '<%= relationship.bcTitle%>列表',
          props: {
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
            query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
              <%_ } _%>
            editIn: 'modal',
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
            baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            baseData: { <%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value },
              <%_ } _%>
            formConfig: { schemas: config.<%= relationship.relationshipName %>Columns },
            fieldName: '<%= relationship.relationshipName %>',
            fieldData: <%= entityInstance %>.value.<%= relationship.relationshipName %>,
            modelName: 'FormList',
          },
          disabled: () => {
            return !<%= entityInstance %>.value.id;
          },
        },
          <%_ } else　if (relationship.source?.annotationOnSource?.includes('editByDescList')) { _%>
      <%= relationship.relationshipName %>DescList: {
          name: 'DescList',
          title: '<%= relationship.bcTitle%>列表',
          props: {
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
            query: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            query: {<%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value},
              <%_ } _%>
            editIn: 'modal',
              <%_ if (relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.toString().includes('relateByIdEntity')) { _%>
            baseData: { ownerEntityName: '<%= entityClass %>', ownerEntityId: <%= entityInstance %>Id.value },
              <%_ } else { _%>
            baseData: { <%= relationship.otherRelationship.relationshipName%>Id: <%= entityInstance %>Id.value },
              <%_ } _%>
            configData: [
              {
                formConfig: config.<%= relationship.relationshipName %>Columns,
                data: {},
              }
            ],
            data: <%= entityInstance %>.value.<%= relationship.relationshipName %>,
            toolButtons: [],
            editComponentPath: '@/views/<%= relationship.otherEntity.entityFolderName%>/<%= relationship.otherEntity.entityFileName%>-edit.vue',
            modelName: 'DescList',
          },
          slots: {
            default: (item) => {
              return h(<%= relationship.otherEntity.entityNameCapitalized %>Desc, {entityId: item.id}, () => []);
            }
          },
          disabled: () => {
            return !<%= entityInstance %>.value.id;
          },
        },
          <%_ } else {
              sortModelName = relationship.relationshipName;
          _%>
      <%= relationship.relationshipName %>Grid: {
          name: '<%= relationship.relationshipName %>Grid',
          title: '<%= relationship.bcTitle%>列表',
          props: {
            modelName: '<%= relationship.relationshipName%>',
            data: <%= entityInstance %>['<%= relationship.relationshipName%>'],
            columns: <%= useCommonTable ? '' : 'config.'%><%= relationship.relationshipName%>Columns(),
            border: true,
            showOverflow: true,
            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: [],
            compact: true,
            size: 'default',
            disabled: !isEdit.value,
            toolbarConfig: {
              buttons: [
                { code: 'insert_actived', name: '新增', icon: 'fa fa-plus' },
                { code: 'remove', name: '删除', icon: 'fa fa-trash-o' },
              ],
              // 表格右上角自定义按钮
              tools: [
                // { code: 'myPrint', name: '自定义打印' }
              ],
              import: false,
              export: false,
              print: false,
              custom: false,
            },
          } as VxeGridProps,
          slots: {},
        },
          <%_ } _%>
      <%_}); _%>
  });
  <%_ } _%>
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>
