import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpDownloader;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.common.constant.CoreConstants;
import com.dxhy.common.util.StringHelper;
import com.dxhy.core.job.pojo.Authorize;
import com.dxhy.core.job.pojo.BaseQueJson;
import com.dxhy.core.job.pojo.BaseResJson;
import com.dxhy.core.job.pojo.GlobalInfo;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName test2
 * @Description TODO
 * @Author wangruwei
 * @Date 2024/8/6 14:54
 * @Version 1.0
 */
@Slf4j
public class test2 {
    public static void main(String[] args) throws Exception {

        Double a = null;
        System.out.println(a.toString());

        /*String yzSignStr = "POST/cjhz/list{\"curr\": 1, \"size\": 20, \"gfsh\": \"99\", \"cjksrq\": \"2022-06-01\", \"cjjsrq\": \"2024-07-08\", \"ycpbz\": 1, \"company\": \"150001205110278555\", \"menuId\": \"800006\"}219_979cd01b6664494fb45ae530c93fa796";
        String newSignature = MD5.getEncode(yzSignStr.toString());
        System.out.println(newSignature);*/



        /*Map<String, String> map = new HashMap<>();
        map.put("batchNo", "20240508000000000000001000000002");
        map.put("taxno", "91429004MABY89K2XB");
        map.put("dataType","1");
        //map.put("electronicInvoiceNo","24422000000099164252");
        //map.put("electronicInvoiceNo","24422000000099164252");

        map.put("fileType", "pdf");

        requestYwjDown(map,"53556628FD7076B698E784BE8A836067","F9EBC0C954CE9202D82468B224430F16");*/
        //zhijieqing();

        //bendiTest();
        /*System.out.println(getFtpFileMap("/data/sftp/jxpt/王汝伟/excelFile/2024/08/14/11002370574_bbfpzhcxList_2024-08-14_1723618423258.xlsx"));
        System.out.println(FileUtil.getSuffix("/data/sftp/jxpt/王汝伟/excelFile/2024/08/14/11002370574_bbfpzhcxList_2024-08-14_1723618423258.xlsx"));
        System.out.println(FileUtil.getSuffix("11002370574_bbfpzhcxList_2024-08-14_1723618423258.xlsx"));*/

//        strToMap();
    }

    private static void zhijieqing() {
        String collectDataStr = "{\n" +
                "    \"authorize\": {\n" +
                "        \"appSec\": \"12AsuqkutOwxVowBJgcEkO0UjNQ=\",\n" +
                "        \"appSecId\": \"1C769BEAE7FAA4647C39C5C7F556654A\"\n" +
                "    },\n" +
                "    \"data\": \"eyJiYXRjaE5vIjoiYjg4NjE2MzU4NzJiNDFkOGI2NjMzMTkwNWIwNjdhOTYiLCJkYXRhVHlwZSI6IjEiLCJ0YXhubyI6IjkxMzIwMTE1NzI2MDk2MDgwWSIsImVsZWN0cm9uaWNJbnZvaWNlTm8iOiIyNDMxMjAwMDAwMDI1Mjg1MDAxNCIsImZpbGVUeXBlIjoicGRmIn0=\",\n" +
                "    \"globalInfo\": {\n" +
                "        \"appId\": \"JXFP\",\n" +
                "        \"dataExchangeId\": \"JXFPGLPT20240904172415384351088\",\n" +
                "        \"enterpriseCode\": \"JXFPGLPT\",\n" +
                "        \"interfaceCode\": \"SOURCE.FILE.DOWN\",\n" +
                "        \"version\": \"v1.0\"\n" +
                "    }\n" +
                "}";

        String url = "http://jxfpapi.ele-cloud.com";

        HttpResponse response = HttpUtil.createPost(url + "/rest/invoice/invoiceDownFile").timeout(600000).body(collectDataStr).executeAsync();

        log.info("返回参数:{}", response.body());
        FileUtil.writeBytes(response.bodyBytes(), "E:\\a\\b\\pdfliu.txt");
        // 根据发票类型保存不同实体

        BaseResJson gatherData = null;
        try {
            gatherData = JSONObject.parseObject(response.body(), BaseResJson.class);
            log.info("调文件下载返回:{}", JSON.toJSONString(gatherData.getReturnStateInfo()));
        } catch (Exception e) {
            log.info("调文件下载，返回内容不为json，以文件流保存");

            //response.writeBody(new File("E:\\a\\b\\aa1."+reqMap.get("fileType")), null);
            response.writeBody(new File("E:\\a\\b\\aa1."+"pdf"), null);
        }


    }

    private static void strToMap() {
        String a = "序号 xh\n" +
                "转内销证明编号 exportNo\n" +
                "缴款书号码 customsCode\n" +
                "填发日期 fillInDate\n" +
                "缴款单位名称 gfName\n" +
                "缴款单位税号 gfTaxNo\n" +
                "税款金额 exportTaxAmount\n" +
                "抵扣税额 yxExportTaxAmount\n" +
                "认证属期 rzhBelongDate\n" +
                "认证类型 bdkStatus\n" +
                "认证日期 rzhDate";

        LinkedHashMap<String,String> params = new LinkedHashMap();
        //获取行
        String[] rows = a.split("\n");
        for (int i = 0; i < rows.length; i++) {
            String rowStr = rows[i];
            String[] split = rowStr.split(" ");
            params.put(split[0],split[1]);
        }
        params.keySet().forEach(key -> {

            String value = params.get(key);
            //System.out.println(key+value);
            System.out.println("params.put(\""+key+"\", \""+value+"\");");

        });


    }

    private static Map<String, String> getFtpFileMap(String imagePath) {
        Map<String, String> ftpFileMap = new HashMap<>(2);
        StringBuilder filePath = new StringBuilder();
        // linux服务器
        if (!imagePath.contains(":")) {
            filePath.append("/");
        }
        String[] filePaths = imagePath.split("/");

        for (int i = 0; i < filePaths.length - 1; i++) {
            if (!StringHelper.isBlank(filePaths[i])) {
                filePath.append(filePaths[i]);
                filePath.append("/");
            }
        }
        ftpFileMap.put("filePath", filePath.toString());
        ftpFileMap.put("fileName", filePaths[filePaths.length - 1]);
        return ftpFileMap;
    }


    private static void bendiTest() {
        long l = HttpDownloader.downloadFile("http://10.1.2.87:8090/ftp/pic/000001/308958754069/2024/f3cbf0b6bfee47a9b8b854ca71bbfda6%E4%BA%91%E5%8D%97%E5%8C%BA%E5%9D%97%E9%93%BE3.pdf", new File("D://22.pdf"), 60000, null);
        //log.info("返回的L是{}",l);

        String url = "http://10.1.2.87:8090/ftp/pic/000001/308958754069/2024/f3cbf0b6bfee47a9b8b854ca71bbfda6%E4%BA%91%E5%8D%97%E5%8C%BA%E5%9D%97%E9%93%BE3.pdf";
        int timeout = 6000;
        HttpResponse response = HttpUtil.createGet(url).timeout(timeout).executeAsync();
        if (response.isOk()) {
            //写入文件
            response.writeBody(new File("D://123.pdf"), null);
        } else {
            throw new HttpException("Server response error with status code: [{}]", new Object[]{response.getStatus()});
        }

        //String responseJson = HttpUtil.get("http://10.1.2.87:8090/ftp/pic/000001/308958754069/2024/f3cbf0b6bfee47a9b8b854ca71bbfda6%E4%BA%91%E5%8D%97%E5%8C%BA%E5%9D%97%E9%93%BE3.pdf");
        //HttpUtil.downloadFile("http://10.1.2.87:8090/ftp/pic/000001/308958754069/2024/f3cbf0b6bfee47a9b8b854ca71bbfda6%E4%BA%91%E5%8D%97%E5%8C%BA%E5%9D%97%E9%93%BE3.pdf","D://22.pdf");
        //String responseJson = FileUtils.readFileToString(new File("D://a.pdf"));
        //System.out.println(responseJson);


        //byte[] responseJson = FileUtils.readFileToByteArray(new File("D://a.pdf"));
        //FileUtils.writeStringToFile(new File("D://123.pdf"), responseJson, "utf-8");
        //FileUtils.writeByteArrayToFile(new File("D://123.pdf"), responseJson1);

        System.out.println("写入完成");
    }

    /**
     * @Description 调下载源文件接口
     * @Return void
     * @Author wangruwei
     * @Date 2024/8/6 10:32
     **/
    private static void requestYwjDown(Map<String, String> reqMap, String aceId, String aceKey) {
        BaseQueJson bqj = new BaseQueJson();
        // 请求通用头
        GlobalInfo globalInfo = new GlobalInfo();
        // 请求通用
        Authorize authorize = new Authorize();
        // 封装参数
        globalInfo.setAppId("JXFP");
        globalInfo.setVersion("v1.0");
        String exchangeId = getDataExchangeId();
        globalInfo.setDataExchangeId(exchangeId);
        globalInfo.setInterfaceCode(CoreConstants.sourceFileGetNew);
        globalInfo.setEnterpriseCode("JXFPGLPT");
        authorize.setAppSecId(aceId);
        String base64Data = Base64.encode(JSONObject.toJSONString(reqMap));
        String appSec = makeAppSec(base64Data, exchangeId, CoreConstants.sourceFileGetNew, aceId, aceKey);
        authorize.setAppSec(appSec);
        bqj.setData(base64Data);
        bqj.setAuthorize(authorize);
        bqj.setGlobalInfo(globalInfo);
        String collectDataStr = JSONObject.toJSONString(bqj);
        String url = "http://jxfpapi.ele-cloud.com";
        //String url = "http://101.124.2.174:8100/";
        log.info("url:" + url+"/rest/invoice/invoiceDownFile");
        log.info("请求参数：" + collectDataStr);
        log.info("发送请求--");
        HttpResponse response = HttpUtil.createPost(url + "/rest/invoice/invoiceDownFile").timeout(600000).body(collectDataStr).executeAsync();

        log.info("返回参数:{}", response.body());
        // 根据发票类型保存不同实体

        BaseResJson gatherData = null;
        try {
            gatherData = JSONObject.parseObject(response.body(), BaseResJson.class);
            log.info("调文件下载返回:{}", JSON.toJSONString(gatherData.getReturnStateInfo()));
        } catch (Exception e) {
            log.info("调文件下载，返回内容不为json，以文件流保存");
            // 获取Content-Type头的值
            String contentType = response.header("Content-Type");
            log.info("contenttype是:{}",contentType);

            response.writeBody(new File("E:\\a\\b\\aa1."+reqMap.get("fileType")), null);
        }
    }


    /**
     * 获取时间戳
     *
     * @return String
     */
    public static String getDataExchangeId() {
        // enterpriseCode+8 位日期
        // (YYYYMMDD)+9 位序列号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 9; i++) {
            sb.append(rand.nextInt(10));
        }
        String data = sb.toString();
        return "JXFPGLPT" + simpleDateFormat.format(new Date()) + data;
    }

    /**
     * 加密方法
     */
    public static String makeAppSec(String data, String dataExchangeId, String interfaceCode, String aceId, String aceKey) {
        String srcStr =
                "POST/rest/invoice/invoiceDownFile?authorize={\"appSecId\":\"" + aceId + "\"}&globalInfo={\"appId\":\"" + "JXFP"
                //"POST/down/invoice/dii?authorize={\"appSecId\":\"" + aceId + "\"}&globalInfo={\"appId\":\"" + "JXFP"
                        + "\",\"version\":\"" + "v1.0" + "\",\"interfaceCode\":\"" + interfaceCode + "\",\"enterpriseCode\":\""
                        + "JXFPGLPT" + "\",\"dataExchangeId\":\"" + dataExchangeId + "\"}&" + "data=" + data + "";
        log.info("待加密的请求：" + srcStr);
        SecretKeySpec keySpec = null;
        keySpec = new SecretKeySpec(aceKey.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA1");
        } catch (NoSuchAlgorithmException e) {
            log.info("业务处理异常：{}", e);
        }
        try {
            mac.init(keySpec);
        } catch (InvalidKeyException e) {
            log.info("业务处理异常：{}", e);
        }
        byte[] singBytes = new byte[0];
        singBytes = mac.doFinal(srcStr.getBytes(StandardCharsets.UTF_8));
        String appSec = Base64.encode(singBytes);
        log.info("interfaceCode接口生成的加密串=appSec--");
        return appSec;
    }

}
