package com.bcxin.ars.strategy.ministerial;

import com.abcxin.smart.validator.annotation.MinisterialAttr;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * 照片处理
 *
 * @author zhangyutong
 */
@Component
public class PhotoMinDataFormatStrategy implements MinDataFormatStrategy {

    @Value("${base-folder}")
    private String folder;

    @Override
    public String format(Field columnField, Object data) {
        if(data == null){
            MinisterialAttr resource = columnField.getAnnotation(MinisterialAttr.class);
            return resource.defaultValue();
        }
        String path = (String) data;
        path = path.replace("getResource.do?path=", folder);
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in;
        byte[] bytes = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(path);
            bytes = new byte[in.available()];
            in.read(bytes);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }
}
