package com.bcxin.rest.web.commons;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.bcxin.Infrastructures.TenantConfigProperty;
import com.bcxin.Infrastructures.exceptions.BadTenantException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public interface FileProcessor {
    String save(MultipartFile file);

    String save(String bStream);

    @Component
    public static class FileProcessorImpl implements FileProcessor {
        private final Logger logger = LoggerFactory.getLogger(FileProcessorImpl.class);
        private final TenantConfigProperty configProperty;

        public FileProcessorImpl(TenantConfigProperty configProperty) {
            this.configProperty = configProperty;
        }

        @Override
        public String save(MultipartFile file) {
            String relativePath = FileProcessor.getPath(file.getOriginalFilename());
            String destFileName = String.format("%s%s", configProperty.getUpload().getPath(),relativePath);
            File destFile = new File(destFileName);
            FileUtil.mkdir(destFile.getParentFile());
            try {
                destFile.createNewFile();
                file.transferTo(destFile);
            } catch (IOException e) {
                throw new BadTenantException("文件创建失败");
            }
            return relativePath;
        }

        @Override
        public String save(String bStream) {
            if (StringUtils.isEmpty(bStream)) {
                logger.info("2.BASE64-BadTenantException=文件不能为空");
                throw new BadTenantException("文件不能为空");
            }
            if (!bStream.startsWith("data:image/") || !bStream.contains(";base64,")) {
                logger.info("3.BASE64-BadTenantException=格式不正确");
                throw new BadTenantException("格式不正确");
            }
            logger.info("4.BASE64-save=star");
            String head = bStream.split(",")[0];
            String blob = bStream.split(",")[1];
            String imgSign = head.split(";")[0];
            String imgType = imgSign.split("/")[1];
            String filename = System.currentTimeMillis() + "." + imgType;
            String relativePath = FileProcessor.getPath(filename);
            logger.info("5.BASE64-save.relativePath=" + relativePath);
            String destFileName = String.format("%s%s", configProperty.getUpload().getPath(), relativePath);
            logger.info("6.BASE64-save.destFileName=" + destFileName);
            byte[] bytes = Base64.decodeBase64(blob);
            File destFile = new File(destFileName);
            FileUtil.mkdir(destFile.getParentFile());

            FileUtil.writeBytes(bytes, destFile);

            logger.info("8.BASE64-save.result=" + relativePath);

            return relativePath;
        }
    }

    public static String getPath(String filename) {
        if (StrUtil.isEmpty(filename)) {
            throw new BadTenantException("文件不能为空");
        }
        filename = filename.trim().replace("+", "");
        return String.format("/uploads/%s/%s/%s",DateUtil.format(new Date(),"yyyy/MM-dd"),UUID.randomUUID(),filename);
    }
}
