package com.dsk.component;

import com.dsk.common.core.domain.R;
import com.dsk.oss.core.OssClient;
import com.dsk.oss.entity.UploadResult;
import com.dsk.oss.factory.OssFactory;
import com.dsk.system.domain.SysUserFileRecord;
import com.dsk.system.domain.vo.SysOssVo;
import com.dsk.system.service.ISysOssService;
import com.dsk.system.service.ISysUserFileRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * 上传组件
 * @author lcl
 * @create 2023/9/15
 */
@Component
public class UploadComponent {

    @Autowired
    private ISysOssService ossService;
    @Autowired
    private ISysUserFileRecordService fileRecordService;

    public R<SysOssVo> upload(String title, ByteArrayOutputStream ba, String suffix, String contentType) {
        ByteArrayInputStream bio = new ByteArrayInputStream(ba.toByteArray());
        OssClient client = OssFactory.instance();
        UploadResult uploadResult = client.uploadSuffix(bio, suffix, contentType);
        //总文件记录
        SysOssVo sysOssVo = ossService.buildResultEntity(title.concat(suffix), suffix, client.getConfigKey(), uploadResult);
        //用户文件记录
        fileRecordService.add(new SysUserFileRecord(sysOssVo.getOriginalName(), 1, sysOssVo.getUrl()));
        return R.ok(sysOssVo);
    }
}
