package com.miaxis.test.Impl;

import com.miaxis.test.inf.ITestService;
import com.miaxis.common.sign.*;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.springframework.stereotype.Service;

import java.io.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

@Service
public class TestServiceImpl implements ITestService {

    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";

    public String imageUpForQG(File file, String serviceName, String type, String filePath) throws Exception {
        ProvResultJson result = new ProvResultJson("操作失败", "1");
        System.out.println("上传照片到全国平台");
        HttpClient client = new HttpClient();
        StringBuffer sb = null;
        FilePart fp = new FilePart("file", file);
        result = this.getHttpServerUrlForFileUpload(this.qgptHttpTopServerPath, serviceName + "/" + type, PlatUtil.getBytesFromFile(file), filePath);
        if (result != null && result.getResult().equals("0")) {
            String sendUrl = result.getObject().toString();
            System.out.println(sendUrl);
            Part[] parts = { fp };
            PostMethod pomethod = new PostMethod(sendUrl);
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, pomethod.getParams());
            pomethod.setRequestEntity(mre);
            client.executeMethod(pomethod);
            sb = new StringBuffer();
            if (pomethod.getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(pomethod.getResponseBodyAsStream(), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                reader.close();
            }
            System.out.println(sb.toString());
//            JSONObject jsonObject = JSONObject.fromObject(sb.toString());
//            String errorcode = jsonObject.containsKey("errorcode") ? jsonObject.getString("errorcode") : "1";
//            if(errorcode.equals("0")){
//                String dataJson = jsonObject.get("data").toString();
//                JSONObject fileIdJosn = JSONObject.fromObject(dataJson);
//                return  fileIdJosn.getString("id"); // 培训学员全国统一编号
//            }
        }else {
            return "";
        }

        return "";
    }



    /**
     * 调用HTTP接口,Delete请求(静态参数在ptUtil里面定义静态变量统一使用)
     * 为文件上传加密数据和验证签名，返回加密后的URL
     * */
    public  ProvResultJson getHttpServerUrlForFileUpload(String urlPort, String serviceName, byte[] data, String imgPath) throws Exception {
        ProvResultJson result = new ProvResultJson("操作失败", "1");

        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()) {
            System.out.println("-99");
            System.out.println("HTTP接口协议签名获取失败: no alias found");
            return result;
        }
        String alias = aliases.nextElement();
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, PlatUtil.keyPassword.toCharArray()); // 私钥
        ISign sign = new Sign();
        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();
        IVerify verify = new Verify();
        boolean ok = verify.verify(data, timestamp, sign_str, cert);
        //String serialNumber = ""; //证书序列号
        //boolean ok = true;
        if (ok) {
            String url = urlPort + serviceName + "?v=" + PlatUtil.url_version + "&ts=" + timestamp + "&user=" + serialNumber + "&sign=" + sign_str;
            if(VerifyUtil.verifyString(imgPath)) {
                url += "&imgPath=" + imgPath;
            }
            result.setObject(url);
            result.setResult("0");
            result.setMsg("操作成功");
        } else {
            System.out.println("-99");
            System.out.println("HTTP接口协议签名获取失败");
        }
//        result.setXlog(xlog);
        return result;
    }

}
