package org.jeecg.modules.xxl;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.seo.service.dataforseo.DataForSEOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * DataForSEO Serp查询及同步任务，{@link DataForSEOService}
 *
 * @author wfansh
 */
@Slf4j
@Component
public class DataForSEOJob {

    @Autowired private DataForSEOService dataForSEOService;

    @XxlJob("runLongTailKeywordsSerpTasksHandler")
    public ReturnT<String> runLongTailKeywordsSerpTasksHandler(String param) {
        log.info("执行长尾词Serp查询..., param = {}", param);
        dataForSEOService.runKeywordsSerpTasks(
                this.parseSiteCodes(param),
                AdwebConstant.KEYWORD_TYPE_LONG_TAIL,
                Integer.MAX_VALUE);
        log.info("执行长尾词Serp查询结束");

        return ReturnT.SUCCESS;
    }

    @XxlJob("runAppointKeywordsSerpTasksHandler")
    public ReturnT<String> runAppointKeywordsSerpTasksHandler(String param) {
        log.info("执行指定词Serp查询..., param = {}", param);
        dataForSEOService.runKeywordsSerpTasks(
                this.parseSiteCodes(param), AdwebConstant.KEYWORD_TYPE_APPOINT, Integer.MAX_VALUE);
        log.info("执行指定词Serp查询结束");

        return ReturnT.SUCCESS;
    }

    @XxlJob("syncKeywordsSerpResultsHandler")
    public ReturnT<String> syncKeywordsSerpResultsHandler(String param) {
        log.info("同步关键词Serp查询结果...");
        dataForSEOService.syncKeywordsSerpResults();
        log.info("同步关键词Serp查询结果结束");

        return ReturnT.SUCCESS;
    }

    private List<String> parseSiteCodes(String param) {
        return Objects.nonNull(param)
                ? Arrays.stream(param.split(",")).map(siteCode -> siteCode.trim()).toList()
                : Collections.EMPTY_LIST;
    }
}
