package com.hz.pm.api.external;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * <p>
 * MhExpertQrCodeClient
 * </p>
 *
 * @author WendyYang
 * @since 21:40 2023/12/28
 */
@Slf4j
@Component
public class MhExpertQrCodeGenClient {

    @Value("${mh.expert-qr-code-url:}")
    private String mhExpertQrCodeGenUrl;

    public String genExpertQrCode(String expertId) {
        if (StrUtil.isBlank(expertId)) {
            return StrUtil.EMPTY;
        }
        try {
            String urlString = mhExpertQrCodeGenUrl + "?id=" + expertId;
            String decode = URLDecoder.decode(urlString, StandardCharsets.UTF_8);
            URL url = URLUtil.url(decode);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();
            byte[] bytes = IoUtil.readBytes(inputStream);
            IoUtil.close(inputStream);
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            log.error("获取专家码异常：{}", expertId, e);
            return StrUtil.EMPTY;
        }
    }

}

