package com.ruoyi.novel.config;

import com.ruoyi.novel.domain.RoyaltySummary;
import com.ruoyi.novel.mapper.RoyaltySummaryMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

// 定时同步PHP数据任务
@Component
public class PhpDataSyncTask {

    @Autowired
    private RoyaltySummaryMapper royaltySummaryMapper;

    @Value("${php.data.url}")
    private String phpDataUrl;

    // 每天凌晨2点执行
    @Scheduled(cron = "0 0 2 * * ?")
    public void syncRoyaltyData() {
        RestTemplate restTemplate = new RestTemplate();
        RoyaltySummary[] summaries = restTemplate.getForObject(
                phpDataUrl + "/royalty/summary",
                RoyaltySummary[].class
        );

        if (summaries != null) {
            Arrays.stream(summaries).forEach(royaltySummaryMapper::insertOrUpdate);
        }
    }
}