package com.yd.oss.api.service.impl;

import com.yd.common.enums.ResultCode;
import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.oss.api.service.ApiOssFileService;
import com.yd.oss.feign.request.ApiOssFileListRequest;
import com.yd.oss.feign.response.ApiOssFileListResponse;
import com.yd.oss.service.dto.OssFileDto;
import com.yd.oss.service.model.OssFile;
import com.yd.oss.service.model.RelObjectMaterial;
import com.yd.oss.service.service.IOssFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiOssFileServiceImpl implements ApiOssFileService {

    @Autowired
    private IOssFileService iOssFileService;

    /**
     * 列表查询-文件元数据信息
     * @param request
     * @return
     */
    @Override
    public Result<List<ApiOssFileListResponse>> list(ApiOssFileListRequest request) {
        List<OssFile> list = iOssFileService.queryList(OssFileDto.builder().objectBizId(request.getObjectBizId()).build());
        if (!CollectionUtils.isEmpty(list)) {
            List<ApiOssFileListResponse> responses = list.stream().map(dto -> {
                ApiOssFileListResponse response = new ApiOssFileListResponse();
                BeanUtils.copyProperties(dto,response);
                return response;
            }).collect(Collectors.toList());
            return Result.success(responses);
        }
        return Result.success();
    }

    /**
     * 删除-文件元数据信息
     * @param fileBizId
     * @return
     */
    @Override
    public Result del(String fileBizId) {
        Result<OssFile> result = checkOssFileIsExist(fileBizId);
        OssFile ossFile = result.getData();
        iOssFileService.removeById(ossFile.getId());
        return Result.success();
    }

    /**
     * 校验文件元数据信息是否存在
     * @param fileBizId
     * @return
     */
    public Result<OssFile> checkOssFileIsExist(String fileBizId) {
        OssFile ossFile = iOssFileService.queryOne(fileBizId);
        if (Objects.isNull(ossFile)) {
            //数据不存在
            throw new BusinessException(ResultCode.NULL_ERROR.getCode(),ResultCode.NULL_ERROR.getMessage());
        }
        return Result.success(ossFile);
    }
}
