package com.ruoyi.spider.ie;

import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.spider.utils.DBUtil;
import com.ruoyi.spider.utils.HttpClientUtil;
import com.ruoyi.spider.utils.UsignUtils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.sql.Direction;
import cn.hutool.db.sql.Order;
import cn.hutool.db.sql.SqlBuilder;
import okhttp3.Headers;

public class EepwService {
    static String authorization =
        "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvdWMuY3NkaGUuY29tXC92MVwvYXV0aFwvbG9naW4iLCJpYXQiOjE3MDA1NTQ2MjcsImV4cCI6MTcwMzE0NjYyNywibmJmIjoxNzAwNTU0NjI3LCJqdGkiOiI0MERYQThrQUIya2JWN0hvIiwic3ViIjo3MDkyMjU4LCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.trns8Krm15lw5zT4s1VSWOLWgtK-Dfpmjb7Ng8A_054";
    Boolean ckeck = Boolean.FALSE;

    private JSONObject postJson(String url, Map<String, String> data) {
        String res = HttpClientUtil.post(url, Dict.create(), data, null);
        return JSONObject.parseObject(res);
    }

    private JSONObject postJson(String url, Dict params, Map<String, String> data, String authorization) {
        long time = System.currentTimeMillis() / 1000;
        params.set("timestrap", "" + time);
        params.set("sign", UsignUtils.getUsignAll2(url, JSON.toJSONString(params)));
        Headers headers = null == authorization ? null : Headers.of("authorization", authorization);
        String res = HttpClientUtil.post(url, params, data, headers);
        return JSONObject.parseObject(res);
    }

    private void me() {
        // https://www.eepw.com/me?//
        // app_type=examWeb&timestrap=1700554628&platform=pc&channel=www.eepw.com&sign=ebc7ab72c77cd5c41a8a1946829657ca
        Dict params = Dict.create();
        params.set("app_type", "examWeb");
        params.set("platform", "pc");
        //https://questions.csdhe.com/api/v1.6.5/college/detail/9838?app_type=senioriup&good_app_type=senioriup&province_id=5604&platform=iossh&timestrap=1728870914&deviceid=senioriupe1c36ec764e85a0838ef5579608644&channel=appStore&version=v1.8.6&oaid=1234&sign=67da4d6c9f507a5fb68e70c67544dca3&id=9838&province_id=5604&subject_id=1401&cate_id=1399
        params.set("channel", "www.eepw.com");
        long time = System.currentTimeMillis() / 1000;
        params.set("timestrap", "" + time);
        String url = "https://www.eepw.com/me";
        params.set("sign", UsignUtils.getUsignAll2(url, JSON.toJSONString(params)));
        Headers headers = null == authorization ? null : Headers.of("authorization", authorization);
        String res = HttpClientUtil.get(url, HttpClientUtil.UTF_8, params, headers);
        System.out.println(res);
    }

    private String getHtml(String url) {
        return getHtml(url, Dict.create(), authorization);
    }

    @SuppressWarnings("unused")
    private String getHtml(String url, Dict params) {
        return getHtml(url, params, authorization);
    }

    private String getHtml(String url, Dict params, String authorization) {
        Headers headers = null == authorization ? null : Headers.of("authorization", authorization);
        return HttpClientUtil.get(url, HttpClientUtil.UTF_8, params, headers);
    }

    public void login() {
        String url = "https://uc.csdhe.com/v1/auth/login";
        Map<String, String> data = new LinkedHashMap<>();
        data.put("mobile", "19119260810");
        data.put("password", "260810");
        data.put("deviceid", "PC");
        data.put("apptype", "examWeb");
        data.put("channel", "www.eepw.com");
        JSONObject res = postJson(url, data);
        String token = res.getJSONObject("Result").getString("access_token");
        // System.out.println(token);
        authorization = "bearer " + token;
        System.out.println(authorization);
    }

    public JSONObject commitKnowAnswer(String uniKey, String answer, Integer type, Long subjectId, Long knowId, Integer num) {
        try {
            ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
            Dict params = Dict.create().set("app_type", "examWeb").set("platform", "web");
            Map<String, String> data = new LinkedHashMap<>();
            // answer=A&uni_key=qzq2cji8cdm9&type=2&subject_id=1401&number=6&know_id=21989&good_app_type=senioriup
            data.put("answer", answer);
            data.put("uni_key", uniKey);
            data.put("type", "" + type);
            data.put("subject_id", "" + subjectId);
            if (null != num) {
                data.put("number", "" + num);
            }
            data.put("know_id", "" + knowId);
            data.put("good_app_type", "senioriup");
            String url = "https://www.eepw.com/api/v1/commit_answer";
            JSONObject res = postJson(url, params, data, authorization);
            return res.getJSONObject("data").getJSONObject("data");
        } catch (Exception e) {
            e.printStackTrace();
            return new JSONObject();
        }
    }

    public void syncKnowledgeAnswer() {
        List<Entity> all = DBUtil.find(Entity.create("csdhe_knowledge").set("level", 2));
        for (Entity row : all) {
            syncKnowAnswer(row.getLong("subject_id"), row.getLong("id"));
        }
    }

    public void syncKnowAnswer(Long subjectId, Long knowId) {
        while (ckeck) {
            int hour = LocalTime.now().getHour();
            if (hour < 22 && hour >= 8) {
                System.out.println("只在晚上22点至早上8点前,运行!");
                ThreadUtil.sleep(5, TimeUnit.SECONDS);
                continue;
            } else {
                break;
            }
        }
        SqlBuilder builder = SqlBuilder.create().select().from("csdhe_question");
        builder.where("is_right_answer= ? and id in (select question_id from csdhe_question_ref where ref_id = ? and type='know_test' )");
        String sql = builder.orderBy(new Order("id", Direction.ASC)).append(" limit 0,100").build();
        List<Entity> coll = DBUtil.query(sql, 0, knowId);
        if (CollUtil.isEmpty(coll)) {
            return;
        }
        for (Entity entity : coll) {
            Long qid = entity.getLong("id");
            String uniKey = entity.getStr("uni_key");
            JSONObject data = commitKnowAnswer(uniKey, "A", entity.getInt("type"), subjectId, knowId, null);
            String answer = data.getString("answer");
            if (StrUtil.isNotBlank(answer)) {
                entity.set("answer2", answer).set("is_right_answer", 1);
                DBUtil.updateById(entity);
            }
            System.out.println("问题Id:" + qid + "答案为:" + entity.get("answer2"));
        }
    }

    /**
     * 根据unikey查询答案
     *
     * @param name
     * @param uniKey
     * @return
     */
    public void syncLookupAnswer() {
        long lastId = 0;
        while (true) {
            SqlBuilder builder = SqlBuilder.create().select().from("csdhe_know_question_2");
            builder.where("uni_key<>'' and is_right_answer=? and id>?");
            String sql = builder.orderBy(new Order("id", Direction.ASC)).append(" limit 0,100").build();
            List<Entity> coll = DBUtil.query(sql, 0, lastId);
            for (Entity entity : coll) {
                Long qid = entity.getLong("id");
                lastId = qid;
                JSONObject data = lookupAnswer(entity.getStr("name"), entity.getStr("uni_key"));
                String analysis = data.getString("analysis");
                String answer = data.getString("answer");
                if (StrUtil.isNotBlank(answer)) {
                    entity.set("analysis", StrUtil.blankToDefault(analysis, entity.getStr("analysis")));
                    entity.set("answer2", answer).set("is_right_answer", 1);
                    DBUtil.updateById(entity);
                }
                System.out.println("问题Id:" + qid + "答案为:" + entity.get("answer2"));
            }
            if (coll.size() < 100) {
                break;
            }
        }
    }

    /**
     * 根据unikey查询答案
     *
     * @param name
     * @param uniKey
     * @return
     */
    private JSONObject lookupAnswer(String name, String uniKey) {
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
        getHtml(String.format("https://www.eepw.com/search/%s？#", name));
        me();
        //
        getHtml(String.format("https://www.eepw.com/shiti/%s.html", uniKey));
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
        String url = String.format("https://www.eepw.com/api/v1/questions/answer/%s", uniKey);
        // ?app_type=examWeb&platform=pc&timestrap=1700623340&sign=16c434e6cb0a55604522f8dd2262ea31
        Dict params = Dict.create();
        params.set("app_type", "examWeb");
        params.set("platform", "pc");
        long time = System.currentTimeMillis() / 1000;
        params.set("timestrap", "" + time);
        params.set("sign", UsignUtils.getUsignAll2(url, JSON.toJSONString(params)));
        String res = getHtml(url, params, authorization);
        return JSON.parseObject(res).getJSONObject("data");
    }

    /**
     *
     */
    public void syncPapgerAnswer() {
        List<Entity> all = DBUtil.find(Entity.create("csdhe_paper"));
        for (Entity item : all) {
            Long subjectId = item.getLong("subject_id");
            Long paperId = item.getLong("id");
            syncPaperAnswer(subjectId, paperId);
        }
    }

    private JSONObject commitPaperAnswer(String uniKey, String answer, Integer type, Long subjectId, Long userPaperId) {
        try {
            ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
            // app_type=examWeb&platform=web
            Dict params = Dict.create().set("app_type", "examWeb").set("platform", "web");
            Map<String, String> data = new LinkedHashMap<>();
            // answer=D&uni_key=nexlazi5t8h4&type=3&subject_id=1400&user_paper_id=6189865
            data.put("answer", answer);
            data.put("uni_key", uniKey);
            data.put("type", "3");
            data.put("subject_id", "" + subjectId);
            data.put("user_paper_id", "" + userPaperId);
            String url = "https://www.eepw.com/api/v1/commit_answer";
            JSONObject res = postJson(url, params, data, authorization);
            System.out.println(res);
            return res.getJSONObject("data").getJSONObject("data");
        } catch (Exception e) {
            return new JSONObject();
        }
    }

    private JSONObject commitPaper(Long paperId, Long subjectId, Long userPaperId) {
        try {
            ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
            // ?app_type=examWeb&platform=web&timestrap=1700639517&sign=3aad0af3dcec39fd4073337025f72a01
            Dict params = Dict.create().set("app_type", "examWeb").set("platform", "web");
            Map<String, String> data = new LinkedHashMap<>();
            // paper_id=6204&subject_id=1400&user_paper_id=6189865&make_time=1366&app_type=examWeb
            data.put("paper_id", "" + paperId);
            data.put("subject_id", "" + subjectId);
            data.put("user_paper_id", "" + userPaperId);
            data.put("make_time", "" + RandomUtil.randomInt(800, 2000));
            data.put("app_type", "examWeb");
            String url = "https://www.eepw.com/api/v1/commit_paper";
            JSONObject res = postJson(url, params, data, authorization);
            return res.getJSONObject("data").getJSONObject("data");
        } catch (Exception e) {
            return new JSONObject();
        }

    }

    private void syncPaperAnswer(Long subjectId, Long paperId) {
        while (ckeck) {
            int hour = LocalTime.now().getHour();
            if (hour < 22 && hour >= 8) {
                System.out.println("只在晚上22点至早上8点前,运行!");
                return;
            } else {
                break;
            }
        }
        List<Entity> coll = DBUtil.find(Entity.create("csdhe_paper_question").set("paper_id", paperId).set("is_right_answer", 0));
        if (CollUtil.isEmpty(coll)) {
            System.out.println("问卷["+paperId+"],已完成获取答案.");
            return;
        }
        ThreadUtil.safeSleep(RandomUtil.randomInt(1, 5) * 800);
        String html = getHtml(String.format("https://www.eepw.com/test?pid=%s", paperId));
        me();
        Document doc = Jsoup.parse(html);
        Long userPaperId = Convert.toLong(doc.select("input[name=user_paper_id]").val());
        for (Entity entity : coll) {
            Long qid = entity.getLong("question_id");
            String uniKey = entity.getStr("uni_key");
            JSONObject data = commitPaperAnswer(uniKey, "A", entity.getInt("type"), subjectId, userPaperId);
            String qid2 = data.getString("question_id");
            String analysis = data.getString("analysis");
            String answer = data.getString("answer");
            if (StrUtil.isNotBlank(answer)) {
                entity.set("analysis", StrUtil.blankToDefault(analysis, entity.getStr("analysis")));
                entity.set("answer2", answer).set("is_right_answer", 1);
                DBUtil.updateById(entity);
            }
            System.out.println("问题Id:" + qid + "\t,[" + qid2 + "]答案为:" + entity.get("answer2"));
        }
        commitPaper(paperId, subjectId, userPaperId);
        ThreadUtil.safeSleep(RandomUtil.randomInt(2, 6) * 800);
    }

    public static void main(String[] args) {
        EepwService service = new EepwService();
        service.login();
        //service.syncKnowledgeAnswer();
        service.syncLookupAnswer();
        //service.syncPapgerAnswer();
    }

}
