package com.jiuzhekan.cbkj.service.testBusiness;

import com.jiuzhekan.cbkj.beans.sysBeans.ResEntity;
import com.jiuzhekan.cbkj.common.utils.Constant;
import com.jiuzhekan.cbkj.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

/**
 * UploadService
 * <p>
 * 杭州聪宝科技有限公司
 * <p>
 *
 * @author guowei
 * @date 2021/4/23 11:10
 */
@Service
@Slf4j
public class UploadService {


    @Value("${file.address}")
    private String location;

    @Value("${root.preview}")
    private String preview;

    @Value("${root.upload.relative}")
    private String relative;

    private static final String BASE64_IMAGES_PNG = "data:image/png;base64,";


    /**
     * 上传文件到当前服务器
     *
     * @param file file
     * @return com.jiuzhekan.cbkj.beans.sysBeans.ResEntity
     * @author guowei
     * @date 2021/4/23
     */
    public ResEntity uploadMultipartFile(MultipartFile file) {

        if (file == null || file.isEmpty()) {
            return new ResEntity(false, "未选择文件", null);
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        StringBuilder filePath = new StringBuilder(relative)
                .append(DateUtil.getDateFormats(DateUtil.date5, null))
                .append("/")
                .append(UUID.randomUUID().toString())
                .append(suffix);
        File dest = new File(String.format("%s%s", location, filePath.toString()));
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            //保存文件
            file.transferTo(dest);
            return new ResEntity(true, Constant.SUCCESS_DX, preview + filePath.toString());
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return new ResEntity(false, "服务异常", null);
        }
    }


    /**
     * 上传base64文件到当前服务器
     *
     * @param baseStr baseStr
     * @return com.jiuzhekan.cbkj.beans.sysBeans.ResEntity
     * @author guowei
     * @date 2021/4/23
     */
    public ResEntity uploadBase64PngImage(String baseStr) {

        if (StringUtils.isBlank(baseStr)) {
            return ResEntity.error("base64不能为空");
        }

        if (!baseStr.startsWith(BASE64_IMAGES_PNG)) {
            return ResEntity.error("base64内容不是png图片");
        }

        baseStr = baseStr.replace(BASE64_IMAGES_PNG, "");
        byte[] bytes;
        try {

            bytes = Base64.getDecoder().decode(baseStr);
        } catch (Exception e) {
            e.printStackTrace();
            return ResEntity.error("base64无法转文件");
        }

        StringBuilder sb = new StringBuilder(relative)
                .append(DateUtil.getDateFormats(DateUtil.date5, null))
                .append("/")
                .append(UUID.randomUUID().toString())
                .append(".png");
        File file = new File(String.format("%s%s", location, sb.toString()));
        //判断文件父目录是否存在
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        try {
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            return ResEntity.success(preview + sb.toString());
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return ResEntity.error("服务异常");
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
