package com.jsc.oscm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsc.oscm.entity.CrawlNode;
import com.jsc.oscm.service.CrawlNodeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

@Component
public class SpiderCleanupTask {

    @Resource
    private CrawlNodeService crawlNodeService;

    @Value("${spiderRunningTimeLimit}")
    Integer spiderRunningTimeLimit;

    private static final Logger logger = Logger.getLogger(SpiderCleanupTask.class.getName());

    @Scheduled(cron = "0 0/10 * * * *")
    public void cleanUpSpiders() throws ParseException {
        List<CrawlNode> allCrawlNodes = crawlNodeService.queryAllCrawlNodes();
        for (CrawlNode crawlNode : allCrawlNodes) {
            if (crawlNode.getNodeStatus() != 0) {
                String nodeIp = crawlNode.getNodeIp();
                String scrapydProjectsString = HttpUtil.get(String.format("http://%s/listprojects.json", nodeIp));
                JSONObject scrapydProjects = JSON.parseObject(scrapydProjectsString);
                JSONArray currentProjects = scrapydProjects.getJSONArray("projects");
                for (Object project : currentProjects) {
                    String scrapydListJobsString = HttpUtil.get(String.format("http://%s/listjobs.json?project=%s", nodeIp, project));
                    JSONObject scrapydListJobs = JSON.parseObject(scrapydListJobsString);
                    JSONArray runningJobs = scrapydListJobs.getJSONArray("running");
                    for (Object runningJobObj : runningJobs) {
                        JSONObject runningJob = JSON.parseObject(runningJobObj.toString());
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date startTime = simpleDateFormat.parse(runningJob.getString("start_time"));
                        long startTimestamp = startTime.getTime();
                        long currentTimestamp = System.currentTimeMillis();
                        if (currentTimestamp - startTimestamp > spiderRunningTimeLimit * 60 * 1000) {
                            String jobId = runningJob.getString("id");
                            Map<String, Object> cancelParam = new HashMap<>();
                            cancelParam.put("project", project.toString());
                            cancelParam.put("job", jobId);
                            HttpUtil.formRequest(String.format("http://%s/cancel.json", nodeIp), cancelParam);
                            logger.log(Level.INFO, String.format("清理 %s 节点的超时任务：%s", nodeIp, jobId));
                        }
                    }
                }
            }
        }
//        logger.log(Level.INFO, "运行超时 spider 清理任务完成");
    }

}
