<%#
 Copyright 2013-2024 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 =';
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).forEach(relationship => { _%>
        <%= persistInstance %>
            .set<%= this._.upperFirst(relationship.relationshipName) %><%= relationship.otherEntity.primaryKey.nameCapitalized %>(
                Optional.ofNullable(<%= instanceName %>.get<%= this._.upperFirst(relationship.relationshipName) %>())
                    .map(<%= relationship.otherEntity.dtoInstance %> -> <%= relationship.otherEntity.dtoInstance %>.get<%= relationship.otherEntity.primaryKey.nameCapitalized %>())
                    .orElse(null));
      <%_ });_%>
      <%# 如果存在单向一对多和单向多对多应该在这里处理 _%>
      <%_ const { showInOneConfig, n2nConfig } = (bcEntityData || { formFieldLines: [], showInOneRelationships: {}, showInOneConfig: {} }); _%>
      <%_ if (showInOneConfig && Object.keys(showInOneConfig).length > 0) { _%>
        <%_ if (Object.keys(showInOneConfig).length === 1)  {
            const showInOneConfigRelationship = showInOneConfig[Object.keys(showInOneConfig)[0]].relationship;
            let relationshipNameCapitalized = showInOneConfigRelationship.otherRelationship.relationshipNameCapitalized;
            if (showInOneConfigRelationship.otherRelationship.relationshipRightSide && showInOneConfigRelationship.otherRelationship.bcConfig.leftRelateByIdEntity) {
                relationshipNameCapitalized = 'OwnerEntity';
            }
        _%>
          <%_ if (relationshipNameCapitalized === 'OwnerEntity') { _%>
        this.createEntityAndRelatedEntities(<%= persistInstance %>, <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
          <%_ } else { _%>
        this.createEntityAndRelatedEntities(<%= persistInstance %>, <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id);
          <%_ } _%>
        <%_ } else { _%>
        this.createOrUpdateN2NRelations(<%= persistInstance %>, Arrays.asList("<%- Object.keys(showInOneConfig).join('", "') %>"));
        <%_ } _%>
      <%_ } else if (n2nConfig && Object.keys(n2nConfig).length > 0) { _%>
        this.createOrUpdateAndRelatedRelations(<%= persistInstance %>, Arrays.asList("<%- 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(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>);
    <%_ } _%>
  <%_ } 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;
    <%_ } _%>
  <%_ } _%>
