package com.esv.freight.file.module.file.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.util.FileUtils;
import com.esv.freight.file.module.file.form.FileForm;
import com.esv.freight.file.module.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @description:
 * @project: freight-file-service
 * @name: com.esv.freight.file.module.file.service.impl.FileServiceImpl
 * @author: 黄朝斌
 * @email: huangchaobin@esvtek.com
 * @createTime: 2020/05/28 14:53
 * @version:1.0
 */
@Service("fileService")
@Slf4j
@RefreshScope
public class FileServiceImpl implements FileService {

    @Value("${file.register}")
    private String FILE_REGISTER;

    @Override
    public void checkFile(FileForm fileForm) throws EException {
        String[] types = FILE_REGISTER.trim().replaceAll("，", ",").split(",");
        String type;
        JSONObject fileTypeJson = new JSONObject();
        for (int i = 0; i < types.length; i++) {
            type = types[i];
            fileTypeJson.put(type.split("=")[0], Integer.parseInt(type.split("=")[1]));
        }

        // 校验文件类型
        String fileType = fileForm.getFileType();
        if (!fileTypeJson.containsKey(fileType)) {
            throw new EException(1001, "不支持的文件类型["+fileType+"]");
        }

        // 校验文件长度
        String fileData = fileForm.getFileData();
        byte[] bytes = Base64.getDecoder().decode(fileData);
        int fileRegSize = fileTypeJson.getIntValue(fileType);
        int fileMaxSize = fileRegSize * 1024 * 1024;
        if (fileMaxSize < bytes.length) {
            throw new EException(1002, "文件大小不能超过["+fileRegSize+"MB]");
        }

        // 校验是否有效图片
        if ("image".equals(fileType) && !FileUtils.isValidImage(bytes)) {
            throw new EException(1001, "不是有效图片");
        }
    }

    @Override
    public void checkIsImage(String fileData) throws EException {
        byte[] bytes = Base64.getDecoder().decode(fileData);
        Image image;
        try {
            image = ImageIO.read(new ByteArrayInputStream(bytes));
        } catch (IOException e) {
            throw new EException(1100, "不是有效图片");
        }
        if (null == image) {
            throw new EException(1010, "不是有效图片");
        }
    }
}
