package com.template.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/getWxArticle")
public class Wx {
    private static final String APP_ID = "wxa46ef222053a1047"; // 换成自己的公众号的AppID
    private static final String APP_SECRET = "16f74a1265c314fd79fdf90670173467"; // 换成自己的公众号的AppSecret
    private static final String API_URL = "https://api.weixin.qq.com/cgi-bin/";
    private static final String ACCESS_TOKEN_URL = API_URL + "token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET; // 获取access_token
    private static final String ARTICLELiST_URL = API_URL + "freepublish/batchget?access_token="; //获取成功发布文章的列表

    /**
     * 获取微信公众号发布的文章，用于互联网+作展示
     */
    @GetMapping("/get")
    public R<JSONArray> getArticleList() {
        // 获取ACCESS_TOKEN
        String accessToken = getAccessToken();

        // 获取文章列表信息
        JSONArray articles = getArticles(accessToken);
        JSONArray articleList = new JSONArray();

        articles.forEach(item -> {
            JSONObject wz = new JSONObject();
            JSONObject article = (JSONObject) item;
            JSONObject content = article.getJSONObject("content");
            JSONObject newsItem = content.getJSONArray("news_item").getJSONObject(0);
            wz.put("title", newsItem.getStr("title"));
            wz.put("url", newsItem.getStr("url"));
            wz.put("createTime", content.getStr("create_time"));
            articleList.add(wz);
        });
        return R.ok(articleList);
    }

    private static String getAccessToken() {
        String response = HttpUtil.get(ACCESS_TOKEN_URL);
        JSONObject json = new JSONObject(response);
        return json.getStr("access_token");
    }

    private static JSONArray getArticles(String accessToken) {
        JSONObject params = new JSONObject();
        params.put("offset", 0);
        params.put("count", 20);
        String response = HttpUtil.post(ARTICLELiST_URL + accessToken, params.toString());
        JSONObject json = new JSONObject(response);

        return json.getJSONArray("item");
    }

}
