package com.miaxis.test.feign;

import com.miaxis.HzgzptApplication;
import com.miaxis.common.sign.*;
import com.miaxis.feign.IQgptService;
import com.miaxis.test.Impl.TestServiceImpl;
import lombok.SneakyThrows;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Map;

@SpringBootTest(classes = HzgzptApplication.class)
@RunWith(SpringRunner.class)
public class FeignTest {

    public static String qgptHttpTopServerPath = "http://114.55.58.112:8085/top/";
    public static String qgptHttpServerPath = "http://115.29.171.186:8085/";
    public static final String file_stuimg = "stuimg";//学员头像
    /** 接口服务器:Imageup (文件资料信息上传) */
    public static final String httpServer_Imageup = "imageup";


    @Resource
    private TestServiceImpl testService;

    @Resource
    private IQgptService qgptService;
    @Test
    @SneakyThrows
    public void testHandleFileUpload() {

        File file = new File("upload.txt");
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                MediaType.TEXT_PLAIN_VALUE, true, file.getName());

        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        MultipartFile multi = new CommonsMultipartFile(fileItem);

//        log.info(uploadClient.handleFileUpload(multi));
    }


    @Test
    public void test2() throws Exception {
        File file =new File("F:/doc/img/gen-view.jpg");
        long timestamp = System.currentTimeMillis(); // 时间戳
        String sign_str = ""; // 签名
        /* 获取签名 */
        String path = getClass().getResource("/").getPath();
        java.io.File jarFile = new java.io.File(path);
        String propertiesfile = jarFile.getParentFile().getAbsolutePath().replace("%20", " ");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        InputStream input = new FileInputStream(propertiesfile + PlatUtil.privateKeyUrl);
        keyStore.load(input, PlatUtil.keyPassword.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new RuntimeException("HTTP接口协议签名获取失败: no alias found");
        }
        String alias = aliases.nextElement();
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, PlatUtil.keyPassword.toCharArray()); // 私钥
        ISign sign = new Sign();
        byte[] data = PlatUtil.getBytesFromFile(file);
        sign_str = sign.sign(data, timestamp, privateKey);
        /* 验证签名 */
        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        String serialNumber = cert.getSerialNumber().toString(); // 证书序列号
        long snInteger = Long.parseLong(serialNumber);
        serialNumber = Long.toHexString(snInteger).toUpperCase();
        MultipartFile multipartFile = fileToMultipartFile(file);
        Map resultMap = qgptService.imageup(PlatUtil.url_version, timestamp, serialNumber, sign_str,multipartFile);
        System.out.println(resultMap);



    }
    public static MultipartFile fileToMultipartFile(File file) {
        String fieldName = "file";  //重点  这个名字需要和你对接的MultipartFil的名称一样
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "multipart/form-data", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

    @Test
    public void test3() throws Exception {



    }






}
