package com.template.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.config.ScheduleConfig;
import com.template.model.pojo.SmartNews;
import com.template.services.SmartNewsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
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;

import javax.annotation.Resource;
import java.util.Date;


@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/0api/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="; //获取成功发布文章的列表

    @Autowired
    SmartNewsService smartNewsService;

    @Resource
    private ScheduleConfig scheduleConfig;

    @Async
    @Scheduled(cron = "0 0 14 * * ? ")
    public void get() {
        if (scheduleConfig.getIsOpen().equals("1")) {
            getArticleList();
        }

    }

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

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

        int size = 20;

        JSONObject params = new JSONObject();
        params.put("offset", 0);
        params.put("count", size);
        String response = HttpUtil.post(ARTICLELiST_URL + accessToken, params.toString());
        JSONObject json = new JSONObject(response);

//          查看是否还有第二页
        Integer itemCount = json.getInt("item_count");
        Integer totalCount = json.getInt("total_count");
        int page = totalCount % size == 0 ? (totalCount / size) : (totalCount / size) + 1;
        for (int conut = 1; conut <= page; conut++) {
            if (1 == conut) {
                JSONArray items = json.getJSONArray("item");
                for (Object item : items) {
                    JSONObject article = (JSONObject) item;
                    JSONObject content = article.getJSONObject("content");
                    JSONArray newsItems = content.getJSONArray("news_item");
                    for (int i = 0; i < newsItems.size(); i++) {
                        JSONObject newsItem = newsItems.getJSONObject(i);
                        SmartNews nw = new SmartNews();
                        nw.setMediaId(article.getStr("article_id"));
                        nw.setTitle(newsItem.getStr("title"));
                        nw.setAuthor(newsItem.getStr("author"));
                        nw.setDigest(newsItem.getStr("digest"));
                        nw.setContent(newsItem.getStr("content"));
                        nw.setContentSourceUrl(newsItem.getStr("content_source_url"));
                        nw.setUrl(newsItem.getStr("url"));
                        String thumbUrl = newsItem.getStr("thumb_url");
                        nw.setFirstImg(thumbUrl);

                        Long updateTime = article.getLong("update_time");
                        updateTime = updateTime * 1000;
                        nw.setDateTime(new Date(updateTime));
//                        判断是否已添加
                        SmartNews smartNews = smartNewsService.getMediaId(nw.getMediaId());
                        if (ObjectUtils.isEmpty(smartNews)) {
                            smartNewsService.save(nw);
                        }else {
                            return;
                        }
                    }
                }
            }
            if (conut != 1) {
                int start = (page - 1) * size;
                JSONArray articles = getArticles(accessToken, start, size);
                for (Object article : articles) {
                    JSONObject article2 = (JSONObject) article;
                    JSONObject content = article2.getJSONObject("content");
                    JSONArray newsItems = content.getJSONArray("news_item");
                    for (int j = 0; j < newsItems.size(); j++) {
                        JSONObject newsItem = newsItems.getJSONObject(j);
                        SmartNews nw = new SmartNews();
                        nw.setMediaId(article2.getStr("article_id"));
                        nw.setTitle(newsItem.getStr("title"));
                        nw.setAuthor(newsItem.getStr("author"));
                        nw.setDigest(newsItem.getStr("digest"));
                        nw.setContent(newsItem.getStr("content"));
                        nw.setContentSourceUrl(newsItem.getStr("content_source_url"));
                        nw.setUrl(newsItem.getStr("url"));
                        String thumbUrl = newsItem.getStr("thumb_url");
                        nw.setFirstImg(thumbUrl);

                        Long updateTime = article2.getLong("update_time");
                        updateTime = updateTime * 1000;
                        nw.setDateTime(new Date(updateTime));
//                        判断是否已添加
                        SmartNews smartNews = smartNewsService.getMediaId(nw.getMediaId());
                        if (ObjectUtils.isEmpty(smartNews)) {
                            smartNewsService.save(nw);
                        }else {
                            return;
                        }
                    }
                }
            }
        }
//        JSONArray articleList = new JSONArray();
//        articles.forEach(item -> {
//            JSONObject wz = new JSONObject();
//            JSONObject article = (JSONObject) item;
//            SmartNews smartNews = new SmartNews();
//            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);
//        });


    }

    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, int start, int size) {
        JSONObject params = new JSONObject();
        params.put("offset", start);
        params.put("count", size);
        String response = HttpUtil.post(ARTICLELiST_URL + accessToken, params.toString());
        JSONObject json = new JSONObject(response);
        return json.getJSONArray("item");
    }



}
