package org.springblade.file.convert;

import org.mapstruct.Mapper;
import org.mapstruct.MappingConstants;
import org.mapstruct.ReportingPolicy;
import org.springblade.file.pojo.dto.BusinessAttachmentAddDTO;
import org.springblade.file.pojo.dto.BusinessAttachmentBatchAddDTO;
import org.springblade.file.pojo.entity.Attachment;
import org.springblade.file.pojo.entity.BusinessAttachment;
import org.springblade.file.pojo.vo.AttachmentDetailVO;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author bfhuange
 * @date 2024/9/4
 */
@Mapper(componentModel = MappingConstants.ComponentModel.SPRING, unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BusinessAttachmentConvert {
    BusinessAttachment dto2entity(BusinessAttachmentAddDTO dto);

    List<BusinessAttachment> dtos2entities(List<BusinessAttachmentAddDTO> dtos);

    AttachmentDetailVO entity2vo(Attachment entity);

    default List<BusinessAttachment> dto2entities(BusinessAttachmentBatchAddDTO dto) {
        if (dto == null || dto.getDetails() == null) {
            return Collections.emptyList();
        }
        AtomicInteger sort = new AtomicInteger(1);
        return dto.getDetails().stream()
                .flatMap(detail -> detail.getAttachmentIds().stream().map(attachmentId -> {
                    BusinessAttachment businessAttachment = new BusinessAttachment();
                    businessAttachment.setAttachmentId(attachmentId);
                    businessAttachment.setBizId(dto.getBizId());
                    businessAttachment.setBizCode(detail.getBizCode());
                    businessAttachment.setSort(sort.getAndIncrement());
                    return businessAttachment;
                })).toList();
    }

}
