<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_ const instanceType = restClass;
const instanceName = restInstance;
const mapper = entityInstance  + 'Mapper';
const dtoToEntity = mapper + '.' + 'toEntity';
const entityToDto = mapper + '.' + 'toDto';
const entityToDtoReference = mapper + '::' + 'toDto';
const returnPrefix = (returnDirectly && !searchEngineElasticsearch) ? 'return' : instanceType + ' result =';
const mybatisReturnPrefix = (returnDirectly && !searchEngine) ? 'return' : 'boolean' + ' result =';
const mybatisReturnEntityPrefix = (returnDirectly && !searchEngine) ? 'return' : instanceType + ' updateEntity =';
const skipRelationships = this._reflexRelationship(relationships, entityClass);
let resultEntity;
let mapsIdEntityInstance;
let mapsIdRepoInstance;
let otherEntityName;
if (isUsingMapsId) {
    const mapsIdEntity = mapsIdAssoc.otherEntityNameCapitalized;
    mapsIdEntityInstance = mapsIdEntity.charAt(0).toLowerCase() + mapsIdEntity.slice(1);
    mapsIdRepoInstance = `${mapsIdEntityInstance}Repository`;
}
_%>
  <%_ if (dtoMapstruct) { _%>
    <%_ resultEntity = persistInstance; _%>
    <%_ if (extendData && ormTool === 'mybatis') { _%>
        Map<String, Object> extData = <%= instanceName %>.getExtData();
    <%_ } _%>
        <%= persistClass %> <%= persistInstance %> = <%= dtoToEntity %>(<%= instanceName %>);
    <%_ if (!saveNewEntityOperation && requiresPersistableImplementation && ormTool === 'hibernate') { _%>
        <%- persistInstance %>.setIsPersisted();
    <%_ } _%>
    <%_ if (saveNewEntityOperation && isUsingMapsId) { _%>
        <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>();
        <% if (ormTool === 'hibernate') { %><%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id)<% } else { %><%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id)<% } %>.ifPresent(<% if (ormTool !== 'mybatis') { %><%= persistInstance %>::<%_ if (fluentMethods === false) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= mapsIdAssoc.relationshipName %><%_ } _%><% } else { %><%= persistInstance %>Temp -> <%= persistInstance %>.setId(<%= otherEntityName %>Id)<% } %>);
    <%_ } _%>
    <%_ if (fieldsContainParentAndChildren) { _%>
        clearChildrenCache();
    <%_ }  _%>
    <%_ if (ormTool === 'mybatis') { _%>
      <%# 如果存在多对一在这里修改相应的ID _%>
      <%_ relationships.filter(relationship => (relationship.relationshipManyToOne && relationship.relationshipLeftSide) || (relationship.relationshipManyToOne && relationship.relationshipRightSide && relationship.bcConfig?.leftUnidirectional && !relationship.bcConfig?.leftRelateByIdEntity)).forEach(relationship => { _%>
        <%= persistInstance %>
            .set<%= this._.upperFirst(relationship.relationshipName) %><%= relationship.otherEntity.primaryKey.nameCapitalized %>(
                <%_ if (relationship.bcConfig?.leftValueFrom === 'currentUser') { _%>
                    <%_
                    if (javaImportMap.has('baseServiceImplImports')) {
                        const baseServiceImplImports = javaImportMap.get('baseServiceImplImports');
                        if (baseServiceImplImports) {
                            baseServiceImplImports.add(`import ${packageName}.security.SecurityUtils;`);
                        } else {
                            javaImportMap.set('baseServiceImplImports', new Set([`import ${packageName}.security.SecurityUtils;`]));
                        }
                    } else {
                        javaImportMap.set('baseServiceImplImports', new Set([`import ${packageName}.security.SecurityUtils;`]));
                    }
                    _%>
                SecurityUtils.getCurrentUserId().orElse(null)
                <%_ } else { _%>
                    <%_
                    if (javaImportMap.has('baseServiceImplImports')) {
                        const baseServiceImplImports = javaImportMap.get('baseServiceImplImports');
                        if (baseServiceImplImports) {
                            baseServiceImplImports.add(`import ${relationship.otherEntity.entityAbsoluteClass};`);
                        } else {
                            javaImportMap.set('baseServiceImplImports', new Set([`import ${relationship.otherEntity.entityAbsoluteClass};`]));
                        }
                    } else {
                        javaImportMap.set('baseServiceImplImports', new Set([`import ${relationship.otherEntity.entityAbsoluteClass};`]));
                    }
                    _%>
                Optional.ofNullable(<%= persistInstance %>.get<%= this._.upperFirst(relationship.relationshipName) %>()).map(<%= relationship.otherEntity.persistClass %>::get<%= relationship.otherEntity.primaryKey.nameCapitalized %>).orElse(null));
                <%_ } _%>
      <%_ });_%>
      <%# 如果存在单向一对多和单向多对多应该在这里处理 _%>
      <%_ const { showInOneConfig, n2nConfig } = (bcEntityData || { formFieldLines: [], showInOneRelationships: {}, showInOneConfig: {} }); _%>
      <%_ if (showInOneConfig && Object.keys(showInOneConfig).length > 0 || n2nConfig && Object.keys(n2nConfig).length > 0) { _%>
        <%_ if (showInOneConfig && Object.keys(showInOneConfig).length > 0)  {
            // 区分OwnerEntity 和非OwnerEntity 两种类型的关联关系
            const showInOneOwnerEntityConfigs = [];
            const showInOneOwnerEntityByselfConfigs = [];
            const showInOneNotOwnerEntityConfigs = [];
            Object.keys(showInOneConfig).forEach(relationshipName => {
                const relationship = showInOneConfig[relationshipName].relationship;
                if (relationship.relationshipLeftSide && relationship.bcConfig.leftRelateByIdEntity && relationship.otherEntity.options?.features?.includes('createBySelf')) {
                    showInOneOwnerEntityByselfConfigs.push(relationshipName);
                } else if (relationship.relationshipLeftSide && relationship.bcConfig.leftRelateByIdEntity) {
                    showInOneOwnerEntityConfigs.push(relationshipName);
                } else {
                    showInOneNotOwnerEntityConfigs.push(relationshipName);
                }
            });
            const existOwnerEntityConfigs = showInOneOwnerEntityConfigs.length > 0;
            const existOwnerEntityByselfConfigs = showInOneOwnerEntityByselfConfigs.length > 0;
            const existNotOwnerEntityConfigs = showInOneNotOwnerEntityConfigs.length > 0;
            if (existNotOwnerEntityConfigs) {
              showInOneNotOwnerEntityConfigs.forEach((relationshipName, index) => {
              const showInOneConfigRelationship = showInOneConfig[relationshipName].relationship;
              const relationshipNameCapitalized = showInOneConfigRelationship.otherRelationship.relationshipNameCapitalized;
              _%>
            <%_ if (showInOneConfigRelationship.relationshipManyToMany) { _%>
            this.createOrUpdateN2NRelations(<%= persistInstance %>, List.of("<%= relationshipName %>"));
            <%_ } else { _%>
            this.<% if (saveNewEntityOperation && index === 0) { %>createEntityAndRelatedEntities<% } else { %>updateEntityAndRelatedEntities<% } %>(<%= persistInstance %>, <%= persistInstance %>.get<%- this._.upperFirst(relationshipName) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id);
                <%_ } _%>
              <%_ }); _%>
            <%_ if (existOwnerEntityConfigs) {
                showInOneOwnerEntityConfigs.forEach(relationshipName => {
                const showInOneConfigRelationship = showInOneConfig[relationshipName].relationship;
                const relationshipNameCapitalized = 'OwnerEntity';
            _%>
            this.updateRelatedEntities(<%= persistInstance %>.get<%= primaryKey.nameCapitalized%>(), <%= persistInstance %>.get<%- this._.upperFirst(relationshipName) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
              <%_ }); _%>
            <%_ } _%>
            <%_ if (existOwnerEntityByselfConfigs) {
                showInOneOwnerEntityByselfConfigs.forEach(relationshipName => {
                const showInOneConfigRelationship = showInOneConfig[relationshipName].relationship;
                const relationshipNameCapitalized = 'OwnerEntity';
            _%>
        this.updateRelationByEntities(<%= persistInstance %>.get<%= primaryKey.nameCapitalized%>(), <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
                <%_ }); _%>
            <%_ } _%>
          <%_ } else { _%>
            <%_ if (existOwnerEntityConfigs) {
                showInOneOwnerEntityConfigs.forEach((relationshipName, index) => {
               const showInOneConfigRelationship = showInOneConfig[relationshipName].relationship;
               const relationshipNameCapitalized = 'OwnerEntity';
            _%>
       this.<% if (saveNewEntityOperation && index === 0) { %>createEntityAndRelatedEntities<% } else { %>updateEntityAndRelatedEntities<% } %>(<%= persistInstance %>, <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
                <%_ }); _%>
           <%_ if (existOwnerEntityByselfConfigs) {
             showInOneOwnerEntityByselfConfigs.forEach(relationshipName => {
               const showInOneConfigRelationship = showInOneConfig[relationshipName].relationship;
               const relationshipNameCapitalized = 'OwnerEntity';
           _%>
       this.updateRelationByEntities(<%= persistInstance %>.get<%= primaryKey.nameCapitalized%>(), <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
                <%_ }); _%>
            <%_ } _%>
          <%_ } else { _%>
            <%_ if (existOwnerEntityByselfConfigs) { _%>
      this.saveOrUpdate(<%= persistInstance %>);
              <%_
                showInOneOwnerEntityByselfConfigs.forEach(relationshipName => {
                  const showInOneConfigRelationship = showInOneConfig[relationshipName].relationship;
                  const relationshipNameCapitalized = 'OwnerEntity';
              _%>
      this.updateRelationByEntities(<%= persistInstance %>.get<%= primaryKey.nameCapitalized%>(), <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
              <%_ }); _%>
            <%_ } _%>
          <%_ } _%>
        <%_ } _%>
      <%_ } _%>
      <%_ if (n2nConfig && Object.keys(n2nConfig).length > 0) { _%>
        this.createOrUpdateAndRelatedRelations(<%= persistInstance %>, List.of("<%- Object.keys(n2nConfig).join('", "') %>"));
      <%_ } _%>
      <%_ } else { _%>
        this.saveOrUpdate(<%= persistInstance %>);
      <%_ } _%>
    <%_ } else { _%>
        <%= persistInstance %> = <%= persistInstance %>Repository.save(<%= persistInstance %>);
    <%_ } _%>
    <%_ if (extendData) { _%>
        <%_ if (ormTool === 'hibernate') { _%>
            <%_ if (multiModel) { %>
        <%= persistInstance %>.setExtData(extData);
        commonExtDataService.saveExtDataByModelId(<%= persistInstance %>,<%= instanceName %>.get<%= upperFirstCamelCase(multiModel)%>Id());
            <%_ } else { _%>
        <%= persistInstance %>.setExtData(extData);
        commonExtDataService.saveExtData(<%= persistInstance %>);
            <%_ } _%>
        <%_ } else { _%>
        this.saveExtData(<%= persistInstance %>, extData);
        Binder.bindRelations(<%= persistInstance %><%- skipRelationships%>);
        <%_ } _%>
    <%_ } _%>
    <%_ if (fieldsContainParentAndChildren && ormTool === 'hibernate') { _%>
        // 更新缓存
        if (<%= persistInstance %>.get<%= this._.upperFirst(parentRelationshipName) %>() != null) {
            <%= persistInstance %>.get<%= this._.upperFirst(parentRelationshipName) %>().add<%= this._.upperFirst(childrenRelationshipName) %>(<%= persistInstance %>);
        }
    <%_ } _%>
    <%_ if (addCustomMethod.indexOf('service') !== -1) { _%>
    <%- include(`/src/main/java/_package_/_entityCustom_/${entityClass}.service.ejs`, { serviceImpl: true, position: 'afterUpdate'}); -%>
    <%_ } _%>
    <%_ if (ormTool === 'hibernate') { _%>
        <%= returnPrefix %> <%= entityToDto %>(<%= persistInstance %>);
    <%_ } else { _%>
        <%= returnPrefix %> findOne(<%= persistInstance %>.get<%= primaryKey.nameCapitalized%>()).orElseThrow();
    <%_ } _%>
  <%_ } else {
      resultEntity = 'result'; _%>
    <%_ if (isUsingMapsId) { _%>
        <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>();
        <%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= instanceName %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= otherEntityName %><%_ } _%>);
    <%_ } _%>
        <%_ if (ormTool === 'mybatis') { _%>
        <%= mybatisReturnPrefix %> saveOrUpdate(<%= persistInstance %>);
        Binder.bindRelations(<%= persistInstance %><%- skipRelationships%>);
        <%_ if (addCustomMethod.indexOf('service') !== -1) { _%>
        <%- include(`/src/main/java/_package_/_entityCustom_/${entityClass}.service.ejs`, { serviceImpl: true, position: 'afterUpdate' }); -%>
        <%_ } _%>
            <%_ if (searchEngine) { _%>
        <%= mybatisReturnEntityPrefix %> <%= entityInstance %>Repository.selectById(<%= persistInstance %>.get<%= primaryKey.nameCapitalized%>());
            <%_ } _%>
        <%_ } else { _%>
        <%= returnPrefix %> <%= entityInstance %>Repository.save(<%= persistInstance %>);
        <%_ } _%>
  <%_ } _%>
  <%_ if (searchEngineElasticsearch) { _%>
        <%= entityInstance %>SearchRepository.index(<% if (!dtoMapstruct && ormTool === 'mybatis') { %>updateEntity<% } else { %><%= resultEntity %><% } %>);
    <%_ if (returnDirectly) { _%>
        return result;
    <%_ } _%>
  <%_ } _%>
