package top.imwork.window.silos.service.book.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import jakarta.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import top.imwork.commons.core.constants.Constants;
import top.imwork.commons.core.utils.StringUtils;
import top.imwork.window.silos.dao.ContentsDao;
import top.imwork.window.silos.dao.InfoDao;
import top.imwork.window.silos.entity.Contents;
import top.imwork.window.silos.entity.Info;
import top.imwork.window.silos.pojo.bo.InfoBO;
import top.imwork.window.silos.pojo.bo.InfoResultBO;
import top.imwork.window.silos.pojo.dto.InfoDTO;
import top.imwork.window.silos.pojo.dto.InfoListDTO;
import top.imwork.window.silos.processor.ChapterContent;
import top.imwork.window.silos.processor.ChapterSplitter;
import top.imwork.window.silos.processor.ChapterSplitterProcessor;
import top.imwork.window.silos.service.book.IInfoService;
import top.imwork.window.silos.convert.InfoConvert;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("infoService")
public class InfoServiceImpl extends ServiceImpl<InfoDao, Info> implements IInfoService {
    @Resource
    private InfoDao infoDao;

    @Resource
    private ContentsDao contentsDao;

    /**
     * 根据id获取信息
     *
     * @param id 用户id
     * @return InfoBO 响应信息
     */
    @Override
    public InfoBO info(Long id) {
        Info info = infoDao.info(id);
        return InfoConvert.infoDoToBo(info);
    }

    /**
     * 新增/更新信息
     *
     * @param infoDTO 信息
     * @return infoBO 更新后信息
     */
    @Override
    public InfoBO save(InfoDTO infoDTO) {
        Info info = InfoConvert.infoDtoToDo(infoDTO);
        if (ObjectUtils.isEmpty(info.getId())) {
            infoDao.insert(info);
        } else {
            infoDao.updateById(info);
        }
        if (StringUtils.isNotEmpty(infoDTO.getFilePaths())) {
            try {
                runWithVirtualThreads(info, infoDTO.getFilePaths());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return InfoConvert.infoDoToBo(info);
    }

    private void runWithVirtualThreads(Info info, String filePath) throws Exception {
        if (!ChapterSplitter.checkVirtualThreadSupport()) {
            System.out.println("当前Java版本不支持虚拟线程！");
            System.out.println("请使用Java 21或更高版本，并添加--enable-preview参数");
            return;
        }

        try {
            // 读取文件内容
            String content = Files.readString(Path.of(filePath));

            // 使用虚拟线程池处理章节拆分
            List<ChapterContent> chapters = ChapterSplitterProcessor.splitChaptersWithVirtualThreads(content);

            // 输出结果
            System.out.println("总共拆分成 " + chapters.size() + " 个章节");

            // 保存章节到文件
            //ChapterSplitterProcessor.saveChaptersToFiles(chapters);
            this.saveContents(chapters, info);
        } catch (IOException e) {
            System.err.println("读取文件出错: " + e.getMessage());
        }
    }

    private void saveContents(List<ChapterContent> chapters, Info info) {
        List<Contents> contentsList = new ArrayList<>();
        for (ChapterContent chapterContent : chapters) {
            Contents contents = new Contents();
            contents.setBookInfoId(info.getIsbn());
            contents.setDelFlag(Constants.DEL_FLAG_N);
            contents.setCreateTime(new Date());
            contents.setUpdateTime(new Date());
            contents.setContentType("text");
            contents.setContentText(chapterContent.getContent());
            contents.setChapterNumber(String.valueOf(chapterContent.getNumber()));
            contents.setChapterTitle(chapterContent.getTitle());
            contents.setVersion("v1.0");
            contents.setIsPublic(1);
            contents.setWordCount(chapterContent.getContent().length());
            contentsList.add(contents);
        }
        contentsDao.insert(contentsList);
    }

    /**
     * 根据id删除信息
     *
     * @param id id
     * @return true/false 是否删除成功
     */
    @Override
    public Boolean delete(Long id) {
        return infoDao.deleteById(id) == 1 ? Boolean.TRUE : Boolean.FALSE;
    }

    @Override
    public Boolean deleteByIds(String[] ids) {
        return infoDao.deleteByIds(ids) > 0 ? Boolean.TRUE : Boolean.FALSE;
    }

    @Override
    public InfoResultBO queryPage(InfoListDTO infoListDTO) {
        QueryWrapper<Info> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(infoListDTO.getInfoName())) {
            queryWrapper.like("title", infoListDTO.getInfoName());
        }

        if (!StringUtils.isEmpty(infoListDTO.getCategoryCode())) {
            queryWrapper.like("category_code", infoListDTO.getCategoryCode());
        }

        if (!StringUtils.isEmpty(infoListDTO.getCreateBeginTime())) {
            queryWrapper.apply("create_time >= '" + infoListDTO.getCreateBeginTime() + "'");
        }

        if (!StringUtils.isEmpty(infoListDTO.getCreateEndTime())) {
            queryWrapper.apply("create_time <= '" + infoListDTO.getCreateEndTime() + "'");
        }

        if (!StringUtils.isEmpty(infoListDTO.getUpdateBeginTime())) {
            queryWrapper.apply("update_time >= '" + infoListDTO.getUpdateBeginTime() + "'");
        }

        if (!StringUtils.isEmpty(infoListDTO.getUpdateEndTime())) {
            queryWrapper.apply("update_time <= '" + infoListDTO.getUpdateEndTime() + "'");
        }
        PageHelper.startPage(infoListDTO.getPageNo(), infoListDTO.getPageRows());
        List<Info> list = infoDao.selectList(queryWrapper);
        PageInfo<Info> pageInfo = new PageInfo<>(list);
        InfoResultBO resultBO = new InfoResultBO();
        resultBO.setPageNo(infoListDTO.getPageNo());
        resultBO.setPageRows(infoListDTO.getPageRows());
        resultBO.setPageCount(pageInfo.getPages());
        resultBO.setTotalRows((int) pageInfo.getTotal());
        resultBO.setDataList(InfoConvert.infoListToInfoBOList(list));
        resultBO.setParams(infoListDTO);

        return resultBO;
    }
}