package com.ruoyi.spider.ie;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.spider.utils.DBUtil;
import com.ruoyi.spider.utils.HttpClientUtil;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.db.Entity;

public class DingKaoService extends AbstraceService {

    static String host = "https://api.dingkao.cn/";
    static String token = "b709fc3c459ea2ecb258be828d01f578";

    private Map<String, String> sign(Dict data) {
        Map<String, String> dataMap = new LinkedHashMap<>(12);
        dataMap.put("timestamp", "" + System.currentTimeMillis());
        dataMap.put("platform", "1");
        dataMap.put("version", "0.5.2");
        dataMap.put("nonce", RandomUtil.randomString(8));
        dataMap.put("seller_id", "129");
        dataMap.put("token", token);
        for (String key : data.keySet()) {
            dataMap.put(key, data.getStr(key));
        }
        List<String> keys = new ArrayList<>(dataMap.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append("=").append(dataMap.get(key)).append("&");
        }
        sb.append("key=c486caec5a91cbd5eb1848414371d144");
        String sign = Md5Utils.hash(sb.toString());
        dataMap.put("sign", sign);
        return dataMap;
    }

    private JSONObject postByForm(String api, Dict data) {
        String text = HttpClientUtil.post(host + api, sign(data));
        return JSONObject.parseObject(text);
    }

    public String login() {
        Dict data = Dict.create();
        data.set("username", "huncs01123456").set("password", "asd123456");
        JSONObject res = postByForm("/v1.member.public/login", data);
        String token = res.getJSONObject("data").getString("token");
        DingKaoService.token = token;
        System.out.println(token);
        return token;

    }

    public void syncCateAll() {
        Dict data = Dict.create().set("parent_id", "96").set("type", "2");
        JSONObject res = postByForm("/v1.index.cate/children", data);
        JSONArray arr = res.getJSONArray("data");
        if (null != arr && arr.size() > 0) {
            for (int i = 0; i < arr.size(); i++) {
                JSONObject json = arr.getJSONObject(i);
                Entity record = Entity.create("dingkao_cate");
                for (String key : new String[] {"id", "parent_id", "type", "code", "title", "desc", "level", "sort"}) {
                    record.set(key, json.get(key));
                }
                insertOrUpdate(record, "id");
                JSONArray children = json.getJSONArray("children");
                if (null != children && children.size() > 0) {
                    for (int j = 0; j < children.size(); j++) {
                        JSONObject item = children.getJSONObject(j);
                        record = Entity.create("dingkao_cate");
                        for (String key : new String[] {"id", "parent_id", "type", "code", "title", "desc", "level", "sort"}) {
                            record.set(key, item.get(key));
                        }
                        insertOrUpdate(record, "id");
                    }
                }
            }
        }
    }

    public JSONArray qbankList(Integer cateId) {
        Dict data = Dict.create().set("page", "1").set("pageNum", "20").set("cate_id", cateId);
        JSONObject res = postByForm("/v1.qbank.index/list", data);
        return res.getJSONArray("data");
    }

    public void syncQbankAll() {
        List<Entity> coll = find(Entity.create("dingkao_cate").set("level", 3));
        for (Entity row : coll) {
            JSONArray arr = qbankList(row.getInt("id"));
            if (null != arr && arr.size() > 0) {
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject json = arr.getJSONObject(i);
                    Entity record = Entity.create("dingkao_qbank");
                    for (String key : new String[] {"id", "cate_id", "cert_id", "title", "logo", "question_count", "question_chapter",
                        "paper_count"}) {
                        record.set(key, json.get(key));
                    }
                    insertOrUpdate(record, "id");
                }
            }
        }
    }

    public JSONArray chapterList(Long qbankId) {
        Dict data = Dict.create().set("qbank_id", qbankId);
        JSONObject res = postByForm("/v1.qbank.chapter/list", data);
        return res.getJSONArray("data");
    }

    public void syncChapterAll() {
        List<Entity> coll = find(Entity.create("dingkao_qbank"));
        for (Entity row : coll) {
            JSONArray arr = chapterList(row.getLong("id"));
            Integer cateId = row.getInt("cate_id");
            convertChapter(arr, cateId);
        }
    }

    private void convertChapter(JSONArray arr, Integer cateId) {
        if (null != arr && arr.size() > 0) {
            for (int i = 0; i < arr.size(); i++) {
                JSONObject json = arr.getJSONObject(i);
                Entity record = Entity.create("dingkao_chapter");
                for (String key : new String[] {"id", "parent_id", "qbank_id", "title", "question_count", "level", "sort", "path"}) {
                    record.set(key, json.get(key));
                }
                record.set("cate_id", cateId);
                insertOrUpdate(record, "id");
                convertChapter(json.getJSONArray("children"), cateId);
            }
        }
    }

    public JSONArray chapterQuestionList(Long qbankId, Long chapterId) {
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
        Dict data = Dict.create().set("qbank_id", qbankId).set("chapter_id", chapterId);
        JSONObject res = postByForm("/v1.qbank.question/list", data);
        return res.getJSONArray("data");
    }

    public void syncChapterQuestionAll() {
        List<Entity> coll = find(Entity.create("dingkao_chapter"));
        for (Entity row : coll) {
            Long qbankId = row.getLong("qbank_id");
            Long chapterId = row.getLong("id");
            JSONArray arr = chapterQuestionList(qbankId, chapterId);
            if (null != arr && arr.size() > 0) {
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject json = arr.getJSONObject(i);
                    Entity record = Entity.create("dingkao_chapter_question");
                    for (String key : new String[] {"id", "qbank_id", "chapter_id", "type_id", "kind_id", "kind_text", "parent_id",
                        "analysis", "sort", "difficulty", "score"}) {
                        record.set(key, json.get(key));
                    }
                    Integer type = json.getInteger("type_id");
                    record.set("name", json.getString("stem"));
                    if (type < 5 && json.getJSONArray("options") != null) {
                        record.set("options", json.getJSONArray("options").toJSONString());
                    } else {
                        record.set("options", json.getString("options"));
                    }
                    if (type < 5 && json.getJSONArray("answer") != null) {
                        record.set("answer", json.getJSONArray("answer").toJSONString());
                    } else {
                        record.set("answer", json.getString("answer"));
                    }
                    insertOrUpdate(record, "id");
                    System.out.println("问题ID:" + record.getStr("id"));
                }
            }
        }
    }

    public JSONArray paperList(Long qbankId) {
        Dict data = Dict.create().set("qbank_id", qbankId).set("page", 1).set("pageNum", 200);
        JSONObject res = postByForm("/v1.qbank.paper/list", data);
        return res.getJSONArray("data");
    }

    public void syncPaperAll() {
        List<Entity> coll = find(Entity.create("dingkao_qbank"));
        for (Entity row : coll) {
            JSONArray arr = paperList(row.getLong("id"));
            Integer cateId = row.getInt("cate_id");
            if (null != arr && arr.size() > 0) {
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject json = arr.getJSONObject(i);
                    Entity record = Entity.create("dingkao_paper");
                    for (String key : new String[] {"id", "qbank_id", "title", "content", "config", "sort", "question_num", "total_score",
                        "pass_score", "limit_time", "is_recommend"}) {
                        record.set(key, json.get(key));
                    }
                    record.set("cate_id", cateId).set("tags", json.getString("tags"));
                    insertOrUpdate(record, "id");
                }
            }
        }
    }

    public JSONArray paperQuestionList(Long paperId) {
        // 重新答案
        Dict data = Dict.create().set("paper_id", paperId);
        postByForm("/v1.qbank.paper/reform", data);
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
        // 获取问题
        JSONObject res = postByForm("/v1.qbank.paper/question", data);
        JSONArray arr = res.getJSONObject("data").getJSONArray("list");
        // 作答
        long start_time = System.currentTimeMillis() / 1000;
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 1570);
        JSONArray questions = new JSONArray(arr.size());
        for (int i = 0; i < arr.size(); i++) {
            JSONObject json = arr.getJSONObject(i);
            questions.add(Dict.create().set("id", json.get("id")).set("answer", ""));
        }
        data = Dict.create().set("paper_id", paperId).set("start_time", start_time);
        data.set("questions", questions.toJSONString());
        res = postByForm("/v1.qbank.paper/submit", data);
        String paper_history_id = res.getJSONObject("data").getString("paper_history_id");
        // 获取解析
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 2) * 800);
        res = postByForm("/v1.qbank.paper/analysis", Dict.create().set("paper_history_id", paper_history_id));

        return res.getJSONObject("data").getJSONArray("list");
    }

    public void syncPaperQuestionAll() {
        // find(Entity.create("dingkao_paper") );
        List<Entity> coll = DBUtil.query(
            "select * from dingkao_paper where id not in(select distinct paper_id from dingkao_paper_question where kind_id <>0) order by id asc");
        for (Entity row : coll) {
            Long paperId = row.getLong("id");
            JSONArray arr = paperQuestionList(paperId);
            if (null != arr && arr.size() > 0) {
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject json = arr.getJSONObject(i);
                    Entity record = Entity.create("dingkao_paper_question");
                    for (String key : new String[] {"id", "parent_id", "qbank_id", "chapter_id", "type_id", "kind_id", "kind_text",
                        "difficulty", "sort", "score", "analysis"}) {
                        record.set(key, json.get(key));
                    }
                    record.set("paper_id", paperId).set("name", json.getString("stem"));
                    record.set("chapter", json.getString("chapter"));
                    Integer type = json.getInteger("type_id");
                    if (type < 5 && json.getJSONArray("options") != null) {
                        record.set("options", json.getJSONArray("options").toJSONString());
                    } else {
                        record.set("options", json.getString("options"));
                    }
                    if (type < 5 && json.getJSONArray("answer") != null) {
                        record.set("answer", json.getJSONArray("answer").toJSONString());
                    } else {
                        record.set("answer", json.getString("answer"));
                    }
                    insertOrUpdate(record, "id");
                    System.out.println("试卷ID:" + record.getStr("paper_id") + "\t问题ID:" + record.getStr("id"));
                }
            }
        }
    }

    public static void main(String[] args) {
        DingKaoService service = new DingKaoService();
        service.login();
        service.syncCateAll();
        service.syncQbankAll();
        service.syncChapterAll();
        service.syncPaperAll();
        service.syncChapterQuestionAll();
        service.syncPaperQuestionAll();
    }

}
