package com.lanyuanxiaoyao.bookstore;

import cn.hutool.core.lang.Tuple;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.blinkfox.fenix.EnableFenix;
import com.lanyuanxiaoyao.bookstore.entity.Chapter;
import com.lanyuanxiaoyao.bookstore.entity.Line;
import com.lanyuanxiaoyao.bookstore.service.BookService;
import com.lanyuanxiaoyao.bookstore.service.ChapterService;
import jakarta.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.stream.Collectors;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.transaction.annotation.Transactional;

/**
 * 启动类
 *
 * @author lanyuanxiaoyao
 * @version 20250922
 */
@SpringBootApplication
@EnableJpaAuditing
@EnableFenix
@EnableConfigurationProperties
public class BookStoreApplication {
  public static void main(String[] args) {
    SpringApplication.run(BookStoreApplication.class, args);
  }

  @Resource
  private BookService bookService;
  @Resource
  private ChapterService chapterService;

  @Transactional(rollbackFor = Throwable.class)
  // @EventListener(ApplicationReadyEvent.class)
  public void loadOldData() throws FileNotFoundException {
    var reader = CsvUtil.getReader(new FileReader("C:\\Users\\lanyuanxiaoyao\\Result_6.csv"));
    var rows = reader.stream()
        .map(row -> new Row(Long.parseLong(row.get(0)), row.get(1), Long.parseLong(row.get(2)), row.get(3)))
        .toList();
    var book = bookService.detailOrThrow(3602572744994816L);
    rows.stream()
        .map(row -> new Tuple(row.chapterSequence(), row.chapterTitle()))
        .distinct()
        .forEach(tuple -> {
          var chapter = new Chapter();
          chapter.setSequence(NumberUtil.toDouble(tuple.get(0)));
          chapter.setName(tuple.get(1));
          chapter.setBook(book);

          var lines = rows.stream()
              .filter(row -> ObjectUtil.equals(row.chapterSequence(), tuple.get(0)) && ObjectUtil.equals(row.chapterTitle(), tuple.get(1)))
              .map(row -> {
                var line = new Line();
                line.setSequence(NumberUtil.toDouble(row.lineSequence()));
                line.setText(row.lineText());
                line.setChapter(chapter);
                return line;
              })
              .collect(Collectors.toSet());
          chapter.setContent(lines);
          chapterService.save(chapter);
        });
  }

  public record Row(long chapterSequence, String chapterTitle, long lineSequence, String lineText) {
  }
}
