package com.happy.common.wx;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.happy.Model.weixin.WeiXinUtil;
import com.happy.Until.DateUtil;
import com.happy.Until.Func;
import com.happy.common.http.HttpsClient;

import java.text.ParseException;
import java.util.*;

/**
 * @Date
 * @Author xieli
 **/
public class WxServerInterface {


    /**
     * 获取access_token
     * @return
     */
    public static String getAccessToken()
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("grant_type", "client_credential");
        jsonObject.put("appid", WeiXinUtil.appid_c);
        jsonObject.put("secret",WeiXinUtil.screct_c);
        String msg3 = HttpsClient.sendJson2("https://api.weixin.qq.com/cgi-bin/stable_token",jsonObject);
        System.out.println(msg3);
        Map map = (Map) JSONUtils.parse(msg3);
        return Func.parseStr(map.get("access_token"));
    }


    /**
     * 昨天访问量
     * @param dayTime 20230815 yyyymmdd 传入时间为当日时间
     * @return 返回为昨日的访问量
     */
    public static WxDailyVisitInfo getDailyRetain(Date dayTime) {
        if (dayTime == null)
            throw new RuntimeException("未传入查询访问量时间");

        String token = getAccessToken();
        if (Func.checkNull(token))
            return null;

        String begin_date = DateUtil.getYesturday(dayTime,DateUtil.Time_Formatter_yyyyMMdd);
        JSONObject message = new JSONObject();
        message.put("access_token",token);
        message.put("begin_date",begin_date);
        message.put("end_date", begin_date);

        String result = HttpsClient.sendJson("https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token="+token, message);
        System.out.println(result);
        Map map = (Map) JSONUtils.parse(result);
        List arrayList = (ArrayList) map.get("list");
        if (arrayList == null || arrayList.size() <= 0)
            return null;

        Map mapInfo = (Map) arrayList.get(0);
        WxDailyVisitInfo info = (WxDailyVisitInfo) Func.convertToObject(WxDailyVisitInfo.class,mapInfo);
        return info;
    }

    public static void main(String[] args) {

        WxDailyVisitInfo info = getDailyRetain(new Date());
        System.out.println(info);
    }


}
