package com.njcn.process.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.process.mapper.SupvFileMapper;
import com.njcn.process.pojo.po.SupvFile;
import com.njcn.process.service.ISupvFileService;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2023-06-21
 */
@Service
@RequiredArgsConstructor
public class SupvFileServiceImpl extends ServiceImpl<SupvFileMapper, SupvFile> implements ISupvFileService {


    private final FileStorageUtil fileStorageUtil;

    private final SupvFileMapper supvFileMapper;

    @Override
    public boolean planUpload(MultipartFile file,  String planId, Integer type,String attachmentType) {
        SupvFile supvFile = this.getOne(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId,planId).eq(SupvFile::getType,type).eq(SupvFile::getAttachmentType,attachmentType));
        String url = fileStorageUtil.uploadMultipart(file, OssPath.SURVEY_RESULT);
        SupvFile supvFilePO = new SupvFile();
        supvFilePO.setAttachmentName(file.getOriginalFilename());
        supvFilePO.setFileUrl(url);
        if(Objects.nonNull(supvFile)){
            fileStorageUtil.deleteFile(supvFile.getFileUrl());
            supvFilePO.setUuid(supvFile.getUuid());
            return this.updateById(supvFilePO);
        }
        supvFilePO.setAttachmentType(attachmentType);
        supvFilePO.setBusiId(planId);
        supvFilePO.setType(type);
        supvFilePO.setUploaderId(RequestUtil.getUserIndex());
        supvFilePO.setUploadTime(LocalDateTime.now());
        supvFilePO.setUploaderName(RequestUtil.getUsername());
        return this.save(supvFilePO);
    }

    @Override
    public String detail(HttpServletResponse response,String busId, Integer type,String attachmentType) {
        SupvFile supvFile = this.getOne(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId,busId).eq(SupvFile::getType,type).eq(SupvFile::getAttachmentType,attachmentType));
        if(Objects.nonNull(supvFile)){
            fileStorageUtil.downloadStream(response,supvFile.getFileUrl());
            return null;
        }else {
            throw new BusinessException("不存在附件");
        }
    }
}
