package com.ycwl.basic.notify.adapters;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ycwl.basic.notify.entity.NotifyContent;
import com.ycwl.basic.notify.entity.WxMpSrvConfig;

import java.util.Date;
import java.util.Map;

public class WxMpSrvNotifyAdapter implements INotifyAdapter{
    private WxMpSrvConfig config;

    @Override
    public void loadConfig(Map<String, String> _config) {
        WxMpSrvConfig config = new WxMpSrvConfig();
        config.setAppId(_config.get("appId"));
        config.setAppSecret(_config.get("appSecret"));
        if (_config.containsKey("state")) {
            config.setState(_config.get("state"));
        }
        config.checkEverythingOK();
        this.config = config;
    }

    @Override
    public void sendTo(NotifyContent notifyContent, String openId) {
        Map<String, Object> params = notifyContent.getParams();
        params.put("touser", openId);
        params.put("miniprogram_state", config.getState());
        sendServiceNotification(params);
    }

    private static final String SEND_TEMPLATE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private String ACCESS_TOKEN = "";
    private Date expireTime = new Date();

    private String getAccessToken() {
        if (ACCESS_TOKEN != null && !ACCESS_TOKEN.isEmpty()) {
            if (expireTime.getTime() > System.currentTimeMillis()) {
                return ACCESS_TOKEN;
            }
        }
        String url = String.format(ACCESS_TOKEN_URL, config.getAppId(), config.getAppSecret());
        String response = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(response);
        ACCESS_TOKEN = jsonObject.getString("access_token");
        expireTime = new Date(System.currentTimeMillis() + jsonObject.getInteger("expires_in") * 1000);
        return ACCESS_TOKEN;
    }

    public void sendServiceNotification(Map<String, Object> params) {
        String url = String.format(SEND_TEMPLATE_MESSAGE_URL, getAccessToken());
        String response = HttpUtil.post(url, JSONObject.toJSONString(params));
        System.out.println(response);
    }
}
