package com.jsc.oscm.service;

import com.jsc.oscm.dao.LogRepository;
import com.jsc.oscm.dao.TaskRepository;
import com.jsc.oscm.entity.Log;
import com.jsc.oscm.entity.Task;
import com.jsc.oscm.util.DateUtil;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class LogService {

    @Resource
    LogRepository logRepository;

    @Resource
    TaskRepository taskRepository;

    public Log findByJobId(String jobId) {
        return logRepository.findByJobId(jobId);
    }

    public String getScrapydJobURL(Integer logId) {
        Log log = logRepository.findById(logId).get();
        String scrapydJobId = log.getScrapydId();
        Optional<Task> relatedTask = taskRepository.findById(log.getTaskId());
        if (relatedTask.isPresent()) {
            Task task = relatedTask.get();
            String address = task.getServer();
            String project = task.getProject();
            String spider = task.getSpider();
            if (address == null) {
                address = "107.182.191.3:6788";
            }
            return String.format("http://%s/logs/%s/%s/%s.log", address, project, spider, scrapydJobId);
        } else {
            return null;
        }
    }

    private List<Integer> handleTaskIdList(String project, String spider) {
        List<Integer> idList = new ArrayList<>();
        //首先根据project和spider查询出对应的task及taskid
        List<Task> tasks;
        if (project.length() == 0 || project.equals("全部")) {
            tasks = taskRepository.findAll();
        } else {
            Task exampleTask = new Task();
            exampleTask.setProject(project);
            if (spider.length() > 0 && !spider.equals("全部")) {
                exampleTask.setSpider(spider);
            }
            Example<Task> example = Example.of(exampleTask);
            tasks = taskRepository.findAll(example);
        }
        tasks.forEach(e -> idList.add(e.getId()));
        return idList;
    }

    public List<Log> queryPageable(int index, int size, Map<String, Object> queryParam) {
        String project = queryParam.get("project").toString();
        String spider = queryParam.get("spider").toString();
        List<Integer> idList = handleTaskIdList(project, spider);
        //处理日期范围
        Date startDate = new Date(0);
        Date endDate = new Date();
        if (queryParam.get("startDate").toString().length() != 0) {
            startDate = new Date(Long.parseLong(queryParam.get("startDate").toString()));
        }
        if (queryParam.get("endDate").toString().length() != 0) {
            endDate = new Date(Long.parseLong(queryParam.get("endDate").toString()));
        }
        Pageable pageable = PageRequest.of(index, size, Sort.by(Sort.Order.desc("id")));
        return logRepository.findByTaskIdInAndCreateTimeBetweenOrderByCreateTimeDesc(
                idList, startDate, endDate, pageable);
    }

    public Long queryCount(Map<String, Object> queryParam) {
        String project = queryParam.get("project").toString();
        String spider = queryParam.get("spider").toString();
        List<Integer> idList = handleTaskIdList(project, spider);
        //处理日期范围
        Date startDate = new Date(0);
        Date endDate = new Date();
        if (queryParam.get("startDate").toString().length() != 0) {
            startDate = new Date(Long.parseLong(queryParam.get("startDate").toString()));
        }
        if (queryParam.get("endDate").toString().length() != 0) {
            endDate = new Date(Long.parseLong(queryParam.get("endDate").toString()));
        }
        return logRepository.countAllByTaskIdInAndCreateTimeBetween(idList, startDate, endDate);
    }

    public Log save(Log log) {
        return logRepository.saveAndFlush(log);
    }

    public Long getAllCount() {
        return logRepository.count();
    }

    public Long getSuccessCount() {
        Log log = new Log();
        log.setResult("1");
        Example<Log> example = Example.of(log);
        return logRepository.count(example);
    }
}
