package com.cftech.mp.qrcode.utils;

import net.sf.json.JSONObject;
import org.mp.api.core.common.WxstoreUtils;
import org.springframework.stereotype.Component;


/**
 * Created by Strive on 2017/4/25.
 */
@Component
public class WxQrcodeAPIUtils {

    /**
     * 临时二维码
     */
    public static String QR_SCENE = "QR_SCENE";

    /**
     * 永久二维码
     */
    public static String QR_LIMIT_SCENE = "QR_LIMIT_SCENE";

    /**
     * 永久二维码 字符串参数形式
     */
    public static String QR_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";

    /**
     * 短连接转长链接标识符
     */
    private static String LONG_URL = "long2short";


    private static String CREATE_QRCODE_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";

    private static String BY_TICKET_FIND_QRCODE = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";

    private static String FIND_QRCODE_SHORTURL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";

    /**
     * 创建微信带参二维码
     * @param token
     * @param expire_seconds 超时时间
     * @param action_name 二维码类型
     * @param scene 场景值ID
     * @return
     */
    public JSONObject createQrcodeTicket(String token, String scene, long expire_seconds) {
        JSONObject reqObj = new JSONObject();
        if (expire_seconds >0) {
            reqObj.put("expire_seconds", expire_seconds);
            reqObj.put("action_name", QR_SCENE);
        } else {
            reqObj.put("expire_seconds", expire_seconds);
            reqObj.put("action_name", QR_LIMIT_STR_SCENE);
        }
        reqObj.put("action_info",//
                new JSONObject().put("scene",//
                        new JSONObject().put(expire_seconds > 0 ? "scene_id" : "scene_str", scene)));

        String reqUrl = CREATE_QRCODE_TICKET_URL.replace("TOKEN", token);
        return WxstoreUtils.httpRequest(reqUrl, "POST", String.valueOf(reqObj));
    }

    /**
     * 返回二维码链接
     * @param ticket
     * @return
     */
    public String ByTicketFindQrcode(String ticket) {
        return BY_TICKET_FIND_QRCODE.replace("TICKET", ticket);
    }

    /**
     * 将长链接转短链接
     * @param token
     * @param longUrl
     * @return
     */
    public JSONObject findShortUrl(String token, String longUrl) {
        JSONObject reqObj = new JSONObject();
        reqObj.put("action", LONG_URL);
        reqObj.put("long_url", longUrl);

        String reqUrl = FIND_QRCODE_SHORTURL.replace("ACCESS_TOKEN", token);
        return WxstoreUtils.httpRequest(reqUrl, "POST", String.valueOf(reqObj));
    }

}
