package com.jsc.oscm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jsc.oscm.dao.LogRepository;
import com.jsc.oscm.entity.Log;
import com.jsc.oscm.model.ReturnT;
import com.jsc.oscm.service.LogService;
import com.jsc.oscm.util.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class LogController {

    @Resource
    LogService logService;

    @Value("${xxl.job.admin.server}")
    String xxlJobAdminServer;

    @PostMapping("/crawljob/queryPageable/{index}/{size}")
    public String queryPageable(@PathVariable(name = "index") int index,
                                @PathVariable(name = "size") int size,
                                @RequestBody Map<String, Object> queryParam) {
        ReturnT<List<Log>> returnT;
        try {
            returnT = new ReturnT<>(200, String.valueOf(logService.queryCount(queryParam)),
                    logService.queryPageable(index, size, queryParam));
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    @PostMapping("/crawljob/getScrapydLogURL")
    public String getScrapydLogURL(@RequestBody JSONObject log) {
        ReturnT<String> returnT;
        try {
            Integer logId = log.getInteger("id");
            String url = logService.getScrapydJobURL(logId);
            if (url != null) {
                returnT = new ReturnT<>(200, "", url);
            } else {
                returnT = new ReturnT<>(404, "", null);
            }
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }


    @GetMapping("/crawljob/detail/{id}")
    public String findJobLogById(@PathVariable(name = "id") int id) {
        ReturnT<String> returnT;
        try {
            String scrapydLogDetail = HttpUtil.get(logService.getScrapydJobURL(id));
            if (scrapydLogDetail != null) {
                returnT = new ReturnT<>(200, "", scrapydLogDetail);
            } else {
                returnT = new ReturnT<>(404, "原Scrapyd日志不存在或已被清理", null);
            }
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }


    /**
     * 供 xxl-job 调用的执行记录创建接口
     */
    @PostMapping("/open/crawljob")
    public String openSave(@RequestBody Log log) {
        ReturnT<Log> returnT;
        try {
            Log savedLog = logService.save(log);
            returnT = new ReturnT<>(200, "", savedLog);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), null);
        }
        return JSON.toJSONString(returnT);
    }

    /**
     * 供采集引擎调用的执行日志状态更新接口
     */
    @PutMapping("/open/crawljob")
    public String openUpdate(@RequestBody Log log) {
        ReturnT<Boolean> returnT;
        try {
            Log savedJob = logService.findByJobId(log.getJobId());
            savedJob.setItemsCount(log.getItemsCount());
            savedJob.setPagesCount(log.getPagesCount());
            savedJob.setFilesCount(log.getFilesCount());
            savedJob.setDownloadBytes(log.getDownloadBytes());
            savedJob.setUpdateTime(log.getUpdateTime());
            savedJob.setStartTime(log.getStartTime());
            savedJob.setTime(log.getTime());
            savedJob.setStatus(log.getStatus());
            if (log.getResult() != null) {
                savedJob.setResult(log.getResult());
            }
            if (log.getFinishTime() != null) {
                savedJob.setFinishTime(log.getFinishTime());
            }
            logService.save(savedJob);
            returnT = new ReturnT<>(200, "", true);
        } catch (Exception e) {
            returnT = new ReturnT<>(500, e.getMessage(), false);
        }
        return JSON.toJSONString(returnT);
    }

}
