package com.ruoyi.zhushi.job;

import com.ruoyi.zhushi.entity.ProductRanking;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@Component
public class ProductRankingJob {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Scheduled(cron = "0 20 10 * * ?") // 每天凌晨执行一次
    public void exportDataToFile() {
        List<ProductRanking> data = jdbcTemplate.query("SELECT * FROM productranking", (rs, rowNum) -> {
            ProductRanking product = new ProductRanking();
            product.setId(rs.getString("id"));
            product.setRank(rs.getString("rank"));
            product.setName(rs.getString("name"));
            product.setPrice(rs.getString("price"));
            product.setImg(rs.getString("img"));
            product.setBrand(rs.getString("brand"));
            product.setComments(rs.getString("comments"));
            product.setIntegral(rs.getString("integral"));
            product.setShop(rs.getString("shop"));
            product.setDesc1(rs.getString("desc1"));
            product.setDesc2(rs.getString("desc2"));
            product.setDesc3(rs.getString("desc3"));
            product.setUrl(rs.getString("url"));
            product.setWebsite(rs.getString("website"));
            product.setCreatedate(rs.getString("createdate"));
            product.setCreatetime(rs.getString("createtime"));
            product.setSn(rs.getString("sn"));
            product.setCategory(rs.getString("category"));
            return product;
        });

        try (FileWriter writer = new FileWriter("data.sql")) {
            for (ProductRanking product : data) {
                writer.write("INSERT INTO productranking (id, `rank`, name, price, img, brand, comments, integral, shop, desc1, desc2, desc3, url, website, createdate, createtime, sn, category) VALUES ('" +
                        product.getId() + "', '" + product.getRank() + "', '" + product.getName() + "', '" + product.getPrice() + "', '" + product.getImg() + "', '" + product.getBrand() + "', '" + product.getComments() + "', '" + product.getIntegral() + "', '" + product.getShop() + "', '" + product.getDesc1() + "', '" + product.getDesc2() + "', '" + product.getDesc3() + "', '" + product.getUrl() + "', '" + product.getWebsite() + "', '" + product.getCreatedate() + "', '" + product.getCreatetime() + "', '" + product.getSn() + "', '" + product.getCategory() + "');\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
