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

import com.yd.auth.core.dto.AuthUserDto;
import com.yd.auth.core.utils.SecurityUtil;
import com.yd.common.enums.CommonEnum;
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.dto.ApiRelMaterialDto;
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 com.yd.oss.service.service.OssService;
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;

    @Autowired
    private OssService ossService;

    /**
     * 列表查询-文件元数据信息
     * @param request
     * @return
     */
    @Override
    public Result<List<ApiOssFileListResponse>> list(ApiOssFileListRequest request) {
        List<ApiOssFileListResponse> list = iOssFileService.list(request.getObjectBizId(),request.getObjectBizIdList(),request.getFileKeyList());
        return Result.success(list);
    }

    /**
     * 删除-文件元数据信息
     * @param fileBizId
     * @return
     */
    @Override
    public Result del(String fileBizId, String projectBizId) {
        // 获取当前操作人
        AuthUserDto authUser = SecurityUtil.getCurrentLoginUser();
        String operator = authUser != null ? authUser.getUsername() : "system";

        // 调用OSS服务删除文件（包含OSS删除和数据库物理删除）
        ossService.deleteFileByBizId(fileBizId, operator);
        return Result.success();
    }

    /**
     * 更新-材料
     * @param relObjectMaterialList
     * @param materialDtoList
     * @return
     */
    @Override
    public Result updateByMaterial(List<RelObjectMaterial> relObjectMaterialList,
                                   List<ApiRelMaterialDto> materialDtoList) {
        if (!CollectionUtils.isEmpty(materialDtoList)) {
            for (ApiRelMaterialDto dto : materialDtoList) {
                if (!CollectionUtils.isEmpty(relObjectMaterialList)) {
                    List<RelObjectMaterial> materials = relObjectMaterialList.stream().filter(d -> d.getMaterialBizId().equals(dto.getMaterialBizId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(materials)) {
                        RelObjectMaterial relObjectMaterial = materials.get(0);
                        if (!CollectionUtils.isEmpty(dto.getFileBizIdList())) {
                            List<OssFile> ossFileList = iOssFileService.queryList(OssFileDto.builder().fileBizIdList(dto.getFileBizIdList()).build());
                            if (!CollectionUtils.isEmpty(ossFileList)) {
                                ossFileList = ossFileList.stream().map(file -> {
                                    file.setObjectType(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getCode());
                                    file.setObjectTableName(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getName());
                                    file.setObjectTableName(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getCode());
                                    file.setObjectBizId(relObjectMaterial.getRelObjectMaterialBizId());
                                    return file;
                                }).collect(Collectors.toList());
                                iOssFileService.saveOrUpdateBatch(ossFileList);
                            }
                        }
                    }
                }

            }
        }
        return Result.success();
    }

    @Override
    public Result updateByMaterial(String relObjectMaterialBizId, List<String> fileBizIdList) {
        //objectId查询列表,置为空字符串
        List<OssFile> ossFiles = iOssFileService.queryList(OssFileDto.builder().objectBizId(relObjectMaterialBizId).build());
        if (!CollectionUtils.isEmpty(ossFiles)) {
            ossFiles = ossFiles.stream().map(file -> {
                file.setObjectType("");
                file.setObjectTableName("");
                file.setObjectTableName("");
                file.setObjectBizId("");
                return file;
            }).collect(Collectors.toList());
            iOssFileService.saveOrUpdateBatch(ossFiles);
        }

        //再更新
        List<OssFile> ossFileList = iOssFileService.queryList(OssFileDto.builder().fileBizIdList(fileBizIdList).build());
        if (!CollectionUtils.isEmpty(ossFileList)) {
            ossFileList = ossFileList.stream().map(file -> {
                file.setObjectType(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getCode());
                file.setObjectTableName(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getName());
                file.setObjectTableName(CommonEnum.UID_TYPE_REL_OBJECT_MATERIAL.getCode());
                file.setObjectBizId(relObjectMaterialBizId);
                return file;
            }).collect(Collectors.toList());
            iOssFileService.saveOrUpdateBatch(ossFileList);
        }
        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);
    }
}
