package com.engine.htsc.image.service.impl;

import com.engine.core.impl.Service;
import com.engine.htsc.image.service.ImageBase64Service;
import sun.misc.BASE64Decoder;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ImageBase64ServiceImpl extends Service implements ImageBase64Service {

    @Override
    public Map<String, Object> generate2Image(Map<String, Object> param) {
        BaseBean bb = new BaseBean();
        Map<String, Object> apimap = new HashMap<String, Object>();

//        String lcbh = Util.null2String(param.get("lcbh"));
        String workFlowNum = "";
//        try {
//            workFlowNum = new String(lcbh.getBytes("GBK"), System.getProperty("sun.jnu.encoding"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        //String ngr = Util.null2String(param.get("ngr"));
        long currentTime = System.currentTimeMillis() ;
        String folderName = currentTime + "";
        String fileName = workFlowNum + currentTime + "_new.png";
        String path = "/home/appadmin/png/"+folderName+"/"+fileName;

        String base64Str = Util.null2String(param.get("pdf"));
        System.out.println(base64Str);
        bb.writeLog(base64Str);
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(base64Str);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File tempFile = new File(path);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            out = new FileOutputStream(tempFile);
            out.write(b);
            out.flush();
            out.close();
        } catch (Exception e) {
            apimap.put("code","-100");
        }finally {
            if(out !=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        apimap.put("code","100");
        return apimap;
    }


}
