package com.zhiwei.weixin.accesstoken;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.UUID;

import com.zhiwei.conf.Conf;
import com.zhiwei.weixin.pojo.AccessToken;
import com.zhiwei.weixin.pojo.TicketToken;
import com.zhiwei.weixin.util.WeixinUtil;

public class CreateTicketToken {
	 

	 // 调用接口获取access_token  
	 
	 private static String token;
	    
	 private static TicketToken ticketToken ;
	 public CreateTicketToken()
	 {
		 token = new CreatAccessToken().getAccessToken();
		if(null == ticketToken)
		{
			ticketToken = WeixinUtil.getJSTicket(token);
		}else
		{
			long b =System.currentTimeMillis() - ticketToken.getExpiresIn();
			if((b/1000)>=3600)
			{
				ticketToken = WeixinUtil.getJSTicket(token);
			}
		}
	 }
	 
	@SuppressWarnings("rawtypes")
	public static HashMap sign(String url) {
    	if(ticketToken.getExpiresIn()<=60)
    	{
    		ticketToken = WeixinUtil.getJSTicket(token);
    	}
    	HashMap ret = new HashMap();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String jsapi_ticket = ticketToken.getJsticket();
        
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
       
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        
        ret.put("appId", Conf.appId);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
