package cn.iocoder.yudao.module.infra.api.file;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.infra.api.file.dto.FileDTO;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FileRespVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

/**
 * 文件 API 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class FileApiImpl implements FileApi {

    @Resource
    private FileService fileService;

    @Override
    public String createFile(String name, String path, byte[] content) {
        return fileService.createFile(name, path, content);
    }

    @Override
    public FileDTO uploadFile(String name, String path, byte[] content){
        FileRespVO fileRespVO = fileService.uploadFile(name, path, content);
        return BeanUtils.toBean(fileRespVO, FileDTO.class);
    }

    @Override
    public Integer updateFileBiz(List<Long> fileIdList, String serviceId) {
        if (StrUtil.isNotBlank(serviceId)) {
            // 先取消关联
            fileService.cancelFileBiz(serviceId);
        }
        if (CollectionUtil.isNotEmpty(fileIdList) && StrUtil.isNotEmpty(serviceId)) {
            // 再关联最新的
            fileService.updateFileBiz(fileIdList, serviceId);
        }
        return 1;
    }

    @Override
    public List<FileDTO> getFileDTOListByBiz(String serviceId) {
        List<FileDO> fileDOList = fileService.getFileListByBiz(serviceId);
        return BeanUtils.toBean(fileDOList, FileDTO.class);
    }

}
