package com.cool.bang.common.tools.file;

import com.alibaba.fastjson.JSONObject;
import com.cool.bang.common.constant.FileConstant;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

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

/**
 * 上传
 *
 * @author PeiZhi Guo
 * 2023-3-7 17:11
 */
public class UploadUtil {

    private static final Logger logger = LoggerFactory.getLogger(UploadUtil.class);

    /**
     * 上传文件
     */
    public static String upload(String fileName, String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("文件读取异常");
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                os.write(buffer, 0, len);
            }
            in.close();
            os.close();
            byte[] bytes = os.toByteArray();
            // 转BASE64编码字符串
            BASE64Encoder encoder = new BASE64Encoder();
            String base64 = encoder.encodeBuffer(bytes).trim();
            return uploadBase64(fileName, base64, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 上传文件
     */
    public static String uploadBase64(String fileName, String base64, Integer isZip) {
        String fileId = "";
        String url = FileConstant.IN_URL + FileConstant.UPLOAD_BASE64;
        try {
            //参数
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("fileName", fileName);
            params.put("base64File", base64);
            params.put("ysbs", isZip.toString());

            //调用接口
            String json = HttpUtil.post(url, params);

            //解析数据
            JSONObject jObj = JSONObject.parseObject(json);
            String code = jObj.getString("code");
            if (code.equals("S000")) {
                JSONObject dataObj = jObj.getJSONObject("data");
                fileId = dataObj.getString("ywjid");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileId;
    }
}
