package com.kmall.manager.manager.wechat.wxtemplate;

import com.kmall.manager.manager.pay.wxpay.WxPayPropertiesBuilder;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.common.utils.StringUtils;
import com.kmall.common.utils.wechat.AccessToken;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author huangyq
 * @date 2019/11/27.
 */
public class WxTemplateUtil {
    private static Logger loggger = LoggerFactory.getLogger(WxTemplateUtil.class);

    /**
     * 获取access_token
     *
     * @param appid     凭证
     * @param appsecret 密钥
     * @return
     */
    public static AccessToken getAccessToken(String appid, String appsecret) {
        AccessToken accessToken = null;
        String requestUrl = WxPayPropertiesBuilder.instance().getAccessTokenUrl().replace("APPID", appid).replace("APPSECRET", appsecret);
//        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET".
//                replace("APPID", appid).replace("APPSECRET", appsecret);

        String tokenObject = WechatUtil.requestOnceGet(requestUrl, new HashMap());
        // 如果请求成功
        if (StringUtils.isNotEmpty(tokenObject)) {
            JSONObject jsonObject = JSONObject.fromObject(tokenObject);
            try {
                accessToken = new AccessToken();
                accessToken.setToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                loggger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

    /**
     * 发送模板消息前获取token
     *
     * @param t 模板库中模板
     */
    public static JSONObject sendMessage(WxTemplate t) {
        AccessToken token = null;
        if (TokenThread.accessToken == null || TokenThread.accessToken.getToken().equals("")) {
            token = getAccessToken(WxPayPropertiesBuilder.instance().getAppId(),
                    WxPayPropertiesBuilder.instance().getSecret());
        } else {
            token = TokenThread.accessToken;
        }
        JSONObject result = sendMessage(t, token.getToken(), WxPayPropertiesBuilder.instance().getTemplateSendUrl());

        return result;
    }

    /**
     * 发送模板消息
     *
     * @param t
     * @param accessToken
     * @return
     */
    public static JSONObject sendMessage(WxTemplate t, String accessToken,String tempSendUrl) {
        int result = 0;
        // 拼装创建菜单的url
        String url = tempSendUrl.replace("ACCESS_TOKEN", accessToken);
        // 将菜单对象转换成json字符串
        String jsonMenu = t.toJSON();
        loggger.info(jsonMenu);
        // 调用接口创建菜单
        String sendObject = WechatUtil.requestOnce(url, jsonMenu);
        JSONObject jsonObject = null;
        if (null != sendObject) {
            jsonObject = JSONObject.fromObject(sendObject);
            if (0 != jsonObject.getInt("errcode")) {
                loggger.error("发送模板消息失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return jsonObject;
    }

    public static void main(String[] args) {
        BasicConfigurator.configure();
        WxTemplate tem = new WxTemplate();
        tem.setTouser("oKs9N5fQHMdJCIjAeJcHPFfqUdIE");
        tem.setTemplate_id("lFTyxlkg1pkRbJVMn-lDhdhsjK5pZqq_8ZTe9Qx_PUA");
        tem.setPage("/pages/ucenter/orderDetail/orderDetail?id=607");
//        tem.setTopcolor("#00DD00");
//        tem.setForm_id("5295a750131d45fa8ef812b97afb7307");

        List<TemplateData> paras = new ArrayList<TemplateData>();
        paras.add(new TemplateData("thing1", "草莓一盒（门店商品）"));
        paras.add(new TemplateData("date2", "2019-11-26"));
        paras.add(new TemplateData("thing3", "请在**之前完成支付"));
//        paras.add(new TemplateData("keyword3", "草莓一盒（门店商品），1个"));
//        paras.add(new TemplateData("keyword4", "0.01"));
//        paras.add(new TemplateData("keyword5", "EMATO17388076"));
//        paras.add(new TemplateData("keyword6", "请在**之前完成支付"));

        tem.setData(paras);
        tem.setEmphasis_keyword("EMATO17388076");

        (new Thread(new TokenThread())).start();
        AccessToken token = null;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET".
                replace("APPID", "wxb6b30b1b14ee502a").replace("APPSECRET", "be0234dbbbde4ce68df43dd2b5e4c7b1");

        String tokenObject = WechatUtil.requestOnceGet(requestUrl, new HashMap());
        // 如果请求成功
        if (StringUtils.isNotEmpty(tokenObject)) {
            JSONObject jsonObject = JSONObject.fromObject(tokenObject);
            try {
                token = new AccessToken();
                token.setToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                token = null;
                // 获取token失败
                loggger.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }

        JSONObject result = sendMessage(tem, token.getToken(), "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN");
        System.out.println(result);
//        sendMessage(tem);
    }
}
