package com.sys.controller;

import com.sys.model.WechatToken;
import com.sys.service.WechatService;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by user on 2016/6/17.
 */
@Controller
@RequestMapping("wechat")
public class WechatController {

    @RequestMapping(value="/getjssdktoken")
    @ResponseBody//结果不会被解析为跳转路径，而是直接写入HTTP response body中
    protected void getjssdktoken(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="url")String url) throws UnsupportedEncodingException {
        Map<String, Object> resultMap = new HashMap<String,Object>();
        WechatToken token = (WechatToken) WechatService.getInstance().getWechatToken();
        String datelinenew = System.currentTimeMillis() + "";
        String timestampnew = datelinenew.substring(0, 10);
        if( token==null || Integer.parseInt(timestampnew)-Integer.parseInt(token.getTimestamp())>=7200){
            String accessToken = WechatService.getInstance().getAccessToken();
            String jsapi_ticket = WechatService.getInstance().getJSToken(accessToken);
            String dateline = System.currentTimeMillis() + "";
            String timestamp = dateline.substring(0, 10);
            String nocestr = WechatService.getInstance().getRandomString(16);
            token = new WechatToken(WechatService.APPID,accessToken,jsapi_ticket, timestamp, nocestr);
            WechatService.getInstance().setWechatToken(token);
        }
        url = url.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
        String urlStr = URLDecoder.decode(url, "UTF-8");
        System.out.println(urlStr);
        String data = "jsapi_ticket="+token.getJsapi_ticket()+"&noncestr="+token.getNocestr()+"&timestamp="+token.getTimestamp()+"&url="+urlStr;
        String signature = DigestUtils.sha1Hex(data);
        token.setSignature(signature);
        token.setUrl(url);
        resultMap.put("token", token);
        response.setCharacterEncoding("UTF-8");
        try {
            response.getWriter().write(JSONObject.fromObject(resultMap).toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
