package com.youlai.boot.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.common.util.SystemUtil;
import com.youlai.boot.system.mapper.ConfigMapper;
import com.youlai.boot.system.mapper.DemandFileMapper;
import com.youlai.boot.system.model.entity.Config;
import com.youlai.boot.system.model.entity.DemandFile;
import com.youlai.boot.system.service.ConfigService;
import com.youlai.boot.system.service.DemandFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class DemandFileServiceImpl extends ServiceImpl<DemandFileMapper, DemandFile> implements DemandFileService {

    private final ConfigService configService;


    @Override
    public List<DemandFile> findByDemandId(Long demandId) {

        List<DemandFile> list = this.lambdaQuery().eq(DemandFile::getDemandId, demandId).list();

        return list;
    }

    @Override
    public String saveDemandFile(MultipartFile file, Long demandId) {

        log.info("接收到文件 {}",file.getName());

        String demandFilePathPrefix = configService.getSystemConfig("demand-file").toString();

        String fileName = SystemUtil.renameFile(Objects.requireNonNull(file.getOriginalFilename()));

        String absPath = demandFilePathPrefix + File.separator + fileName;

        File destFile = new File(absPath);

        try (FileOutputStream fos = new FileOutputStream(destFile)) {
            log.info("写入文件 {}",file.getOriginalFilename());
            fos.write(file.getBytes());
            DemandFile demandFile = new DemandFile();
            demandFile.setDemandId(demandId);
            demandFile.setFileName(file.getOriginalFilename());
            demandFile.setFilePath(absPath);
            this.save(demandFile);
            return absPath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return null;
        }


    }
}
