package com.yanzuoguang.wxxcx.base;

import com.yanzuoguang.util.helper.HttpHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李贤军
 */
@Component
public class WxXcxRequestByteArrayImpl implements WxXcxByteArrayRequest {

    @Value("${yzg.wx.xwx.charset:utf-8}")
    private String defaultCharSet;

    @Override
    public byte[] request(WxXcxRequestUrl req, WxXcxResponseArrayByteConvert convert) {
        String url = req.getUrl();
//        String charSet = defaultCharSet;
        String charSet = "utf-8";
        Map<String, String> header;
        if (req instanceof WxXcxRequestHeader) {
            // 设置header信息
            header = ((WxXcxRequestHeader) req).getHeader();
        } else {
            header = new HashMap<>(0);
        }
        byte[] response = null;
        try {
            if (req instanceof WxXcxRequestPostFormData) {
                WxXcxRequestPostFormData post = (WxXcxRequestPostFormData) req;
                HttpURLConnection conn = HttpHelper.getConn(url, header);
                response = HttpHelper.postResultByteArray(conn, post.getPost());
            } else if (req instanceof WxXcxRequestPostApplication) {
                WxXcxRequestPostApplication post = (WxXcxRequestPostApplication) req;
                // 打开URL连接
                java.net.HttpURLConnection httpConn = HttpHelper.getConn(url, header, true);
                response = HttpHelper.postResultByteArray(httpConn, post.getPost());
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return convert.getResponse(response);
    }
}