package cn.com.poc.common.rest.impl;

import cn.com.poc.common.model.BizFileUploadRecordModel;
import cn.com.poc.common.rest.BosRest;
import cn.com.poc.common.service.BizFileUploadRecordService;
import cn.com.poc.common.service.BosConfigService;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.MD5Util;
import cn.com.poc.common.utils.MD5Utils;
import cn.hutool.crypto.digest.MD5;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@Component
public class BosRestImpl implements BosRest {

    @Resource
    private BosConfigService bosConfigService;

    @Resource
    private BizFileUploadRecordService bizFileUploadRecordService;

    @Override
    public String upload(MultipartFile file) throws IOException {
        Assert.notNull(file);
        String contentType = file.getContentType();
        String originalFilename = file.getOriginalFilename();
        String prefix = originalFilename.substring(originalFilename.lastIndexOf(".")).replaceAll("\\.", "");

        String upload = bosConfigService.upload(file.getInputStream(), prefix, contentType);

        //计算文件MD5值
        InputStream inputStream = file.getInputStream();
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        String md5 = MD5.create().digestHex(bytes);

        BizFileUploadRecordModel bizFileUploadRecordModel = new BizFileUploadRecordModel();
        bizFileUploadRecordModel.setFileName(file.getOriginalFilename());
        bizFileUploadRecordModel.setFileUrl(upload);
        bizFileUploadRecordModel.setMd5(md5);
        bizFileUploadRecordModel.setCoverSheetUrl("");
        bizFileUploadRecordService.save(bizFileUploadRecordModel);
        return upload;
    }
}
