package com.hz.pm.api.irs;

import com.alibaba.fastjson.JSON;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.GetClient;
import com.hz.pm.api.AppTests;
import com.hz.pm.api.common.util.CryptUtils;
import com.hz.pm.api.common.util.HmacAuthUtil;
import com.hz.pm.api.common.util.RefreshKeyUtil;
import com.hz.pm.api.irs.manage.AppIrsManage;
import com.ningdatech.zwdd.ZwddIntegrationProperties;
import com.ningdatech.zwdd.client.ZwddAuthClient;
import com.ningdatech.zwdd.client.ZwddClient;
import com.ningdatech.zwdd.client.provider.ZwddAuthClientProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname IrsTest
 * @Description
 * @Date 2023/6/26 17:42
 * @Author PoffyZhang
 */
public class IrsTest extends AppTests {

    @Autowired
    private ZwddAuthClient zwddAuthClient;

    @Autowired
    private ZwddClient zwddClient;
    @Autowired
    private AppIrsManage appIrsManage;

    @Test
    public void test1() {
        String method = "GET";
        String url = "https://bcdsg.zj.gov.cn:8443/restapi/prod/IC33000020230427000001/irs-res-bill/report/pdfUrl" +
                "?appCode=A331123467587202210014168";
        String appScret = "BCDSGS_4ab4235d26a9a357170a39f3a13fd68c";
        String appKey = "BCDSGA_d874c8e46b541eb4e8aac6510fd3351b";

        Map<String, String> header = HmacAuthUtil.generateHeader(url, method, appKey, appScret);
        //请求头
        HttpHeaders headers = new HttpHeaders();

        for (Map.Entry<String, String> entry : header.entrySet()) {
            headers.add(entry.getKey(), entry.getValue());
        }
        //封装请求头
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.exchange(url, HttpMethod.GET, formEntity, String.class);

        System.out.println(JSON.toJSONString(forEntity));
    }

    @Test
    public void testApp() throws NoSuchAlgorithmException {
        long timestamp = System.currentTimeMillis();
        String areaCode = "331123";
        String appScret = "496f0f2a19994f76b4fd9dae087366c7";
        String appKey = "A331101453557202109017383";
        String appCode = "A331123467587202307014177";//A331123467587202307014171

        String requestSecret = RefreshKeyUtil.getRequestSecret(appKey, appScret,timestamp);
        String sign = CryptUtils.MD5Encode(appKey + requestSecret + timestamp);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/001003001029/dataSharing/XS8daav3bcemZ3Ra.htm?" +
                "requestTime=" + timestamp + "&sign=" + sign + "&appKey=" + appKey + "&name=&" +
                "pageSize=10&deptCode=&areaCode=" + areaCode + "&pageNum=1&appCode=" + appCode;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);

        System.out.println(JSON.toJSONString(forEntity));
    }

    @Test
    public void test2() throws NoSuchAlgorithmException {
        long timestamp = System.currentTimeMillis();
        String areaCode = "331123";
        String appKey = "A331101453557202109017383";
        String appScret = "496f0f2a19994f76b4fd9dae087366c7";
        String baseProjSys = "初次建设的应用21";
        String baseProjSysCode = "A331123467587202307014177";
        String baseProjName = "遂昌县-nsl-项目测试004";
        String baseProjId = "331123230130123412186";
        String requestSecret = RefreshKeyUtil.getRequestSecret(appKey, appScret,timestamp);

        String capCode = CryptUtils.MD5Encode(timestamp + areaCode);
        String capTime = String.valueOf(timestamp);
        String sign = CryptUtils.MD5Encode(appKey + requestSecret + timestamp);
        String url = "https://interface.zjzwfw.gov.cn/gateway/api/proxy/001003001029/dataSharing/94wbaL1I1Pbz0648.htm?requestTime=" + timestamp +
                "&sign=" + sign + "&appKey=" + appKey + "&capCode=" + capCode + "&capTime=" + capTime +
                "&baseProjSys=" + baseProjSys + "&areaCode=331123&baseProjName=" + baseProjName + "&baseProjId=" + baseProjId +
                "&isEffective=1&baseProjSysCode=" + baseProjSysCode;
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);

        System.out.println(JSON.toJSONString(forEntity));
    }

    @Test
    public void test3() throws NoSuchAlgorithmException {
        long timestamp = System.currentTimeMillis();
        String areaCode = "331121";
        System.out.println(CryptUtils.MD5Encode(timestamp + areaCode));
    }

    @Test
    public void test4() {
        CloseableHttpResponse response = null;
        try {
            String api = "/media/download";
            GetClient getClient = getZwddExecutableClient().newGetClient(api);
            //设置参数
            getClient.addParameter("access_token", zwddClient.getAccessToken().getData());
            getClient.addParameter("media_id", "$hQHNKaUCo2pwZwMGDAEN2gBAK2Z2YUVMb0xYZnFJSGRuZ1h3OVZGd3hadDNrTXlYNWlQOXF0OERrZTc0b2M5UU0xeExsUVFkalBQNFVJakZ0aA");
            //调用API
            //String result = getClient.get();
            //System.err.println(result);
            response = getClient.getB();
            org.apache.http.HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            System.out.println(is);
            File voice = new File("C:\\Users\\PoffyZhang\\Desktop\\log1.jpg");
            OutputStream fos = new FileOutputStream(voice);
            int cache = 10 * 1024;
            byte[] buffer = new byte[cache];
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = is.read(buffer)) != -1) {
                fos.write(buffer, 0, ch);
                sb.append(buffer);
            }
            System.out.println(sb.toString());
            is.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (response != null) {
                try {
                    //特别提醒：需要调用response的close方法关闭网络连接！！！
                    response.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }

    @Test
    public void test5() {
        CloseableHttpResponse response = null;
        try {
            String api = "/media/download";
            GetClient getClient = getZwddExecutableClient().newGetClient(api);
            //设置参数
            getClient.addParameter("access_token", zwddClient.getAccessToken().getData());
            getClient.addParameter("media_id", "$hQHNxoECo2pwZwMGDAEN2gAsOEkvNENaMmZ5UUVncDduWERralJxRW5aem45ODN5UHpKRjErcUxFeUkvTT0");
            //调用API
            //String result = getClient.get();
            //System.err.println(result);
            response = getClient.getB();
            org.apache.http.HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            System.out.println(is);
            File voice = new File("C:\\Users\\PoffyZhang\\Desktop\\log1.jpg");
            OutputStream fos = new FileOutputStream(voice);
            int cache = 10 * 1024;
            byte[] buffer = new byte[cache];
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = is.read(buffer)) != -1) {
                fos.write(buffer, 0, ch);
                sb.append(buffer);
            }
            System.out.println(sb.toString());
            is.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (response != null) {
                try {
                    //特别提醒：需要调用response的close方法关闭网络连接！！！
                    response.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }

    private static ExecutableClient zwddExecutableClient;
    @Autowired
    private ZwddIntegrationProperties zwddProperties;

    public ExecutableClient getZwddExecutableClient() {
        if (Objects.isNull(zwddExecutableClient)) {
            synchronized (ZwddAuthClientProvider.class) {
                if (Objects.isNull(zwddExecutableClient)) {
                    zwddExecutableClient = ExecutableClient.getInstance();
                    //DomainName不同环境对应不同域名，示例为sass域名
                    zwddExecutableClient.setDomainName(zwddProperties.getDomain());
                    zwddExecutableClient.setProtocal("https");
                    //应用App Key
                    zwddExecutableClient.setAccessKey(zwddProperties.getAppKey());
                    //应用App Secret
                    zwddExecutableClient.setSecretKey(zwddProperties.getAppSecret());
                    zwddExecutableClient.init();
                }
            }
        }
        return zwddExecutableClient;
    }

}
