package com.cnd3b.utility.wechatdock;

import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.BaseClass;
import com.cnd3b.utility.WebRequest;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Calendar;

public class WechatDock_gzh extends BaseClass {
    public static String appid = "wx45f99fca9b087ae6";
    public static String secret = "cc42ba15deaa82f07f387bd64d421be2";


    //有效期2小时，需定时刷新，重复获取将导致上次获取的失效
    private static String access_token = "";
    private static long access_token_timelimit = 0L;

    private static String getAccessToken() {
        long nowtime = Calendar.getInstance().getTimeInMillis();
        if (access_token_timelimit < nowtime) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            String res = new WebRequest().doGet(url);

            JSONObject resobject = JSONObject.parseObject(res);
            if (resobject.containsKey("access_token")) {
                access_token = resobject.getString("access_token");
                access_token_timelimit = nowtime + 1000 * resobject.getIntValue("expires_in");
            }
        }
        return access_token;
    }

    //有效期2小时，需定时刷新，重复获取将导致上次获取的失效
    private static String ticket = "";
    private static long ticket_timelimit = 0L;

    private static String getTicket() {
        long nowtime = Calendar.getInstance().getTimeInMillis();
        if (ticket_timelimit < nowtime) {
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getAccessToken() + "&type=jsapi";
            String res = new WebRequest().doGet(url);

            JSONObject resobject = JSONObject.parseObject(res);
            if (resobject.containsKey("errcode") && "0".equals(resobject.getString("errcode"))) {
                ticket = resobject.getString("ticket");
                ticket_timelimit = nowtime + 1000 * resobject.getIntValue("expires_in");
            }
        }
        return ticket;
    }

    private static String wxcardticket = "";
    private static long wxcardticket_timelimit = 0L;

    public static String getWxCardTicket() {
        long nowtime = Calendar.getInstance().getTimeInMillis();
        if (wxcardticket_timelimit < nowtime) {
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getAccessToken() + "&type=wx_card";
            String res = new WebRequest().doGet(url);

            JSONObject resobject = JSONObject.parseObject(res);
            if (resobject.containsKey("errcode") && "0".equals(resobject.getString("errcode"))) {
                wxcardticket = resobject.getString("ticket");
                wxcardticket_timelimit = nowtime + 1000 * resobject.getIntValue("expires_in");
            }
        }
        return wxcardticket;
    }

    public static JSONObject wechatDock(String url) {
        String nonceStr = Calendar.getInstance().getTimeInMillis() + "";
        String jsapi_ticket = getTicket();
        String timestamp = Calendar.getInstance().getTimeInMillis() + "";

        String a = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        String signature = DigestUtils.shaHex(a);

        JSONObject resultobject = new JSONObject();
        resultobject.put("appId", appid);
        resultobject.put("timestamp", timestamp);
        resultobject.put("nonceStr", nonceStr);
        resultobject.put("signature", signature);

        return resultobject;
    }

    public JSONObject getWebClientAccessToken(String wechat_code) {
        WebRequest request = new WebRequest();
        String result = request.doGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + wechat_code + "&grant_type=authorization_code");
        return JSONObject.parseObject(result);
    }

    public WechatUser getCustMsg(String wechat_code) {
        JSONObject tokenobject = getWebClientAccessToken(wechat_code);
        WechatUser user = new WechatUser();
        if (tokenobject.containsKey("access_token")) {
            String access_token = tokenobject.getString("access_token");
            String openid = tokenobject.getString("openid");

            WebRequest request = new WebRequest();
            String result = request.doGet(" https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN");
            JSONObject custobject = JSONObject.parseObject(result);

            user.setOpenid(custobject.getString("openid"));
            user.setNickname(custobject.getString("nickname"));
            user.setSex(custobject.getIntValue("sex"));
            user.setProvince(custobject.getString("province"));
            user.setCity(custobject.getString("city"));
            user.setCountry(custobject.getString("country"));
            user.setHeadimgurl(custobject.getString("headimgurl"));
        } else {
            printErrOut("微信用户信息获取失败wechat_code:" + wechat_code, tokenobject.toString());
        }
        return user;
    }

    /**
     * vip卡券投放
     */
    public String sendVipCard(String wechat_openid) {
        JSONObject cardobject = new JSONObject();
        cardobject.put("action_name", "QR_CARD");
        //cardobject.put("expire_seconds", "1800");

        JSONObject infoobject = new JSONObject();
        JSONObject card = new JSONObject();
        card.put("card_id", "p8wWm6JSyu_jZjNwZw6smBGPhWX8");
        //card.put("code", "198374613512");
        card.put("openid", wechat_openid);
        card.put("is_unique_code", false);
        //card.put("outer_str", "12b");
        infoobject.put("card", card);
        cardobject.put("action_info", infoobject);

        WebRequest request = new WebRequest();
        String result = request.doPost("", "https://api.weixin.qq.com/card/qrcode/create?access_token=" + getAccessToken());
        JSONObject custobject = JSONObject.parseObject(result);

        return custobject.toString();
    }
}
