package com.bonus.canteen.core.common.export.service;

import com.bonus.canteen.core.common.utils.SysUtil;
import com.bonus.common.houqin.oss.OssProperties;
import com.bonus.common.houqin.oss.service.OssTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
public class ExportUploadManager {
   private static final Logger log = LoggerFactory.getLogger(ExportUploadManager.class);
   @Resource
   @Lazy
   private OssProperties ossProperties;
   @Resource
   @Lazy
   private OssTemplate ossTemplate;

   public String upload(String fileName, File tempFile, String merchantIdString) throws Exception {
      log.info("上传文件到OSS：{}", fileName);
      StringBuilder filePath = new StringBuilder();
      filePath.append(merchantIdString).append("/export").append("/").append(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))).append("/").append(fileName);
      InputStream inputStream = Files.newInputStream(tempFile.toPath());

      try {
         this.ossTemplate.putObject(this.ossProperties.getBucketName(), filePath.toString(), inputStream);
      } catch (Throwable var9) {
         if (inputStream != null) {
            try {
               inputStream.close();
            } catch (Throwable var8) {
               var9.addSuppressed(var8);
            }
         }

         throw var9;
      }

      if (inputStream != null) {
         inputStream.close();
      }

      String var10000 = this.ossProperties.getBucketName();
      return "/" + var10000 + "/" + String.valueOf(filePath);
   }

   public void remove(String fileUrl) throws Exception {
      log.info("删除OSS文件：{}", fileUrl);
      this.ossTemplate.removeObject(this.ossProperties.getBucketName(), SysUtil.getObjectName(fileUrl));
   }
}
