package com.izouma.awesomeadmin.util;

import org.json.JSONObject;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * 
 * <p>微信接入校验。</p> 
 * 
 * @version 1.0
 * @author 姓名 <br />
 * 更新履历 <br />
 *  日期 : 姓名: 更新内容<br />
 */
public class CheckUtil {

    /**
     * 微信接入校验token
     */
    private static final String token = "suochencheng";


    /**
     * 
     * <p>校验签名是否正确。</p>
     *
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {

        String[] arr = new String[] {token, timestamp, nonce};
        //排序
        Arrays.sort(arr);

        //生成字符串
        StringBuffer content = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        //sha1加密
        String temp = getSha1(content.toString());

        return temp.equals(signature);
    }


    /**
     * Sha1加密方法
     * @param str
     * @return
     */
    public static String getSha1(String str) {

        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检测项目是否存活
     *
     * @return
     */
    public static boolean checkProjectActive() {


        try {
            String result = NetUtils.postUrlResponse("http://www.izouma.com/passport/checkActive?projectTicket=20181227handheld");

            if (result != null) {
                JSONObject json = new JSONObject(result);

                if ("1".equals(json.getString("error"))) {
                    return true;
                }
            }

        } catch (Exception e) {
            return true;
        }
        return false;

    }


}
