package com.chinaweal.aiccs.crgs.transfor.sdk;

import cn.hutool.core.codec.Base64Encoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
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 org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/11/2 18:35
 **/
@Slf4j
@Service
public class UploadSDK {

    @Value("${ot.uploadUrl}")
    private String uploadUrl;

    @Value("${ot.eap_username}")
    private String userName;

    @Value("${ot.eap_password}")
    private String password;

    /**
     * 上传行政处罚信息文件
     *
     * @param filePath 文件路径
     * @return 上传结果
     * @author lroyia
     * @since 2021年11月2日 19:03:07
     */
    public String uploadNCase2(String filePath) {
        DataHandler dataHandler = new DataHandler(new FileDataSource(filePath));
        //调用接口
        ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
        factory.setServiceClass(UploadWebserviceBO.class);
        //eap_username用户名 eap_password密码
        factory.setAddress(String.format(uploadUrl, userName, password));
        factory.getServiceFactory().setDataBinding(new AegisDatabinding());
        UploadWebserviceBO service = (UploadWebserviceBO) factory.create();
        //上传并获取接口返回结果
        return service.uploadCreditInfoByCase(dataHandler);
    }

    public String uploadNCase(String filePath) {
        String fileStr = "";
        File file = new File(filePath);
        try (InputStream is = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            IOUtils.copy(is, bos);
            byte[] data = bos.toByteArray();
            // 转换成base64
            Base64Encoder base64Encoder = new Base64Encoder();
            fileStr = base64Encoder.encode(data);
//            System.out.println("------------------------------------");
//            System.out.println(fileStr);
//            System.out.println("------------------------------------");
        } catch (Exception e) {
            log.info("上传行政处罚信息文件异常", e);
        }
        String str = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:upl=\"http://upload.bo.creditinfotransfer.datacollection.unieap.neusoft.com/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <upl:uploadCreditInfoByCase>\n" +
                "         <!--Optional:-->\n" +
                "         <upl:arg0>" + fileStr + "</upl:arg0>\n" +
                "      </upl:uploadCreditInfoByCase>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        try (CloseableHttpClient client = HttpClients.createDefault()){
            HttpPost postMethod = new HttpPost(String.format(uploadUrl, userName, password));
            postMethod.setHeader("Content-Type", "text/xml; charset=utf-8");

            postMethod.setEntity(new StringEntity(str));
            CloseableHttpResponse execute = client.execute(postMethod);
            int statusCode = execute.getStatusLine().getStatusCode();
            String soapResponseData = EntityUtils.toString(execute.getEntity(), StandardCharsets.UTF_8);
            //200说明正常返回数据
            if (statusCode == 200) {
                log.info("{}异地流转行政处罚上传接口，返回结果：{}", filePath, soapResponseData);
                int z = soapResponseData.indexOf("<ns1:return>");
                int j = soapResponseData.indexOf("</ns1:return>");
                fileStr = soapResponseData.substring(z + "<ns1:return>".length(), j);
            } else {
                log.info("{}异地流转行政处罚上传接口，状态值：{}", filePath, statusCode);
            }
        } catch (Exception e) {
            log.error("上传报错", e);
        }
        return fileStr;
    }

    /**
     * 上传行政许可信息文件
     *
     * @param filePath 文件路径
     * @return 上传结果
     * @author lroyia
     * @since 2021年11月2日 19:08:26
     */
    public String uploadPermit2(String filePath) {
        //xls文件地址
        DataHandler dataHandler = new DataHandler(new FileDataSource(filePath));
        //调用接口
        ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
        factory.setServiceClass(UploadWebserviceBO.class);
        //eap_username用户名 eap_password密码
        factory.setAddress(String.format(uploadUrl, userName, password));
        factory.getServiceFactory().setDataBinding(new AegisDatabinding());
        UploadWebserviceBO service = (UploadWebserviceBO) factory.create();
        //上传并获取接口返回结果
        return service.uploadCreditInfoByPermit(dataHandler);
    }

    public String uploadPermit(String filePath) {
        String fileStr = "";
        File file = new File(filePath);
        try (InputStream is = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            IOUtils.copy(is, bos);
            byte[] data = bos.toByteArray();
            // 转换成base64
            Base64Encoder base64Encoder = new Base64Encoder();
            fileStr = base64Encoder.encode(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:upl=\"http://upload.bo.creditinfotransfer.datacollection.unieap.neusoft.com/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <upl:uploadCreditInfoByPermit>\n" +
                "         <!--Optional:-->\n" +
                "         <upl:arg0>" + fileStr + "</upl:arg0>\n" +
                "      </upl:uploadCreditInfoByPermit>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        try (CloseableHttpClient client = HttpClients.createDefault()){
            HttpPost postMethod = new HttpPost(String.format(uploadUrl, userName, password));
            postMethod.setHeader("Content-Type", "text/xml; charset=utf-8");
            postMethod.setEntity(new StringEntity(str));
            CloseableHttpResponse response = client.execute(postMethod);
            int statusCode = response.getStatusLine().getStatusCode();
            String soapResponseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            //200说明正常返回数据
            if (statusCode == 200) {
                log.info("{}异地流转行政处罚上传接口，返回结果：{}", filePath, soapResponseData);
                int z = soapResponseData.indexOf("<ns1:return>");
                int j = soapResponseData.indexOf("</ns1:return>");
                fileStr = soapResponseData.substring(z + "<ns1:return>".length(), j);
            } else {
                log.info("{}异地流转行政处罚上传接口，状态值：{}", filePath, statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileStr;
    }
}
