package com.tjk.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tjk.comm.ReadPro;
import com.tjk.comm.Sign;
import com.tjk.entity.WxShare;
@Controller
public class WeChatController extends JsonBaseController{
	@Resource
	ReadPro read;
	//静态资源缓存微信签名信息
    private static HashMap<String, WxShare> map=new HashMap<String, WxShare>();
    
    //请求获取微信分享签名
  	@RequestMapping("/api/product/wx.do")
  	public void getWxShare(HttpServletRequest request,HttpServletResponse response,String url){
  		
  		JsonEntity json = this.getJsonInstance();
  		String appId=read.readProperties("appId");
  		String appSecrect=read.readProperties("appSecrect");
  		String address="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+
  				"&secret="+appSecrect;
  		//判断是否有url的签名
  		WxShare wx=map.get(url);
  		if(wx==null){
  			
  			HashMap<String, WxShare> share=transfer(address, url);
  			
  			json.setData(share);
  		}else{
  			long time=wx.getTimeStamp();
  			if((System.currentTimeMillis()/1000-time)>5400){
  				
  				HashMap<String, WxShare> share = transfer(address, url);
  				json.setData(share);
  			}else{
  				HashMap<String, WxShare> share=new HashMap<String, WxShare>();
  				share.put("url", map.get(url));
  				json.setData(share);
  			}
  		}
  		json.flush(response);
  	}
  	
  	//验证成开发者
  	@RequestMapping("api/wx/token_check.do")
  	public void ddd(HttpServletRequest request, HttpServletResponse response){
  	    // 自定义 token
  	    String TOKEN = read.readProperties("token");
  	   // 微信加密签名
        String signature = request.getParameter("signature");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        //将token、timestamp、nonce三个参数进行字典序排序
        //将三个参数字符串拼接成一个字符串进行sha1加密
        String[] str = { TOKEN, timestamp, nonce };
        // 字典序排序
        Arrays.sort(str);
        String bigStr = str[0] + str[1] + str[2];
        // SHA1加密
        String digest = "";
        try {
			MessageDigest crypt=MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(bigStr.getBytes("UTF-8"));
			digest=Sign.byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
        // 确认请求来至微信
        if (digest.equals(signature)) {
        	System.out.println("验证成功");
        	System.out.println(echostr);
            try {
				response.getWriter().print(echostr);
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
  	     
  	}
	
  	public HashMap<String, WxShare> transfer(String address,String url){
  		    //获取access_token
  		    Map<String,String> m=Sign.sendGet(address);
			String token= m.get("access_token");
			address="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi";
			//获取jsapi_ticket
			m =Sign.sendGet(address);
			String tiket= m.get("ticket");
			//获取签名等信息
			m=Sign.getSignature(tiket, url);
			WxShare wxs=new WxShare(Long.parseLong(m.get("timestamp")), m.get("nonceStr"), m.get("signature"));
			map.put(url, wxs);
			HashMap<String, WxShare> share=new HashMap<String, WxShare>();
			share.put("url", wxs);
			return share;
  	}
}
