package com.kmall.manager.manager.pingan.utils;

//~--- non-JDK imports --------------------------------------------------------

import com.kmall.manager.manager.pingan.properties.PinganPayPropertiesBuilder;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

//~--- JDK imports ------------------------------------------------------------

//~--- classes ----------------------------------------------------------------

/**
 * Class TLinx2Util
 * Description tlinx api 工具类
 * Create 2017-03-07 14:01:23
 * @author Benny.YEE
 */
public class TLinxPluginUtil {

    /**
     * 签名
     * @param postMap
     * @param privatekey 说明：
     * @return
     */
    public static String sign(Map<String, String> postMap, String privatekey) {
        String sortStr = null;
        String sign    = null;

        try {

            /**
             * 1 A~z排序
             */
            sortStr = sort(postMap);
      //     System.out.println("=======排序后的明文：" + sortStr);

            /**
             * 2 sha1加密(小写)
             */
            String sha1 = TLinxSHA1.SHA1(sortStr);

     //       System.out.println("=======sha1：" + sha1);

            /**
             * 3 RSA加密(小写),二进制转十六进制
             */
            sign = TLinxRSACoder.sign(sha1.getBytes("utf-8"), privatekey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sign;
    }

    /**
     * 进件验签
     * @param respObject
     * @param publickey 说明：
     * @return
     */
    public static Boolean verifySign(JSONObject respObject, String publickey) {
        boolean verify = false;
        try {
            String respSign = respObject.getString("sign");

            respObject.remove("sign");                // 删除sign节点

            String rspparm = sortjson(respObject);    
            String sha1    = TLinxSHA1.SHA1(rspparm);           // sha1加密

            verify = TLinxRSACoder.verify(sha1.getBytes(), publickey, respSign);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return verify;
    }

    /**
     * AES加密，再二进制转十六进制(bin2hex)
     * @param datamap 说明：
     *
     * @return 返回值说明：
     * @throws Exception
     */
    public static String handleEncrypt(JSONObject datamap) throws Exception {
    	System.out.println("aes加密data数据:"+datamap.toString());
        return TLinxAESCoder.encrypt(datamap.toString(), PinganPayPropertiesBuilder.instance().getPayOpenKey());    // AES加密，并bin2hex
    }
    

    /**
     * 签名
     * @param getmap
     * @param datamap 说明：
     *
     * @return 返回值说明：
     */
    public static String handleSign(TreeMap<String, String> getmap, TreeMap<String, String> datamap) {
        Map<String, String> veriDataMap = new HashMap<String, String>();

        veriDataMap.putAll(getmap);
        veriDataMap.putAll(datamap);

        // 私钥签名
        return sign(veriDataMap, PinganPayPropertiesBuilder.instance().getPayPrivateKey());
    }
    
    /**
     * 签名(不上送datamap时用)
     * @param getmap
     *
     * @return 返回值说明：
     */
    public static String handleSign2(TreeMap<String, String> getmap) {
        Map<String, String> veriDataMap = new HashMap<String, String>();

        veriDataMap.putAll(getmap);
        // 签名
        return sign(veriDataMap, PinganPayPropertiesBuilder.instance().getPayPrivateKey());
    }

    /**
     * 根据返回格式来选择post请求处理方式
     * @param postmap
     * @param uri
     * @param tarType
     * @return
     */
    public static String handlePostbyTarType(TreeMap<String, String> postmap, String uri, String tarType) {
        if("gzip".equals(tarType)){
            return handlePostGZIP(postmap, uri);
        }else{
            return handlePost(postmap, uri);
        }
    }

    /**
     * 请求接口
     * @param postmap
     * @param uri 说明：
     * @return      响应字符串
     */
    public static String handlePost(TreeMap<String, String> postmap, String uri) {
        String url = PinganPayPropertiesBuilder.instance().getPayUrl() + uri;
        System.out.println("==url=="+url);
        if (url.contains("https")) {
            return HttpsUtil.httpMethodPost(url, postmap, "UTF-8");
        } else {
            return HttpUtil.httpMethodPost(url, postmap, "UTF-8");
        }
    }
    
    public static String handlePost2(TreeMap<String, String> postmap, String uri) {
        if (uri.contains("https")) {
            return HttpsUtil.httpMethodPost(uri, postmap, "UTF-8");
        } else {
            return HttpUtil.httpMethodPost(uri, postmap, "UTF-8");
        }
    }
       
    

    public static String handlePostGZIP(TreeMap<String, String> postmap, String uri) {
        String url = PinganPayPropertiesBuilder.instance().getPayUrl() + uri;
        if (url.contains("https")) {
            return HttpsUtil.httpMethodPostGZIP(url, postmap, "UTF-8");
        } else {
            return HttpUtil.httpMethodPostGZIP(url, postmap, "UTF-8");
        }
    }
 

    // 排序
    public static String sort(Map paramMap) throws Exception {
        String sort = "";
        TLinxMapUtil signMap = new TLinxMapUtil();
        if (paramMap != null) {
            String key;
            for (Iterator it = paramMap.keySet().iterator(); it.hasNext();) {
                key = (String) it.next();
                String value = ((paramMap.get(key) != null) && (!(""
                        .equals(paramMap.get(key).toString())))) ? paramMap
                        .get(key).toString() : "";
                signMap.put(key, value);
            }
            signMap.sort();
            for (Iterator it = signMap.keySet().iterator(); it.hasNext();) {
                key = (String) it.next();
                sort = sort + key + "=" + signMap.get(key).toString() + "&";
            }
            if ((sort != null) && (!("".equals(sort)))) {
                sort = sort.substring(0, sort.length() - 1);
            }
        }
        return sort;
    }


    // 排序
    public static String sortjson(JSONObject jsonMap) throws Exception {
        Map<String ,String > paramMap=new HashMap<String, String>();
        // 将json字符串转换成jsonObject
        JSONObject jsonObject = JSONObject.fromObject(jsonMap);
        Iterator ite = jsonObject.keys();
        // 遍历jsonObject数据,添加到Map对象
        while (ite.hasNext()) {
            String key = ite.next().toString();
            String value = jsonObject.get(key).toString();
            paramMap.put(key, value);
        }
        String sort = "";
        TLinxMapUtil signMap = new TLinxMapUtil();
        if (paramMap != null) {
            String key1;
            for (Iterator it = paramMap.keySet().iterator(); it.hasNext();) {
                key1 = (String) it.next();
                String value = ((paramMap.get(key1) != null) && (!(""
                        .equals(paramMap.get(key1).toString())))) ? paramMap
                        .get(key1).toString() : "";
                signMap.put(key1, value);
            }
            signMap.sort();
            for (Iterator it = signMap.keySet().iterator(); it.hasNext();) {
                key1 = (String) it.next();
                sort = sort + key1 + "=" + signMap.get(key1).toString() + "&";
            }
            if ((sort != null) && (!("".equals(sort)))) {
                sort = sort.substring(0, sort.length() - 1);
            }
        }
        return sort;
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
