package com.zhiwei.weixin.jsticket;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhiwei.weixin.accesstoken.CreatAccessToken;
import com.zhiwei.weixin.pojo.TicketToken;
import com.zhiwei.weixin.util.WeixinUtil;

/** 
 * @Package com.zhiwei.weixin.jsticket
 * @ClassName: GetJSTicket
 * @Description: TODO(获取卡劵js_ticket)
 * @author 志伟
 * @date 2015-3-27 下午1:32:50
 */
public class GetJSTicket {
	
    //获取ticket
    private static TicketToken ticketoken;
    //卡劵id     //p_VmbjngNeUuEWe9-IZ0xVqXkpjw 赠送卡劵id
    private static String card_id = "p_Vmbjs0WI73ZfC7PuKFg8Y_8qvs";    //     p_Vmbjs0WI73ZfC7PuKFg8Y_8qvs//基础350卡劵id
	//记录日志
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
	//
	private String token ;
	
	public GetJSTicket() 
	{
		token = new CreatAccessToken().getAccessToken();
		if(ticketoken==null)
		{
			ticketoken = WeixinUtil.getTicket(token);
		}else
		{
			long c =System.currentTimeMillis()-ticketoken.getExpiresIn();
//			System.out.println("time c is=========="+c);
			if((c/1000)>=3600)
			{
				ticketoken = WeixinUtil.getTicket(token);
			}
		}
	}
	
	
	
	/**获取js_ticket**/
	
	public List getApiTicket(String openid)
	{
		List  list = new ArrayList();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String api_ticket = ticketoken.getJsticket();
        
        //注意这里参数名必须全部小写，且必须有序
        string1 = timestamp+ api_ticket+openid +card_id ;
        
        
        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();
        }
        
        list.add(card_id);
        list.add(timestamp);
        list.add(signature);
        list.add(openid);     
        System.out.println("list:"+list);
        return list;
	}
	
	
		/**计算签名**/
	  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);
	    }
}
