package com.lakala.zf.laop.java.sdk.demo.v2;

import com.lakala.zf.laop.java.sdk.demo.BaseCommonDemo;
import com.lkl.laop.sdk.LKLSDK;
import com.lkl.laop.sdk.request.V2LaepCreateEleReceiptRequest;
import com.lkl.laop.sdk.utils.JsonUtils;

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

/**
 * @author nxj
 * @date 2024/1/17 10:18
 * @description 账管家V2.0-生成电子回单DEMO
 */
public class V2LaepCreateEleReceiptRequestDemo extends BaseCommonDemo {
    public static void main(String[] args) throws Exception {
        // 1. 配置初始化
        doInit();

        //2. 装配数据
        V2LaepCreateEleReceiptRequest req = new V2LaepCreateEleReceiptRequest();
        req.setBmcpNo("1");
        req.setMercId("8221000581200BS");
        req.setAcctSysSq("663321182762102784");
        //3. 发送请求
        String response = LKLSDK.httpPost(req);

        //下载文件
        //downloadFile(response);

        //4. 响应
        System.out.println(response);
    }

    private static void downloadFile(String response) {
        Map parse = JsonUtils.parse(response, Map.class);
        Object respData = parse.get("respData");
        Map parse1 = JsonUtils.parse(JsonUtils.toJSONString(respData), Map.class);
        String fileName = parse1.get("fileName").toString();
        String fileObject = parse1.get("fileObject").toString();
        boolean downResult = base64str2File(fileObject, "./" + fileName);
        System.out.println("下载结果:" + downResult);
    }


    public static boolean base64str2File(String base64FileStr, String filePath) {

        if (base64FileStr == null) {
            return false;
        }
        //判断文件夹是否存在
        File outputFile = new File(filePath);
        File fileP = outputFile.getParentFile();
        if (!fileP.exists() && !fileP.mkdirs() && !fileP.mkdir()) {
            throw new IllegalArgumentException("创建文件目录失败");
        }
        Base64.Decoder decoder = Base64.getDecoder();
        OutputStream out = null;
        try {
            // Base64解码,对字节数组字符串进行Base64解码并生成文件
            byte[] byt = decoder.decode(base64FileStr);
            InputStream input = new ByteArrayInputStream(byt);
            // 生成指定格式的文件
            out = new FileOutputStream(filePath);
            byte[] buff = new byte[1024];
            int len;
            while ((len = input.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
