package com.wechat.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.wechat.common.utils.MessageUtils;
import com.wechat.common.utils.MvcUtil;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.base.BaseController;
import com.wechat.model.dto.JsapiSignatureDto;
import com.wechat.model.responseDto.JsonResp;
import com.wechat.service.WeiXinService;

@Controller
@RequestMapping("jsSdk")
public class JsSdkController extends BaseController {

    //微信服务
    @Autowired
    private WeiXinService               weiXinService;
    
    // 签名字符串
    @Value("#{configProperties['weixin.jsapi.signature']}")
    private String wxJspSignatureStr;

    // Appid
    @Value("#{configProperties['weixin.appid']}")
    private String wxAppid;
    

    /**
     * jssdk 签名
     * 
     * @param openId
     * @throws NoSuchAlgorithmException 
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping(value = "signature", method = RequestMethod.GET)
    public void getSignature(@RequestParam String url, HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //获取16位随机字符串
        String randomStr = StringsUtils.getRandomString(16);
        //时间戳
        String timestamp = Long.toString(System.currentTimeMillis()/1000);
        
        String urlForSign = java.net.URLDecoder.decode(url, "utf-8");
        
        //签名用字符串
        String signatureStr = MessageUtils.getText(wxJspSignatureStr, weiXinService.getJsapiTicket(), randomStr, timestamp, urlForSign);
        log.info("签名用字符：" + signatureStr);
        
        //签名
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(signatureStr.getBytes("UTF-8"));
        String signature = byteToHex(crypt.digest());
        
        JsapiSignatureDto jsapiSignatureDto = new JsapiSignatureDto();
        jsapiSignatureDto.setAppId(wxAppid);
        jsapiSignatureDto.setNonceStr(randomStr);
        jsapiSignatureDto.setTimestamp(timestamp);
        jsapiSignatureDto.setSignature(signature);
        
        JsonResp<JsapiSignatureDto> resp = new JsonResp<JsapiSignatureDto>();
        resp.setInfo(jsapiSignatureDto);
        
        String json = JSON.toJSONString(resp, true);
        try {
            MvcUtil.writeJson(request, response, json);
        } catch (IOException e) {
           log.error(e);
        } 
    }
    
    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;
    }

}
