package com.starry.admin.modules.weichat.utils;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.starry.admin.common.exception.CustomException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import ws.schild.jave.Encoder;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;

@Slf4j
public class WxFileUtils {

    /**
     * 下载微信临时素材文件
     *
     * @param access_token
     *            微信token
     * @param mediaId
     *            素材ID
     * @return InputStream
     * @throws IOException
     *             IOException
     */
    public static InputStream getTemporaryMaterial(String access_token, String mediaId) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id="
                + mediaId;
        // 请求参数
        HashMap<String, String> param = new HashMap<>();
        param.put("media_id", mediaId);
        // 获取到http连接对象
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(param));
        httpPost.setEntity(stringEntity);
        // 打开链接发送请求 获取到返回的流
        CloseableHttpClient build = HttpClients.custom().build();
        CloseableHttpResponse execute = build.execute(httpPost);
        return execute.getEntity().getContent();
    }

    public static void audioConvert2Mp3(File source, File target) {
        if (FileUtil.isEmpty(source)) {
            log.error("从微信下载的临时素材文件为空");
            throw new CustomException("音频文件上传失败");
        }
        try {
            AudioAttributes audio = new AudioAttributes();
            audio.setCodec("libmp3lame");
            audio.setBitRate(228000);
            audio.setChannels(2);
            audio.setSamplingRate(44100);
            EncodingAttributes attrs = new EncodingAttributes();
            attrs.setOutputFormat("mp3");
            attrs.setAudioAttributes(audio);
            Encoder encoder = new Encoder();
            encoder.encode(new MultimediaObject(source), target, attrs);
        } catch (Exception ex) {
            log.error("音频文件格式转化失败", ex);
            throw new CustomException("音频文件上传失败");
        }
    }

}
