package com.qmth.exam.reserve.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.time.Duration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qmth.boot.core.fss.store.impl.OssStore;
import com.qmth.boot.tools.models.ByteArray;
import com.qmth.exam.reserve.config.WxProperty;
import com.qmth.exam.reserve.service.FileUploadService;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    private final static Logger log = LoggerFactory.getLogger(FileUploadServiceImpl.class);

    @Autowired
    private WxProperty property;

    @Override
    public String uploadFile(String dirName, File file) {
        try {
            OssStore store = new OssStore(property.getServer(), property.getConfig());
            String filePath = dirName + "/" + file.getName();
            store.write(filePath, Files.newInputStream(file.toPath()), ByteArray.md5(file).toHexString());
            String url = store.getPresignedUrl(filePath, Duration.ofMinutes(5));
            store.close();
            return url;
        } catch (Exception e) {
            log.warn("文件上传出错", e);
        }
        return null;
    }

    @Override
    public String uploadByText(String dirName, String text, String fileName) {
        try {
            OssStore store = new OssStore(property.getServer(), property.getConfig());
            String filePath = dirName + "/" + fileName;
            ByteArray data = ByteArray.fromString(text);
            store.write(filePath, new ByteArrayInputStream(data.value()), ByteArray.md5(data.value()).toHexString());
            String url = store.getPresignedUrl(filePath, Duration.ofMinutes(5));
            store.close();
            return url;
        } catch (Exception e) {
            log.warn("文件上传出错", e);
        }
        return null;
    }

}
