package com.xxl.job.executor.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.log.XxlJobLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@Component
public class JobWaitingQueueThread extends Thread {

    @Value("${oscm.server.url}")
    String oscmServer;


    public void addToWaitingQueue(Map<String, Object> CrawlTaskInfo) {
        JSONObject bestNode = new JSONObject();
        bestNode.put("nodeId", "17");
        bestNode.put("nodeIp", "107.182.191.3:6788");
        CrawlTaskInfo.put("node", bestNode);
        buildCrawlThread(CrawlTaskInfo);
    }

    public void buildCrawlThread(Map<String, Object> CrawlTaskInfo) {
        JSONObject paramsMap = JSON.parseObject(CrawlTaskInfo.get("paramsMap").toString());
        JSONObject node = JSON.parseObject(CrawlTaskInfo.get("node").toString());
        String url = CrawlTaskInfo.get("url").toString();
        //4.1触发采集线程
        String scheduleUrl = String.format("http://%s/schedule.json", node.getString("nodeIp"));
        Map<String, String> postData = new HashMap<>();
        postData.put("project", paramsMap.getString("project"));
        postData.put("spider", paramsMap.getString("spider"));
        postData.put("params", JSON.toJSONString(paramsMap));
        String scheduleResult = HttpUtil.formPost(scheduleUrl, postData);
        //4.2、回调采集管理平台接口，创建执行记录,从scheduleResult中可解析出scrapyd任务id
        String scrapydJobId = null;
        JSONObject scheduleResultMap = JSON.parseObject(scheduleResult);
        if (scheduleResultMap == null || scheduleResultMap.getString("status") == null || !scheduleResultMap.getString("status").equals("ok")) {
            XxlJobLogger.log(String.format("站点：%s在采集节点%s上调度失败", url, node.get("nodeIp")));
        } else {
            scrapydJobId = scheduleResultMap.getString("jobid");
        }
        //4.4调用oscm接口，创建执行记录
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> oscmLogMap = new HashMap<>();
        oscmLogMap.put("jobId", paramsMap.get("job_id"));
        oscmLogMap.put("taskId", paramsMap.get("taskid").toString());
        oscmLogMap.put("createTime", simpleDateFormat.format(new Date()));
        oscmLogMap.put("startTime", simpleDateFormat.format(new Date()));
        oscmLogMap.put("scrapydId", scrapydJobId);
        oscmLogMap.put("status", "0");
        oscmLogMap.put("pagesCount", "0");
        oscmLogMap.put("itemCount", "0");
        oscmLogMap.put("nodeId", node.get("id"));
        oscmLogMap.put("redisQueueName", "WebSite_" + paramsMap.get("clusterName"));
        if (scrapydJobId == null) {
            //调度失败
            oscmLogMap.put("finishTime", simpleDateFormat.format(new Date()));
            oscmLogMap.put("status", "2");
            oscmLogMap.put("result", "0");
            HttpUtil.post(String.format("%s/api/open/crawljob", oscmServer), oscmLogMap);
            return;
        }
        XxlJobLogger.log("创建执行记录");
        String response = HttpUtil.post(String.format("%s/api/open/crawljob", oscmServer), oscmLogMap);
        JSONObject rspObj = JSON.parseObject(response);
        if (rspObj == null || !rspObj.getString("code").equals("200")) {
            XxlJobLogger.log("创建oscm执行记录失败");
        }
    }

}
