package com.hfkj.channel.weixin.utils;

import com.alibaba.fastjson.JSON;
import com.wechat.pay.contrib.apache.httpclient.WechatPayUploadHttpPost;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
/**
 * 微信工具类
 * @className: WeiXinUtil
 * @author: HuRui
 * @date: 2022/11/17
 **/
public class WeiXinUploadUtil {

    /**
     * 【服务商、电商】图片上传
     * @param filePath 全路径文件
     * @return
     */
    public static String uploadMediaImgFile(String filePath) throws IOException {
        HttpClientBuilder clientBuilder = new HttpClientBuilder();
        CloseableHttpClient httpClient = clientBuilder.getHttpClient();
        try {
            URI uri = new URI("https://api.mch.weixin.qq.com/v3/merchant/media/upload");
            File file = new File(filePath);
            try (FileInputStream ins1 = new FileInputStream(file)) {
                String sha256 = DigestUtils.sha256Hex(ins1);
                try (InputStream ins2 = new FileInputStream(file)) {
                    HttpPost request = new WechatPayUploadHttpPost.Builder(uri)
                            // 如需直接设置媒体文件元信息，可使用withFile代替withImage
                            .withImage(file.getName(), sha256, ins2)
                            .build();
                    CloseableHttpResponse response = httpClient.execute(request);
                    String bodyAsString = EntityUtils.toString(response.getEntity());
                    System.out.println(bodyAsString);
                    if (StringUtils.isNotBlank(bodyAsString)) {
                        return JSON.parseObject(bodyAsString).getString("media_id");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();;
        }
        return null;
    }


}
