package com.saye.hospitalgd.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

/**
 * @author thuang
 * @version 1.0
 * @description: 支付宝对账文件下载
 * @date 2021/8/9 14:49
 */
@Slf4j
public class AlipayUtil {

    private AlipayConfig alipayConfig;

    public AlipayUtil(String serverUrl,String appId,String privateKey,String publicKey){
        // 获取支付宝支付的配置信息

        alipayConfig = new AlipayConfig();
        //url 测试改成沙箱的地址

        serverUrl="https://openapi.alipaydev.com/gateway.do";
        alipayConfig.setServerUrl(serverUrl);

        //商户appid
        appId="2021000118603047";
        alipayConfig.setAppId(appId);

        //商户私钥
        privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCiqA0Y3wms1/2QJrLSJdiDNBzE/Ta9idvvh7gmBbMY1wNeQPYl9yVMXceTU4BjyKjFZwckzos76sWekMpo1AHIRgcyNbXjFGv/sFJdd8261pvkcetkfWcaF5bn+11zWED2Ar04iZxNY2voSvKCUcMdPx7cp+lmX0+VQkZ+2XCtnljfl3fvfk7/HHG7sdDBnfuACWr5cMyTJ4dfPE7V68jOJsf3d+zo3p3WBTfvi03QxJZ5ub/JVn88gM4ekVa9k5Z0U8kDRUWwNlv8TbPjPqSZO9KXdZyVpHVJXygAj9dCapb/WU5DJI6YpwEdVnZlMhR2zN8DutYvPgFlITvqMeOhAgMBAAECggEBAIHInUqvDEVBwix29FABqpRlzF7RvA/YJAknvaN5AMJdLW7TXpREcxpP6aKACf2UajW4U1bnBum0FiLDXP3vy8xFNBC4En0yGkpW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Kcquz/FrNPavJE4cqSyTlHF1EhMRerLrXevVnXdWg=";
        alipayConfig.setPrivateKey(privateKey);

        //格式使用默认

        //编码使用默认

        //公钥
        publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7HNXm2VP/vv030jAjdlWlL+Wzmr+Z0690DAzeYmkud2KODgoAM9GnIhYwmXLbFvNVevKZa0wXACKlEylG5tlUX0vXJaJizhRR+/9iAmgAZrVNbNXfQswekqcTDz7G31loKgmDhKZ1BqllOlZxXQ4/xMvcZhs6/u4sySxodVuciYGG95vL53uUyGfooSr2NG3gCXFsBcYS0WAE6NnYwj0FsY7DqtfqhQqD29V4JwPzM109phc5JC+IdDZR6ah69lpRXEgtuVZ2LPV0yDxzSyN3w4G2Pmnir9qj+xPlVKevXVgse3hLKiW2ZPuuaIFfOwM3sYUu2uHtxv0obzPIRWauwIDAQAB";
        alipayConfig.setAlipayPublicKey(publicKey);

        //应用公钥
        //MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoqgNGN8JrNf9kCay0iXYgzQcxP02vYnb74e4JgWzGNcDXkD2JfclTF3Hk1OAY8ioxWcHJM6LO+rFnpDKaNQByEYHMjW14xRr/7BSXXfNutab5HHrZH1nGheW5/tdc1hA9gK9OImcTWNr6EryglHDHT8e3KfpZl9PlUJGftlwrZ5Y35d3735O/xxxu7HQwZ37gAlq+XDMkyeHXzxO1evIzibH93fs6N6d1gU374tN0MSWebm/yVZ/PIDOHpFWvZOWdFPJA0VFsDZb/E2z4z6kmTvSl3WclaR1SV8oAI/XQmqW/1lOQySOmKcBHVZ2ZTIUdszfA7rWLz4BZSE76jHjoQIDAQAB
        //支付宝公钥
        //MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7HNXm2VP/vv030jAjdlWlL+Wzmr+Z0690DAzeYmkud2KODgoAM9GnIhYwmXLbFvNVevKZa0wXACKlEylG5tlUX0vXJaJizhRR+/9iAmgAZrVNbNXfQswekqcTDz7G31loKgmDhKZ1BqllOlZxXQ4/xMvcZhs6/u4sySxodVuciYGG95vL53uUyGfooSr2NG3gCXFsBcYS0WAE6NnYwj0FsY7DqtfqhQqD29V4JwPzM109phc5JC+IdDZR6ah69lpRXEgtuVZ2LPV0yDxzSyN3w4G2Pmnir9qj+xPlVKevXVgse3hLKiW2ZPuuaIFfOwM3sYUu2uHtxv0obzPIRWauwIDAQAB

        //AES密钥 Bg945nFXBEAcWtCHZ2Ay9w==

        //加密类型 使用默认
    }
    /**
     * 实现支付宝对账
     * @param
     * bill_type
     *  trade：商户基于支付宝交易收单的业务账单；
     *  signcustomer：基于商户支付宝余额收入及支出等资金变动的帐务账单。
     * bill_date 查询的账单时间
     * @return response
     */
    public void alipayBill(String bill_type,String bill_date) {
        log.info("==================向支付宝发起对账请求");


        try {
            //实例化客户端(参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型)
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getServerUrl(), alipayConfig.getAppId(),
                    alipayConfig.getPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
                    alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();//创建API对应的request类

            request.setBizContent("{" +
                    "\"bill_type\":\""+bill_type+"\"," +
                    "\"bill_date\":\""+bill_date+"\"}"); //设置业务参数
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            String billDownloadUrl = response.getBillDownloadUrl();
            log.info("==================支付宝返回文件下载地址：" + billDownloadUrl);
            downBill(billDownloadUrl); //调用下载文件方法
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }//通过alipayClient调用API，获得对应的response类
        //根据response中的结果继续业务逻辑处理
    }

    /**
     * 下载账单文件：
     *
     * @param
     * @return response
     */
    public String downBill(String billDownloadUrl) {
        long filename = new Date().getTime();

        //指定希望保存的文件路径
        String filePath = "D:/1/alipay/billfile/fund_bill_" + filename + ".zip";
        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            url = new URL(billDownloadUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setConnectTimeout(5 * 1000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
            httpUrlConnection.connect();
            fis = httpUrlConnection.getInputStream();
            byte[] temp = new byte[1024];
            int b;
            fos = new FileOutputStream(new File(filePath));
            while ((b = fis.read(temp)) != -1) {
                fos.write(temp, 0, b);
                fos.flush();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) fis.close();
                if (fos != null) fos.close();
                if (httpUrlConnection != null) httpUrlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        new AlipayUtil("","","","").alipayBill("trade","2021-08-10");

    }

}
