package cn.hmsoft.weixin.entity.request;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import cn.hmsoft.helper.RandomHelper;
import cn.hmsoft.weixin.data.model.WxDefine;
import cn.hmsoft.weixin.util.WeiXinUtil;

public class JsApiRequestJson {
	private boolean debug = false;
	private String appId;
	private Long timestamp;
	private String nonceStr;
	private String signature;

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public Long getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(Long timestamp) {
		this.timestamp = timestamp;
	}

	public String getNonceStr() {
		return nonceStr;
	}

	public void setNonceStr(String nonceStr) {
		this.nonceStr = nonceStr;
	}

	public String getSignature() {
		return signature;
	}

	public void setSignature(String signature) {
		this.signature = signature;
	}

	public JsApiRequestJson(String app_id,String url) {
		init(WeiXinUtil.getWxDefine(app_id), url);
	}
	public JsApiRequestJson(int wx_id,String url) {
		init(WeiXinUtil.getWxDefine(wx_id), url);

	}
	
	private void init(WxDefine wx,String url ){
		this.appId = wx.getApp_id();
		this.nonceStr = RandomHelper.getRandomValue(16);
		this.timestamp = new Date().getTime() / 1000;
		String jsapi_ticket = wx.getApp_jsapi();
		// this.nonceStr = "Wm3WZYTPz0wzccnW";
		// String jsapi_ticket =
		// "sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg";
		// this.timestamp = 1414587457L;
		// url = "http://mp.weixin.qq.com";
		//
		Map<String, String> map = new HashMap<String, String>();
		map.put("nonceStr", nonceStr);
		map.put("timestamp", timestamp + "");
		map.put("jsapi_ticket", jsapi_ticket);
		map.put("url", url);

		String[] array = new String[] { "nonceStr", "timestamp", "jsapi_ticket", "url" };
		// 对参数进行排序
		java.util.Arrays.sort(array);
		String total = "";
		for (String string : array) {
			total = total + string.toLowerCase() + "=" + map.get(string) + "&";
		}
		total = total.substring(0, total.length() - 1);
		// SHA-1加密实例
		MessageDigest sha1 = null;
		try {
			sha1 = MessageDigest.getInstance("SHA-1");
		} catch (Exception e) {

		}
		sha1.update(total.getBytes());
		byte[] codedBytes = sha1.digest();
		// 将加密后的字节数组转换成字符串。
		String codedString = new BigInteger(1, codedBytes).toString(16);
		//String code = ByteHelper.bytes2HexString(codedBytes);
		this.signature = codedString;
	}
}
