package com.ruoyi.spider.ie;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

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;

/**
 * 题库
 * 
 * @author duzj
 *
 */
public class PaperService2 extends AuthService {

    public void syncPaperAll() {
        List<Entity> all = find(Entity.create("csdhe_subject"));
        for (Entity row : all) {
            for (Integer type : new Integer[] {1, 2}) {
                AtomicInteger page = new AtomicInteger(1);
                while (true) {
                    JSONArray arr = getPaperList(row.getLong("id"), type, page.getAndIncrement());
                    if (null == arr) {
                        break;
                    }
                    for (int i = 0; i < arr.size(); i++) {
                        JSONObject obj = arr.getJSONObject(i);
                        Entity record = Entity.create("csdhe_paper");
                        for (String key : new String[] {"id", "subject_id", "type", "name", "score", "people", "pdf_url"}) {
                            record.set(key, obj.get(key));
                        }
                        insertOrUpdate(record, "id");
                        System.out.println("试卷ID:" + record.getStr("id"));
                    }
                    if (arr.size() < 10) {
                        break;
                    }
                    ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
                }
            }
        }
    }

    /**
     * @param type 类型 1-模拟试卷,2-历年真题
     * @param page 页码
     * @return [{"id":5991,"name":"高职单招英语模拟试卷(一)", "subject_id":1402,"type":1,"score":100,"people":23605,
     *         "pay_status":0,"pdf_url":"https://img2.meite.com/pdf/20230924185230/5991.pdf"}]
     */
    public JSONArray getPaperList(Long subjectId, Integer type, Integer page) {
        Dict params = commonParams();
        String api = "/api/v1.0.5/my_paper_list";
        params.set("page", page).set("limit", 10).set("type", type);
        params.set("subject_id", subjectId).set("cate_id", "1399");
        JSONObject res = getJson(api, params, authorization);
        return res.getJSONObject("data").getJSONArray("data");
    }

    public JSONArray getPaperQuestionList(Long subjectId, Long paperId) {
        Dict params = commonParams();
        String api = "/api/v1.4.0/paper-question-list";
        params.set("paper_id", paperId).set("user_paper_id", 0);
        params.set("subject_id", subjectId).set("cate_id", "1399");
        JSONObject res = getJson(api, params, authorization);
        return res.getJSONObject("data").getJSONArray("data");
    }

    public void syncPaperQuestionAll() {
        String ids = "in 13639,64124,78494,78496,78499,78501,78508,78515,79269,107371,107372,108920,110673";
        List<Entity> all = find(Entity.create("csdhe_paper").set("id", ids));
        for (Entity item : all) {
            Long subjectId = item.getLong("subject_id");
            Long paperId = item.getLong("id");
            syncPaperQuestion(subjectId, paperId);
            ThreadUtil.safeSleep(RandomUtil.randomInt(2, 6) * 800);
        }
    }

    private void syncPaperQuestion(Long subjectId, Long paperId) {
        try {
            JSONArray arr = getPaperQuestionList(subjectId, paperId);
            if (null == arr) {
                return;
            }
            String tableName = "csdhe_paper_question";
            for (int i = 0; i < arr.size(); i++) {
                JSONObject row = arr.getJSONObject(i);
                String[] fields = new String[] {"question_id", "uni_key", "type", "type_name", "name", "grade", "score", "number",
                    "analysis", "answer", "paper_type_title", "paper_type_id"};
                JSONArray ques = row.getJSONArray("material_ques");
                if (row.getBooleanValue("is_materials") && null != ques && ques.size() > 0) {
                    for (int j = 0; j < ques.size(); j++) {
                        row = ques.getJSONObject(j);
                        long questionId = row.getLongValue("question_id");
                        addRef(questionId, paperId);
                        Entity record = Entity.create(tableName).set("paper_id", paperId);
                        for (String key : fields) {
                            record.set(key, row.get(key));
                        }
                        record.set("options", row.getString("options")).set("subject_id", subjectId);
                        record.set("is_materials", Boolean.TRUE).set("materials", row.getString("materials"));
                        List<Entity> coll = find(Entity.create(tableName).set("question_id", questionId));
                        if (CollUtil.isNotEmpty(coll)) {
                            Entity old = coll.get(0);
                            for (String key : new String[] {"analysis", "answer2", "is_right_answer"}) {
                                record.set(key, old.get(key));
                            }
                        } else {
                            insertOrUpdate(record, "question_id");
                        }
                        System.out.println("试题ID:" + paperId + "\t问题ID:" + record.getStr("question_id"));
                    }
                } else {
                    long questionId = row.getLongValue("question_id");
                    addRef(questionId, paperId);
                    Entity record = Entity.create(tableName).set("paper_id", paperId);
                    for (String key : fields) {
                        record.set(key, row.get(key));
                    }
                    record.set("options", row.getString("options")).set("subject_id", subjectId);
                    record.set("is_materials", Boolean.TRUE).set("materials", row.getString("materials"));
                    List<Entity> coll = find(Entity.create(tableName).set("question_id", questionId));
                    if (CollUtil.isNotEmpty(coll)) {
                        Entity old = coll.get(0);
                        for (String key : new String[] {"analysis", "answer2", "is_right_answer"}) {
                            record.set(key, old.get(key));
                        }
                    } else {
                        insertOrUpdate(record, "question_id");
                    }
                    System.out.println("试题ID:" + paperId + "\t问题ID:" + record.getStr("question_id"));
                }
            }
        } catch (Exception e) {
            logger.error("同步试题出错:{}:{}", subjectId, paperId, e);
        }
    }

    private void addRef(long questionId, Long paperId) {
        Entity record = Entity.create("csdhe_paper_question_ref").set("q_id", questionId).set("paper_id", paperId);
        insertOrUpdate(record, "q_id", "paper_id");
    }

    public static void main(String[] args) {
        PaperService2 service = new PaperService2();
        // service.syncPaperAll();
        // System.out.println(service.getPaperList(1402l, 1, 1));
        // System.out.println(service.getPaperQuestionList(1400l, 6204l));
        service.syncPaperQuestionAll();
    }
}
