<%#
 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 =';
let resultEntity;
let mapsIdEntityInstance;
let mapsIdRepoInstance;
let otherEntityName;

if (isUsingMapsId) {
    mapsIdEntityInstance = mapsIdAssoc.otherEntityNameCapitalized.charAt(0).toLowerCase() + mapsIdAssoc.otherEntityNameCapitalized.slice(1);
    mapsIdRepoInstance = `${mapsIdEntityInstance}Repository`;
    otherEntityName = mapsIdAssoc.otherEntityName;
} _%>
<%_ if (!viaService) { _%><%# service里或其他部分%>
  <%_ if (dtoMapstruct) { _%>
    <%_ resultEntity = persistInstance; _%>
        <%= persistClass %> <%= persistInstance %> = <%= dtoToEntity %>(<%= instanceName %>);
    <%_ if (isPersisted) { _%>
        <%= persistInstance %>.setIsPersisted();
    <%_ } _%>
    <%_ if (isUsingMapsId) { _%>
        <%= mapsIdAssoc.otherEntity.primaryKey.type %> <%= otherEntityName %>Id = <%= instanceName %>.get<%= mapsIdAssoc.relationshipNameCapitalized %>().get<%= primaryKey.nameCapitalized %>();
        <%= mapsIdRepoInstance %>.findById(<%= otherEntityName %>Id).ifPresent(<%= persistInstance %>::<%_ if (!fluentMethods) { _%>set<%= mapsIdAssoc.relationshipNameCapitalized %> <%_ } else { _%><%= mapsIdAssoc.relationshipName %><%_ } _%>);
    <%_ } _%>
    <%_ if (updatableEntity) { _%>
        <%_ if (ormTool === 'hibernate') { _%>
        <%= persistInstance %> = <%= entityInstance %>Repository.save(<%= persistInstance %>);
        <%_ } else { _%>
          <%# 如果存在单身一对多和单向多对多应该在这里处理 %>
          <%_ 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.updateEntityAndRelatedEntities(<%= persistInstance %>, <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id, <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Name, "<%= persistClass %>");
              <%_ } else { _%>
        this.updateEntityAndRelatedEntities(<%= persistInstance %>, <%= persistInstance %>.get<%- this._.upperFirst(Object.keys(showInOneConfig)[0]) %>(), <%= showInOneConfigRelationship.otherEntityNameCapitalized %>::set<%= relationshipNameCapitalized %>Id);
              <%_ } _%>
            <%_ } else { _%>
              <%# 可能要对RelateByIdEntity的情况进行排除 _%>
              <%_ const n2nRelationships  = Object.keys(showInOneConfig).filter(
                relationshipName => !(showInOneConfig[relationshipName].relationshi.relationshipLeftSide && showInOneConfig[relationshipName].relationship.bcConfig.leftRelateByIdEntity)
              ); _%>
        this.createOrUpdateN2NRelations(<%= persistInstance %>, Arrays.asList("<%- n2nRelationships.join('", "') %>"));
            <%_ } _%>
          <%_ } else if (n2nConfig && Object.keys(n2nConfig).length > 0) { _%>
        this.createOrUpdateAndRelatedRelations(<%= persistInstance %>, <% if (javaVersion === '8') { %>Arrays.asList<% } else { %>List.of<% } %>("<%- Object.keys(n2nConfig).join('", "') %>"));
          <%_ } else { _%>
        <%= entityInstance %>Repository.updateById(<%= persistInstance %>);
          <%_ } _%>
        <%_ } _%>
    <%_ } else { _%>
        // no save call needed as we have no fields that can be updated
    <%_ } _%>
    <%_ 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(<%= instanceName %>.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 (isPersisted) { _%>
        <%= persistInstance %>.setIsPersisted();
    <%_ } _%>
    <%_ if (updatableEntity) { _%>
        <%= returnPrefix %> <%= entityInstance %>Repository.save(<%= persistInstance %>);
    <%_ } else { _%>
        // no save call needed as we have no fields that can be updated
        <%= returnPrefix %> <%= persistInstance %>;
    <%_ } _%>
  <%_ } _%>
  <%_ if (searchEngineElasticsearch) { _%>
        <%= entityInstance %>SearchRepository.index(<%= resultEntity %>);
    <%_ if (returnDirectly) { _%>
        return result;
    <%_ } _%>
  <%_ } _%>
<%_ } else { _%><%# controller中 %>
        <%= returnPrefix %> null;
        if (CollectionUtils.isNotEmpty(batchFields) && CollectionUtils.isNotEmpty(batchIds)) {
            batchIds = new ArrayList<>(batchIds);
            if (!batchIds.contains(<%= primaryKey.name %>)) {
                batchIds.add(<%= primaryKey.name %>);
            }
            <%= entityInstance %>Service.updateBatch(<%= instanceName %>, batchFields, batchIds);
            result = <%= entityInstance %>Service.findOne(<%= primaryKey.name %>).orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>);
        } else {
            result = <%= entityInstance %>Service.update(<%= instanceName %>);
        }
<%_ } _%>
