package com.xunmei.sync.service.api;

import com.xunmei.common.core.exception.SystemException;
import com.xunmei.common.core.http.service.CustomHttpClient;
import com.xunmei.common.core.http.service.params.HttpParams;
import com.xunmei.common.core.http.service.result.ResultExecute;
import com.xunmei.sync.config.ThirdPartySystemConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@Component
public class FjnxXmlApi implements ResultExecute {
    @Autowired
    private CustomHttpClient httpClient;

    @Autowired
    private ThirdPartySystemConfig thirdPartySystemConfig;

    public <T> T get(final HttpParams httpParams) {
        httpParams.setUrl(this.thirdPartySystemConfig.getFjnxPortalIp() + httpParams.getUrl());
        return this.httpClient.execute(httpParams, this);
    }

    @Override
    public Object toBody(final Response response, final HttpParams request, final StopWatch stopWatch) throws Exception {

        final String body = response.body()
                .string();
        if (response.code() != 200 && response.code()!=0 ) {
            throw new SystemException("100002", String.format("[ %s ] => [ %s ]", request, body));
        }
        else if(response.code() == 1)
        {
            // 文件下载失败
        } else if (response.code() == 500) {
            // 统一运营门户系统服务异常
        }
        return body;
    }

    public static String httpGet(String urlStr)
    {
        try
        {
            URL url = new URL(urlStr);
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);

            conn.setDoInput(true);

            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("Get");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
//            byte[] data = xml.getBytes();
            // 设置文件长度
            //conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "text/xml");
            // 开始连接请求
            conn.connect();
//            OutputStream out = conn.getOutputStream();
            // 写入请求的字符串
//            out.write(data);
//            out.flush();
//            out.close();

            // 请求返回的状态
            if (conn.getResponseCode() == 200)
            {
                // 请求返回的数据
                InputStream in = conn.getInputStream();
                try
                {
                    ByteArrayOutputStream s = new ByteArrayOutputStream();
                    int length = 0;
                    byte[] buffer = new byte[1024 * 1024];
                    while ((length = in.read(buffer)) != -1)
                    {
                        s.write(buffer, 0, length);
                    }
                    return s.toString("UTF-8");

                }
                catch (Exception e1)
                {
                    e1.printStackTrace();
                }
                finally
                {
                    in.close();
                }
            }
            else if(conn.getResponseCode() == 1)
            {
                // 文件下载失败
            } else if (conn.getResponseCode() == 500) {
                // 统一运营门户系统服务异常
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T convertXmlToJavaBean(String xml, Class<T> t) throws Exception
    {
        T obj;
        JAXBContext context = JAXBContext.newInstance(t);
        StringReader stringReader = new StringReader(xml);
        SAXParserFactory sax = SAXParserFactory.newInstance();
        sax.setNamespaceAware(false);// 设置忽略明明空间
        XMLReader xmlReader = sax.newSAXParser().getXMLReader();
        Source source = new SAXSource(xmlReader, new InputSource(stringReader));
        Unmarshaller unmarshaller = context.createUnmarshaller();
        obj = (T) unmarshaller.unmarshal(source);
        return obj;
    }
}
