package com.izouma.awesomeadmin.service;


import com.izouma.awesomeadmin.dao.AccessTokenMapper;
import com.izouma.awesomeadmin.model.AccessToken;
import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import com.izouma.awesomeadmin.util.WeixinUtil;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeiXinService {

    @Autowired
    private AccessTokenMapper accessTokenMapper;


    public String getAccessToken() {

        String access_token = "";
        //查询是否有accessToken
        final AccessToken at = accessTokenMapper.getAccessToken();

        if (at == null) {
            access_token = newAccessToken();
        } else {
            //获取token
            access_token = at.getAccessToken();

            //判断是否过期
            if (access_token == null || Integer.parseInt(WeixinUtil.create_timestamp()) - Integer.parseInt(at.getTimeStamp()) > 7000) {

                access_token = newAccessToken();

            }

        }

        return access_token;

    }


    /**
     * 
     * <p>获取新的accessToken。</p>
     *
     * @return
     */
    private String newAccessToken() {

        String access_token;
        String app_id = PropertiesFileLoader.getProperties("weixinappid");
        String app_ket = PropertiesFileLoader.getProperties("weixinsecret");
        //重新获取token
        String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + app_id + "&secret=" + app_ket;
        JSONObject accessData = WeixinUtil.loadJSON(accessUrl);
        access_token = (String) accessData.get("access_token");

        Map <String, Object> parameter = new HashMap <String, Object>();
        parameter.put("accessToken", access_token);
        parameter.put("timeStamp", WeixinUtil.create_timestamp());
        accessTokenMapper.updateAccessToken(parameter);
        return access_token;
    }


    public Map <String, String> getSignature(String shareUrl) {

        String access_token = getAccessToken();

        String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        JSONObject ticketData = WeixinUtil.loadJSON(ticketUrl);
        String jsapi_ticket = (String) ticketData.get("ticket");

        // 注意 URL 一定要动态获取，不能 hardcode
        // String url = requesturl.getRequestURL().toString();
        //url = url.replaceAll("127.0.0.1:90", "webapp.weiqiuwang.com");
        Map <String, String> ret = WeixinUtil.sign(jsapi_ticket, shareUrl);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        ret.put("appId", PropertiesFileLoader.getProperties("weixinappid"));
        return ret;

    }

}
