<%#
 Copyright 2013-2023 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.
-%>
package <%= entityAbsolutePackage %>.service.mapper;

<%_
  const getOriginalField = field => field.originalField || field;
  // add by plus start
  const manyListName = ormTool !== 'mybatis' ? 'Set' : 'List';
  const manyListType = ormTool !== 'mybatis' ? 'LinkedHashSet' : 'ArrayList';
  // add by plus end
  const uuidMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldTypeUUID);
  const byteMapMethod = dtoReferences.some(reference => reference.valueReference && reference.valueReference.field && reference.valueReference.field.fieldTypeBytes);
  // const dtoRelationships = dtoReferences.filter(reference => reference.relationship && !reference.relationship.otherEntity.embedded).map(reference => reference.relationship); // comment by begcode
  const dtoRelationships = dtoReferences
          .filter(reference => reference.relationship && !reference.relationship.otherEntity.embedded)
          .filter(reference => !multiModule || (multiModule && (!moduleName || moduleName === reference.relationship.otherEntity.moduleName)))
          .map(reference => reference.relationship);
  // add by begcode start
    let existingMappings = [];
    for (reference of dtoReferences) {
        // if the entity is mapped twice, we should implement the mapping once
        if (reference.relationship && !reference.relationship.otherEntity.embedded && !existingMappings.includes(reference.name) && reference.relationship.otherEntityNameCapitalized !== persistClass) {
            if ((reference.relationship.relationshipType === 'one-to-many' && reference.relationship.bcConfig && reference.relationship.bcConfig.showInOne)) {
                existingMappings.push(reference.relationship.otherEntity.entityNameCapitalized);
            }
        }
    }
    // 过滤掉单向one-to-many的关系,这些用来正常显示的，不需要转换。
    const removeFieldRelationships = dtoRelationships.filter(relationship => relationship.relationshipOneToMany && relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('unidirectional'));
  // add by begcode end
  let otherEntitiesFields = otherEntities
    .filter(otherEntity => dtoRelationships.some(relationship => relationship.otherEntity === otherEntity))
    .filter(otherEntity => !removeFieldRelationships.some(relationship => relationship.otherEntity === otherEntity)) // add by begcode
    .map(otherEntity =>
      dtoRelationships
        .filter(relationship => relationship.otherEntity === otherEntity)
        .map(({relatedField, collection}) => ({otherEntity, relatedField, collection}))
    )
    .flat();
  otherEntitiesFields.forEach(a => {
    a.collection = a.collection || otherEntitiesFields.some(b => a.otherEntity === b.otherEntity && a.relatedField && b.relatedField && getOriginalField(a.relatedField) === getOriginalField(b.relatedField) && b.collection === true)
  });
  otherEntitiesFields = this._.uniqWith(otherEntitiesFields, (a, b) => a.otherEntity === b.otherEntity && a.collection === b.collection && a.relatedField && b.relatedField && getOriginalField(a.relatedField) === getOriginalField(b.relatedField));
_%>

<%_ if (dtoRelationships.some(r => r.collection)) { _%>
  <%_ if (ormTool === 'hibernate') { _%>
import java.util.Set;
  <%_ } else { _%>
import java.util.List;
  <%_ } _%>
  <%_ if (otherEntitiesFields.filter(field => field.relatedField).some(field => field.collection)) { _%>
import java.util.stream.Collectors;
  <%_ } _%>
<%_ } _%>
<%_ if (packageName !== entityAbsolutePackage) { _%>
import <%= packageName %>.service.mapper.EntityMapper;
<%_ } _%>

import <%= entityAbsoluteClass %>;
import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>;
<%# filter(relationship => !(relationship.relationshipType === 'one-to-many' && relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('unidirectional'))). %>
<%_ for (const otherEntity of this._.uniq(dtoRelationships.map(relationship => relationship.otherEntity).filter(otherEntity => otherEntity.entityClass !== entityClass))) {
_%>
  <%_ if (applicationTypeMonolith || (applicationTypeMicroservice && (otherEntity.applications.includes('*') || otherEntity.applications.includes(baseName)))) { _%>
import <%= otherEntity.entityAbsoluteClass %>;
import <%= otherEntity.entityAbsolutePackage %>.service.dto.<%= otherEntity.dtoClass %>;
  <%_ } _%>
<%_ } _%>

import org.mapstruct.*;
<%_ if (uuidMapMethod) { _%>

import java.util.Objects;
import java.util.UUID;
<%_ } _%>

/**
 * Mapper for the entity {@link <%= persistClass %>} and its DTO {@link <%= dtoClass %>}.
 */
@Mapper(componentModel = "spring")
public interface <%= entityClass %>Mapper extends EntityMapper<<%= dtoClass %>, <%= persistClass %>> {
<%_ if (!embedded) { _%>
  <%_ var renMapAnotEnt = false; /*Render Mapping Annotation during Entity to DTO conversion?*/ _%>
  <%_ for (relationship of dtoRelationships.filter(relationship => !(!relationship.ownerSide && relationship.relationshipOneToMany && relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('unidirectional')))) { _%>
    <%_ if (applicationTypeMonolith || (applicationTypeMicroservice && (relationship.otherEntity.applications.includes('*') || relationship.otherEntity.applications.includes(baseName)))) { _%> <%# add by begcode %>
    <%_
      renMapAnotEnt = true;
      let qualifiedByName = relationship.otherEntity.entityInstance + this._.upperFirst(relationship.otherEntityField);
      qualifiedByName = qualifiedByName + (relationship.collection ? manyListName : '');
    _%>
      <%_ if (!(relationship.relationshipOneToMany && relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('unidirectional') || (fieldsContainParentAndChildren && relationship.relationshipName === 'children'))) { _%> <%# add by begcode %>
    @Mapping(target = "<%= relationship.propertyName %>", source = "<%= relationship.propertyName %>", qualifiedByName="<%= qualifiedByName %>")
      <%_ } _%> <%# add by begcode %>
    <%_ } _%> <%# add by begcode %>
  <%_ } _%>
  <%_ for (const field of fields.filter(field => field.mapstructExpression)) {
      renMapAnotEnt = true; _%>
    @Mapping( target = "<%= field.propertyName %>", expression = "<%- field.mapstructExpression %>")
  <%_ } _%>
  <%_ if (renMapAnotEnt) { _%>
    <%= dtoClass %> toDto(<%= persistClass %> s);
  <%_ } _%>

  <%_ var renMapAnotDto = false;  /*Render Mapping Annotation during DTO to Entity conversion?*/ _%>
  <%_ if(primaryKey.ids.length > 1) { _%>
    <%_ renMapAnotDto = true; _%>
    <%_ for (const id of primaryKey.ids) { _%>
    @Mapping(target = "id.<%= id.name %>", source = "<%= id.nameDotted %>")
    <%_ } _%>
  <%_ } _%>
  <%_ for (const field of fields.filter(field => (field.options && field.options.extendAbstractAuditingEntity) || (['delFlag', 'deletedTime'].includes(field.propertyName) && (softDelete && !skipSoftDelete)))) { _%>
    <%_ renMapAnotDto = true; _%>
    @Mapping( target = "<%= field.propertyName %>", ignore = true)
  <%_ } _%>
  <%_ for (relationship of dtoRelationships) { _%>
    <%_ if (!relationship.ownerSide && !(relationship.relationshipType === 'one-to-many' && relationship.source && relationship.source.annotationOnSource && relationship.source.annotationOnSource.includes('unidirectional'))) { _%>
      <%_ renMapAnotDto = true; _%>
    @Mapping(target = "<%= relationship.propertyName %>", ignore = true)
    <%_ }
    if (relationship.collection && fluentMethods && ormTool === 'hibernate') { // modify by begcode
      renMapAnotDto = true; _%>
    @Mapping(target = "remove<%= relationship.relationshipNameCapitalized %>", ignore = true)
    <%_ } _%>
    <%_ if (fieldsContainParentAndChildren && ormTool === 'mybatis' && relationship.relationshipType === 'many-to-one' && relationship.otherEntityNameCapitalized === entityNameCapitalized) { _%>
    @Mapping(target = "<%= relationship.relationshipName %><%= this.upperFirstCamelCase(relationship.otherEntity.primaryKey.name) %>", source = "<%= relationship.relationshipName %>.<%= relationship.otherEntity.primaryKey.name %>")
    <%_ } _%>
  <%_ } _%>
  <%_ if (renMapAnotDto) { _%>
    <%= persistClass %> toEntity(<%= dtoClass %> <%= dtoInstance %>);
  <%_ } _%>
  <%_ for (const {otherEntity, relatedField, collection} of otherEntitiesFields.filter(field => field.relatedField)) { _%>
    <%_ if (applicationTypeMonolith || (applicationTypeMicroservice && (otherEntity.applications.includes('*') || otherEntity.applications.includes(baseName)))) { _%><%# add by begcode %>
    <%_ const mapperName = otherEntity.entityInstance + this._.upperFirst(relatedField.propertyName); _%>

    @Named("<%= mapperName %>")
    @BeanMapping(ignoreByDefault = true)
    <%_ for (const field of otherEntity.primaryKey.fields) { _%>
    @Mapping(target = "<%= field.propertyName %>", source = "<%= field.propertyName %>")
    <%_ } _%>
    <%_ if (!relatedField.id) { _%>
      <%_ if (relatedField.mapstructExpression) { _%>
    @Mapping(target = "<%= relatedField.propertyName %>", expression = "<%- relatedField.mapstructExpression %>")
      <%_ } else { _%>
    @Mapping(target = "<%= relatedField.propertyName %>", source = "<%= relatedField.propertyName %>")
      <%_ } _%>
    <%_ } _%>
      <%_ if (relatedField.mapstructExpression) { _%>
    <%- otherEntity.dtoClass %> toDto<%= this._.upperFirst(mapperName) %>(<%- otherEntity.persistClass %> s);
    <%_ } else { _%>
    <%- otherEntity.dtoClass %> toDto<%= this._.upperFirst(mapperName) %>(<%- otherEntity.persistClass %> <%= otherEntity.persistInstance %>);
      <%_ } _%>
    <%_ if (collection) { %>
      <%_ const collectionMapperName = otherEntity.entityInstance + this._.upperFirst(relatedField.propertyName) + manyListName; _%>

    @Named("<%= collectionMapperName %>")
    default <%= manyListName %><<%- otherEntity.dtoClass %>> toDto<%= this._.upperFirst(mapperName) %><%= manyListName %>(<%= manyListName %><<%- otherEntity.persistClass %>> <%= otherEntity.persistInstance %>) {
        return <%= otherEntity.persistInstance %>.stream().map(this:: toDto<%= this._.upperFirst(mapperName) %>).collect(Collectors.to<%= manyListName %>());
    }
    <%_ } _%>
    <%_ } _%> <%# add by plus %>
  <%_ } _%>
  <%_ if (uuidMapMethod) { _%>

    default String map(UUID value) {
        return Objects.toString(value, null);
    }
  <%_ } _%>
  <%_ if (byteMapMethod) { _%>

    default String map(byte[] value) {
        return new String(value);
    }
  <%_ } _%>
<%_ } _%>
    // begcode-please-regenerate-this-file 如果您不希望重新生成代码时被覆盖，将please修改为don't ！！！<%# add by plus %>
}
