package com.ruoyi.spider.ie;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Entity;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.spider.helper.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 资讯服务
 *
 * @author duzj
 */
public class ArticleService extends AuthService {
    public static String tableName = "csdhe_article";

    public void syncAll(Integer provinceId) {
        // [{"key":"recommend","value":"热门" },{"key":"experience","value":"备考心得" },{"key":"outline","value":"考试大纲"
        // },{"key":"trends","value":"考试动态" },{"key":"newhand","value":"新手必读" },{"key":"examask","value":"考试问答"
        // },{"key":"fingerpost","value":"报考指南" },{"key":"result","value":"成绩查询" }]
        for (String type : new String[]{"recommend", "experience", "outline", "trends", "newhand", "examask", "fingerpost", "result"}) {
            getList(type,provinceId);
        }
    }

    private void getList(String type,Integer provinceId) {
        String api = "/api/v1/articles-list";
        AtomicInteger page = new AtomicInteger(1);
        int size = 20;
        List<Entity> coll = find(Entity.create(tableName));
        Map<Long ,Long> existArticleIds = new HashMap<>();
        for (Entity row : coll) {
            existArticleIds.put(row.getLong("id"),row.getLong("id"));
        }
        while (true) {
            Dict params = commonParams();
            params.set("province_id", provinceId).set("information_id", type);
            params.set("page", page.getAndIncrement()).set("limit", size);
            params.set("cate_id", 1399).set("subject_id", 1400);
            JSONObject res = getJson(api, params, authorization);
            JSONArray arr = res.getJSONObject("data").getJSONObject("list").getJSONArray("data");

            System.out.println("取数据完成，第"+page+"页");
            if (CollUtil.isEmpty(arr)) {
                break;
            }

            for (int i = 0; i < arr.size(); i++) {
                JSONObject row = arr.getJSONObject(i);
                if (existArticleIds.containsKey(row.getLong("id"))){
                    System.out.println("存在文章-id为 "+row.getLong("id")+" ，不重新取数据");
                    continue;
                }
                if (!row.getString("title").contains("2025")) {
                    //非2025的先不处理
                    continue;
                }
                getDetail(row,provinceId);
            }
            if (arr.size() < size) {
                break;
            }
        }
    }

    private void getDetail(JSONObject row,Integer provinceId) {
        String api = "/api/v1/articles-show";
        // ? province_id=5485&id=56307&cate_id=1399&subject_id=1400&good_app_type=senioriup&sign=33a668193bc5be55c21261d6f5f7f75f
        Dict params = commonParams();
        params.set("id", row.get("id"));
        JSONObject res = getJson(api, params, authorization);
        JSONObject data = res.getJSONObject("data");
        JSONObject bean = data.getJSONObject("info");
        Entity record = Entity.create(tableName).parseBean(bean);
        JSONArray refs = data.getJSONArray("tj_list");
        if (CollUtil.isNotEmpty(refs)) {
            List<Object> ids = new ArrayList<>(refs.size());
            for (int i = 0; i < refs.size(); i++) {
                ids.add(refs.getJSONObject(i).get("id"));
            }
            record.set("ref_ids", ids);
        }
        record.set("province_id", provinceId);
        record.set("ref_ids", record.getStr("ref_ids") );
        insertOrUpdate(record, "id");
        System.out.println(record.getLong("id") + "\t" + record.getStr("title"));
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 6) * 800);
    }




    public static void main(String[] args) {
        // 湖南省 5604，河南 5310
        Integer provinceId = 5604;
        ArticleService service = new ArticleService();
        service.syncAll(provinceId);
    }

}
