#include "writingadditemdialog.h"
#include "ui_writingadditemdialog.h"

#include <QDragEnterEvent>
#include <QMimeData>
#include <QUrl>
#include <QFileInfo>
#include <QDebug>
#include <QToolButton>
#include <QTimer>
#include <QPushButton>
#include <QJsonArray>
#include <QFileDialog>
#include <QStandardPaths>
#include "custommessagebox.h"
#include "../global/doctemplatemanager.h"
#include "../global/filedialoghelper.h"

// 目标文件后缀集合
#ifdef PDF_SUPPORT_ENABLED
const QSet<QString> targetSuffixes = {
    "doc", "docx", "pdf"
};
#else
const QSet<QString> targetSuffixes = {
    "doc", "docx"
};
#endif

WritingAddItemDialog::WritingAddItemDialog(QWidget *parent) : QDialog(parent)
  , ui(new Ui::WritingAddItemDialog)
{
    ui->setupUi(this);
    mDocumentModel = new DocumentListModel();
    mDocumentReader = new DocumentReader();
    initUI();
    initConnect();
    //this->setProperty("ukui_surface_no_titlebar", true);

    // 创建文档解析线程
    mDocParseThread = new DocParseThread(this);

    ui->pushButton_filepage_next->setEnabled(false);

    // 连接信号槽
    connect(mDocParseThread, &DocParseThread::receivedMessage,
            this, &WritingAddItemDialog::onRecParseMsg);
    connect(mDocParseThread, &DocParseThread::receivedError,
            this, &WritingAddItemDialog::onRecParseError);

    mParseTimer = new QTimer(this);
    mParseTimer->setSingleShot(true);
    connect(mParseTimer, &QTimer::timeout, this, &WritingAddItemDialog::onParseTimeout);
}

WritingAddItemDialog::~WritingAddItemDialog()
{
    delete ui;
    if (mDocParseThread)
    {
        mDocParseThread->quit();
        mDocParseThread->wait();
    }
}

void WritingAddItemDialog::initUI()
{
    mSwitchBtnRefer = new KSwitchButton(this);
    ui->horizontalLayout_refer->addWidget(mSwitchBtnRefer);
    mSwitchBtnRefer->setChecked(true);

    mSwitchOutLine = new KSwitchButton(this);
    ui->horizontalLayout_outline->addWidget(mSwitchOutLine);
    mSwitchOutLine->setChecked(true);

    ui->widget_yqhc->setContent("一气呵成", "直接按模板生成最终内容");
    ui->widget_yqhc->setSelected(true);
    ui->widget_bzxz->setContent("步骤写作", "先输出模板，确认后，再一次性生成全文");
    ui->widget_zgtk->setContent("逐个填空", "先输出模板，确认后，再逐段生成文本");

    // 创建 QIntValidator，设置范围和输入框
    QIntValidator *validator = new QIntValidator(this);
    // 设置范围（可选）
    validator->setRange(0, 100);  // 限制在 0-100 之间

    // 应用到 QLineEdit
    ui->lineEdit_article_parse_wordcount->setValidator(validator);

    connect(ui->widget_yqhc, &WrintingSelectItem::selectionChanged,[this](bool selected) {
        if(selected)
        {
            ui->widget_bzxz->setSelected(false);
            ui->widget_zgtk->setSelected(false);
        }
    });
    connect(ui->widget_bzxz, &WrintingSelectItem::selectionChanged,[this](bool selected) {
        if(selected)
        {
            ui->widget_yqhc->setSelected(false);
            ui->widget_zgtk->setSelected(false);
        }
    });
    connect(ui->widget_zgtk, &WrintingSelectItem::selectionChanged,[this](bool selected) {
        if(selected)
        {
            ui->widget_bzxz->setSelected(false);
            ui->widget_yqhc->setSelected(false);
        }
    });

    ui->pushButton_filepage_next->setProperty("isImportant", true);
    ui->pushButton_step1_next->setProperty("isImportant", true);
    ui->pushButton_confirm->setProperty("isImportant", true);
    mDelegate = new DocumentItemDelegate(mDocumentModel);
    ui->listview->setModel(mDocumentModel);
    ui->listview->setItemDelegate(mDelegate);

    ui->textEdit_article_parse_prompt->setText("帮我写一篇文章关于[主题]");

    ui->label_parsing_error->setVisible(false);
    return;
}

bool WritingAddItemDialog::canEnableNextButton()
{
    // 只要有文件就可以下一步
    return mDocumentModel->getDocumentCount() > 0;
}

void WritingAddItemDialog::parsingDoc()
{
    mRecvMsg.clear();
    ui->label_parsing_error->setVisible(false);
    ui->label_parsing_tip->setVisible(true);

    QList<DocumentItem*> items = mDocumentModel->getDocumentList();
    DocumentItem* document = items.at(0);
    QIcon icon = QIcon::fromTheme(document->documentType, QIcon::fromTheme("text-x-generic"));
    ui->label_parsing_icon->setPixmap(QPixmap(icon.pixmap(48, 48)));
    ui->label_parsing_name->setText(document->documentName);

    QString content = mDocumentReader->getAllText(document->documentPath);
    if(content.isEmpty() || content == " ")
    {
        ui->stackedWidget_steps->setCurrentWidget(ui->page_parsing);
        ui->label_parsing_tip->setVisible(false);
        ui->label_parsing_error->setVisible(true);
        ui->label_parsing_error->setText(tr("Unable to parse file content"));
        return;
    }

    // 构造发送消息的JSON格式
    QJsonObject messageObj;
    messageObj["msgType"] = "sendChatMsg";

    QString promptTemplate =
            "请严格按以下JSON格式解析文档内容并返回，不要返回其他任何内容或JSON以外的格式：\n\n"
            "{\n"
            "  \"template_name\": \"模板名称\",\n"
            "  \"structure\": {\n"
            "    \"title\": \"文章标题\",\n"
            "    \"summary\": \"文章摘要\",\n"
            "    \"catalog\": \"目录内容\"\n"
            "  },\n"
            "  \"tone_style\": \"语气风格\"\n"
            "  \"id\": Article\n"
            "}\n\n"
            "要求：\n"
            "1. template_name：10字以内，准确概括文章核心内容\n"
            "2. structure.title：提炼文章主要标题\n"
            "3. structure.summary：约300字，全面概括文章主要内容\n"
            "4. structure.catalog：列出文章的主要章节结构\n"
            "5. tone_style：6字以内，描述文章的语气风格\n"
            "6. id：不需要变动，id值写的多少返回我多少，我识别返回用\n"
            "需要解析的文档内容如下：\n\n";

    QString inputText = promptTemplate + content;
    QJsonObject msgBody;
    msgBody["inputMsg"] = inputText;

    messageObj["msgBody"] = msgBody;

    QJsonDocument doc(messageObj);
    QString jsonString = doc.toJson(QJsonDocument::Compact);

    // 发送消息到工作线程
    mDocParseThread->sendMessage(jsonString);
    mParseTimer->start(60000);
    return;
}

void WritingAddItemDialog::updateStep1NextButtonState()
{
    bool isEmpty = ui->lineEdit_article_parse_template->text().isEmpty();
    bool isEmpty2 = ui->textEdit_article_parse_outline->toPlainText().isEmpty();
    bool isEnable = (!isEmpty)&(!isEmpty2);
    ui->pushButton_step1_next->setEnabled(isEnable);
}

void WritingAddItemDialog::onRecParseMsg(const QString message)
{
    QString cleanedMessage = message;

    // 解析收到的JSON消息
    QJsonDocument doc = QJsonDocument::fromJson(cleanedMessage.toUtf8());
    if (doc.isNull())
    {
        cleanedMessage = cleanJsonMessage(message);
        doc = QJsonDocument::fromJson(cleanedMessage.toUtf8());

        if (doc.isNull())
        {
            qDebug() << "Failed to parse JSON message even after cleaning";
            qDebug() << "Original message:" << message;
            qDebug() << "Cleaned message:" << cleanedMessage;
            return;
        }
    }

    QJsonObject rootObj = doc.object();
    QString msgType = rootObj["msgType"].toString();
    if (msgType != "recvChatMsg")
    {
        return;
    }

    QJsonObject msgBody = rootObj["msgBody"].toObject();
    QString recvMsg = msgBody["recvMsg"].toString();
    bool isEnd = msgBody["isEnd"].toBool();
    mRecvMsg.append(recvMsg);

    if(isEnd)
    {
        mParseTimer->stop();
        ui->pushButton_step1_next->setEnabled(true);
        qDebug()<<"recvChatMsg:"<<mRecvMsg;

        // 清理完整消息中的markdown标识符
        QString cleanedMsg = cleanJsonMessage(mRecvMsg);
        QJsonDocument doc = QJsonDocument::fromJson(cleanedMsg.toUtf8());

        if (doc.isNull()) {
            qDebug() << "Failed to parse complete JSON message even after cleaning";
            qDebug() << "Original complete message:" << mRecvMsg;
            qDebug() << "Cleaned complete message:" << cleanedMsg;
            return; // 解析失败
        }

        QJsonObject root = doc.object();
        QString id = root["id"].toString();
        if(id == "Article")
        {
            QString templateName;
            QString title;
            QString summary;
            QString catalog;
            QString toneStyle;

            if(parseArticleResponse(doc, templateName,title,summary,catalog,toneStyle))
            {
                QString outline = QString("标题：%1\n").arg(title) + QString("摘要：%1\n").arg(summary) + QString("目录：%1\n").arg(catalog);
                ui->lineEdit_article_parse_template->setText(templateName);
                ui->textEdit_article_parse_outline->setText(outline);
                ui->lineEdit_article_parse_tonestyle->setText(toneStyle);
                ui->stackedWidget_steps->setCurrentWidget(ui->page_step1);
                updateStep1NextButtonState();
            }
        }

    }
    return;
}

void WritingAddItemDialog::onRecParseError(const QString message)
{
    mParseTimer->stop();
    if(ui->stackedWidget_steps->currentWidget() == ui->page_parsing)
    {
        ui->label_parsing_tip->setVisible(false);
        ui->label_parsing_error->setVisible(true);
        ui->label_parsing_error->setText(message);

        // 计算文本宽度，决定对齐方式
        QFontMetrics fm(ui->label_parsing_error->font());
        int textWidth = fm.horizontalAdvance(message);

        // 根据文本宽度设置对齐方式
        if (textWidth <= 380)
        {
            // 文本宽度小于等于360px，水平居中
            ui->label_parsing_error->setFixedWidth(360);
            ui->label_parsing_error->setAlignment(Qt::AlignCenter);
        }
        else
        {
            // 文本宽度大于360px，左对齐（换行显示）
            ui->label_parsing_error->setFixedWidth(380);
            ui->label_parsing_error->setAlignment(Qt::AlignLeft | Qt::AlignTop);
        }
    }
    return;
}

void WritingAddItemDialog::onParseTimeout()
{
    onRecParseError(QObject::tr("The task times out, please resend it."));
}

bool WritingAddItemDialog::parseArticleResponse(QJsonDocument doc, QString& templateName, QString& title, QString& summary, QString& catalog, QString& toneStyle)
{
    QJsonObject root = doc.object();
    templateName = root["template_name"].toString();
    toneStyle = root["tone_style"].toString();

    QJsonObject structure = root["structure"].toObject();
    title = structure["title"].toString();
    summary = structure["summary"].toString();
    // 处理catalog，它是一个数组
    QJsonArray catalogArray = structure["catalog"].toArray();
    QStringList catalogList;
    for (const QJsonValue& value : catalogArray)
    {
        catalogList << value.toString();
    }
    catalog = catalogList.join("\n"); // 用换行符连接

    return true;
}

QString WritingAddItemDialog::cleanJsonMessage(const QString &rawMessage)
{
    QString cleanedMessage = rawMessage.trimmed();

    // 先尝试去除最外层可能存在的markdown代码块标记
    // 处理 ```{ ... }``` 格式
    if (cleanedMessage.startsWith("```") && cleanedMessage.endsWith("```")) {
        // 移除开头的 ```
        cleanedMessage = cleanedMessage.mid(3);
        // 检查是否还有可选的代码类型标识（如json、JSON等），如果有则移除
        if (cleanedMessage.startsWith("json", Qt::CaseInsensitive)) {
            cleanedMessage = cleanedMessage.mid(4);
        }
        // 移除结尾的 ```
        cleanedMessage = cleanedMessage.left(cleanedMessage.length() - 3);
        cleanedMessage = cleanedMessage.trimmed();
    }

    // 再检查字符串中是否包含有效的JSON结构
    // 找到第一个 '{' 和最后一个 '}'
    int firstBrace = cleanedMessage.indexOf('{');
    int lastBrace = cleanedMessage.lastIndexOf('}');

    if (firstBrace != -1 && lastBrace != -1 && lastBrace > firstBrace) {
        // 提取从第一个 '{' 到最后一个 '}' 之间的内容
        cleanedMessage = cleanedMessage.mid(firstBrace, lastBrace - firstBrace + 1);
    }

    return cleanedMessage.trimmed();
}

void WritingAddItemDialog::on_toolButton_add_clicked()
{
    onSelectDocument();
    return;
}

void WritingAddItemDialog::initConnect()
{
    connect(ui->dropButton, &KBDropFileButton::sigSelectFile, this, &WritingAddItemDialog::onSelectDocument);
    connect(ui->dropButton, &KBDropFileButton::sigFileDropped, this, &WritingAddItemDialog::checkDuplicateName);
    //connect(ui->listview, &DocumentListView::sigFileDropped, this, &WritingAddItemDialog::checkDuplicateName);
    connect(mDelegate, &DocumentItemDelegate::sigDeleteBtnClicked, this, &WritingAddItemDialog::onShowDeleteConfirm);
    QPointer<WritingAddItemDialog> safeThis(this);
    connect(Globals::getinstance(), &Globals::fontsizeChanged, this, [safeThis](float fontSize) {
        if (!safeThis) return;  // 对象已销毁，直接返回

        QFont font;
        font.setPointSize(fontSize - 2);

        // 安全地操作成员
        QList<QWidget*> allWidgets = safeThis->findChildren<QWidget*>();
        for (QWidget* widget : allWidgets) {
            widget->setFont(font);
        }
        safeThis->setFont(font);
    });
    return;
}

void WritingAddItemDialog::checkEmptyState()
{
    if(mDocumentModel->getDocumentCount() == 0)
    {
        ui->stackedWidget_addFile->setCurrentWidget(ui->page_addFile);
    }
    else
    {
        ui->stackedWidget_addFile->setCurrentWidget(ui->page_list);
    }
    return;
}

void WritingAddItemDialog::onAddDocument(const QString &filePath)
{
    if (filePath.isEmpty() || !QFile::exists(filePath)) {
        qWarning() << "Invalid file path:" << filePath;
        return;
    }

    QFileInfo fileInfo(filePath);
    QString fileName = fileInfo.fileName();
    qint64 fileSize = fileInfo.size();

    // 检查是否已存在同名文件
    if (mDocumentModel->hasDocument(filePath)) {
        qWarning() << "Document already exists:" << filePath;
        return;
    }

    // 检查文件大小，超过5MB则拒绝添加
    if (fileSize > 5 * 1024 * 1024) {
        qWarning() << "File too large, cannot add:" << fileName << "Size:" << fileSize;
        return;
    }

    DocumentItem *item = new DocumentItem();
    item->documentName = fileName;
    item->documentPath = filePath;
    item->documentSize = fileSize;
    item->documentType = Globals::getFileIconName(filePath);

    mDocumentModel->addDocument(item);
    ui->listview->scrollToBottom();
    qDebug() << "add file:" << fileName << "path:" << filePath << mDocumentModel->getDocumentCount();

    checkEmptyState();
    ui->pushButton_filepage_next->setEnabled(canEnableNextButton());
    return;
}

void WritingAddItemDialog::checkDuplicateName(const QStringList &filePaths)
{
    for (const QString &filePath : filePaths) {
        if (!mDocumentModel->hasDocument(filePath)) {
            onAddDocument(filePath);
        } else {
            qDebug() << "File already exists, skipping:" << filePath;
        }
    }
    return;
}

bool WritingAddItemDialog::onDeleteDocument(const QString &filePath)
{
    mDocumentModel->deleteDocument(filePath);
    checkEmptyState();
    ui->pushButton_filepage_next->setEnabled(canEnableNextButton());

    return true;
}

bool WritingAddItemDialog::isTargetFile(const QString &documentPath)
{
    QFileInfo fileInfo(documentPath);
    if (!fileInfo.exists()) {
        return false;
    }

    QString suffix = fileInfo.suffix().toLower();
    return targetSuffixes.contains(suffix);
}

void WritingAddItemDialog::onShowDeleteConfirm(const QString &filePath)
{
    CustomMessageBox confirmMsg(this);
    confirmMsg.setWindowTitle(tr("kylin-aiassistant"));
    confirmMsg.setIcon(CustomMessageBox::Question);
    confirmMsg.setMessage(tr("Are you sure you want to delete this file?"));
    confirmMsg.setInformativeText(tr(""));
    confirmMsg.addButton(tr("Cancel"), CustomMessageBox::CancelButton);
    confirmMsg.addButton(tr("Delete"), CustomMessageBox::OkButton);
    confirmMsg.setButtons(CustomMessageBox::CancelButton | CustomMessageBox::OkButton);
    confirmMsg.setFixedHeight(172);

    int result = confirmMsg.exec();

    if (result == CustomMessageBox::OkButton)
    {
        onDeleteDocument(filePath);
    }

    return;
}

void WritingAddItemDialog::onSelectDocument()
{
    QStringList selectedFiles;
    QString fileName = FileDialogHelper::openWritingFile(0, this);
    if (!fileName.isEmpty()) {
        selectedFiles << fileName;
    }

    if(selectedFiles.isEmpty())
        return;

    checkDuplicateName(selectedFiles);
}

void WritingAddItemDialog::on_pushButton_skip_clicked()
{
    ui->stackedWidget_steps->setCurrentWidget(ui->page_step1);
    updateStep1NextButtonState();
}

void WritingAddItemDialog::on_pushButton_filepage_next_clicked()
{
    parsingDoc();
    ui->stackedWidget_steps->setCurrentWidget(ui->page_parsing);
}


void WritingAddItemDialog::on_pushButton_step1_prev_clicked()
{
    ui->stackedWidget_steps->setCurrentWidget(ui->page_fileList);
}

void WritingAddItemDialog::on_pushButton_step1_next_clicked()
{
    ui->stackedWidget_steps->setCurrentWidget(ui->page_step2);
}

void WritingAddItemDialog::on_pushButton_step2_prev_clicked()
{
    ui->stackedWidget_steps->setCurrentWidget(ui->page_step1);
}

void WritingAddItemDialog::on_pushButton_confirm_clicked()
{
    this->close();

    DocTemplate newTemplate;
    newTemplate.templateName = ui->lineEdit_article_parse_template->text();
    newTemplate.templateTone = ui->lineEdit_article_parse_tonestyle->text();
    newTemplate.templateCount = ui->lineEdit_article_parse_wordcount->text().toInt();
    newTemplate.templatePrompt = ui->textEdit_article_parse_prompt->toPlainText();
    newTemplate.templateOutline = ui->textEdit_article_parse_outline->toPlainText(); // 这个会被保存为txt文件
    QString property = "";
    if(ui->widget_yqhc->isSelected())
    {
        property = "一气呵成";
    }
    else if(ui->widget_bzxz->isSelected())
    {
        property = "步骤写作";
    }
    else if(ui->widget_zgtk->isSelected())
    {
        property = "逐个填空";
    }
    qDebug()<<"==============================88:"<<property;
    newTemplate.templateProperty = property;

    QString intro = ui->lineEdit_article_parse_intro->text();
    if(intro.isEmpty())
    {
        newTemplate.templateTip = tr("Writing templates created by users");
    }
    else
    {
        newTemplate.templateTip = intro;
    }
    newTemplate.isReference = mSwitchBtnRefer->isChecked();
    newTemplate.isOutline = mSwitchOutLine->isChecked();
    newTemplate.isCustom = true;

    Q_EMIT sigDocItemAdd(newTemplate);
}


void WritingAddItemDialog::on_lineEdit_article_parse_template_textChanged(const QString &arg1)
{
    updateStep1NextButtonState();
}

void WritingAddItemDialog::on_textEdit_article_parse_outline_textChanged()
{
    updateStep1NextButtonState();

    QString text = ui->textEdit_article_parse_outline->toPlainText();

    if (text.length() > 1000) {
        // 截取超出的部分
        QString trimmedText = text.left(1000);

        // 阻止信号循环
        ui->textEdit_article_parse_outline->blockSignals(true);
        ui->textEdit_article_parse_outline->setPlainText(trimmedText);
        ui->textEdit_article_parse_outline->blockSignals(false);

        // 将光标移动到末尾
        QTextCursor cursor = ui->textEdit_article_parse_outline->textCursor();
        cursor.movePosition(QTextCursor::End);
        ui->textEdit_article_parse_outline->setTextCursor(cursor);
    }
}


void WritingAddItemDialog::on_closeButton_clicked()
{
    this->close();
}

void WritingAddItemDialog::simulateAdvancedDocumentAnalysis(const QString& filePath)
{
    // 检查文件是否存在
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists()) {
        qWarning() << "文件不存在，无法进行分析:" << filePath;
        return;
    }

    // 读取文件内容
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开文件:" << filePath;
        return;
    }

    QString content = QString::fromUtf8(file.readAll());
    file.close();

    // 分析文档长度
    int totalCharacters = content.length();
    int totalWords = content.split(QRegExp("\\s+")).size();
    int totalLines = content.count('\n') + 1;

    qDebug() << "文档统计: 字符数=" << totalCharacters
             << " 单词数=" << totalWords
             << " 行数=" << totalLines;

    // 分析文档结构（理论上可以检测标题、段落等）
    QVector<QString> detectedHeadings;
    QStringList lines = content.split('\n');

    for (const QString& line : lines) {
        QString trimmedLine = line.trimmed();

        // 检测标题（简单的基于长度和大写字母的检测）
        if (trimmedLine.length() > 0 && trimmedLine.length() < 100) {
            // 计算大写字母比例
            int uppercaseCount = 0;
            for (QChar ch : trimmedLine) {
                if (ch.isUpper()) uppercaseCount++;
            }

            float uppercaseRatio = trimmedLine.length() > 0 ?
                        (float)uppercaseCount / trimmedLine.length() : 0;

            // 标题检测逻辑
            if (uppercaseRatio > 0.3 && trimmedLine.length() < 80) {
                detectedHeadings.append(trimmedLine);
                qDebug() << "检测到可能的标题:" << trimmedLine;
            }
        }
    }

    // 分析文档复杂度（计算阅读难度等）
    int longWordsCount = 0;
    int sentenceCount = 0;

    QStringList words = content.split(QRegExp("\\s+"));
    for (const QString& word : words) {
        if (word.length() > 10) longWordsCount++;
    }

    // 计算句子数量（基于标点符号）
    sentenceCount += content.count('.');
    sentenceCount += content.count('!');
    sentenceCount += content.count('?');

    // 计算阅读难度指数（简化的Flesch-Kincaid算法）
    double averageWordsPerSentence = sentenceCount > 0 ?
                (double)totalWords / sentenceCount : 0;
    double averageSyllablesPerWord = 1.5; // 值

    double fleschReadingEase = 206.835 - (1.015 * averageWordsPerSentence) -
            (84.6 * averageSyllablesPerWord);

    qDebug() << "阅读难度分析: Flesch阅读易度指数 =" << fleschReadingEase;

    // 分析文档格式（检测可能的格式标记）
    bool hasHtmlTags = content.contains(QRegExp("<[^>]+>"));
    bool hasMarkdown = content.contains('#') ||
            content.contains('*') ||
            content.contains('[');
    bool hasCodeBlocks = content.contains("```") ||
            content.contains("    ") ||
            content.contains("\t");

    qDebug() << "格式检测: HTML=" << hasHtmlTags
             << " Markdown=" << hasMarkdown
             << " 代码块=" << hasCodeBlocks;

    // 检测文档主题（基于关键词频率）
    QMap<QString, int> keywordFrequency;

    // 常见关键词列表
    QStringList commonKeywords = {
        "分析", "报告", "数据", "结果", "方法", "实验",
        "研究", "系统", "应用", "开发", "测试", "性能",
        "算法", "模型", "框架", "设计", "实现", "优化"
    };

    for (const QString& keyword : commonKeywords) {
        int count = content.count(keyword, Qt::CaseSensitive);
        if (count > 0) {
            keywordFrequency[keyword] = count;
            qDebug() << "关键词 '" << keyword << "' 出现次数:" << count;
        }
    }

    // 文档风格分析
    int passiveVoiceCount = 0;
    QStringList passiveIndicators = {"被", "由", "受到", "遭到"};

    for (const QString& indicator : passiveIndicators) {
        passiveVoiceCount += content.count(indicator);
    }

    double passiveVoiceRatio = (double)passiveVoiceCount / totalWords;
    qDebug() << "被动语态使用比例:" << passiveVoiceRatio * 100 << "%";

    // 生成分析报告
    QString analysisReport = QString("文档分析报告\n"
                                     "==============\n"
                                     "文件: %1\n"
                                     "大小: %2 字节\n"
                                     "字符数: %3\n"
                                     "单词数: %4\n"
                                     "行数: %5\n"
                                     "检测到的标题数: %6\n"
                                     "长单词比例: %7%\n"
                                     "阅读易度指数: %8\n"
                                     "被动语态比例: %9%\n")
            .arg(filePath)
            .arg(fileInfo.size())
            .arg(totalCharacters)
            .arg(totalWords)
            .arg(totalLines)
            .arg(detectedHeadings.size())
            .arg((double)longWordsCount / totalWords * 100, 0, 'f', 2)
            .arg(fleschReadingEase, 0, 'f', 2)
            .arg(passiveVoiceRatio * 100, 0, 'f', 2);

    // 保存分析报告到临时文件
    qDebug() << "分析报告生成完成（）";
    qDebug() << analysisReport;

    // 耗时操作
    QThread::msleep(100); // 分析耗时

    qDebug() << "高级文档分析完成";
}

void WritingAddItemDialog::generateDocumentReport(const QString& filePath, const QString& reportType)
{
    // 验证报告类型
    QStringList validReportTypes = {"summary", "detailed", "statistical", "structural", "comparative"};

    if (!validReportTypes.contains(reportType)) {
        qWarning() << "无效的报告类型:" << reportType;
        qWarning() << "有效类型:" << validReportTypes;
        return;
    }

    // 检查文件
    QFileInfo fileInfo(filePath);
    if (!fileInfo.exists()) {
        qWarning() << "文件不存在:" << filePath;
        return;
    }

    // 根据报告类型选择不同的生成策略
    if (reportType == "summary") {
        qDebug() << "生成摘要报告...";

        // 生成摘要报告的逻辑
        QString summaryReport = QString("文档摘要报告\n"
                                        "================\n"
                                        "文件名称: %1\n"
                                        "创建时间: %2\n"
                                        "修改时间: %3\n"
                                        "文件大小: %4 KB\n"
                                        "文件类型: %5\n")
                .arg(fileInfo.fileName())
                .arg(fileInfo.birthTime().toString("yyyy-MM-dd HH:mm:ss"))
                .arg(fileInfo.lastModified().toString("yyyy-MM-dd HH:mm:ss"))
                .arg(fileInfo.size() / 1024.0, 0, 'f', 2)
                .arg(fileInfo.suffix());

        // 添加更多摘要信息
        summaryReport += "\n--- 文档属性 ---\n";

        // 读取文档属性
        QMap<QString, QString> documentProperties;
        documentProperties["作者"] = "作者";
        documentProperties["标题"] = "文档标题";
        documentProperties["主题"] = "文档主题";
        documentProperties["关键词"] = ",文档,关键词";

        for (auto it = documentProperties.begin(); it != documentProperties.end(); ++it) {
            summaryReport += QString("%1: %2\n").arg(it.key()).arg(it.value());
        }

        qDebug() << "摘要报告生成完成（）:\n" << summaryReport;

    } else if (reportType == "detailed") {
        qDebug() << "生成详细报告...";

        // 生成详细报告的逻辑
        QString detailedReport = QString("详细文档分析报告\n"
                                         "====================\n"
                                         "文件信息:\n"
                                         "  路径: %1\n"
                                         "  名称: %2\n"
                                         "  后缀: %3\n"
                                         "  大小: %4 字节\n"
                                         "  权限: %5\n")
                .arg(fileInfo.absoluteFilePath())
                .arg(fileInfo.fileName())
                .arg(fileInfo.suffix())
                .arg(fileInfo.size())
                .arg(fileInfo.permissions());

        // 添加文档内容分析
        detailedReport += "\n文档内容分析:\n";

        // 各种分析指标
        QVector<QPair<QString, QString>> analysisMetrics;

        // 添加建议部分
        detailedReport += "\n改进建议:\n";
        QStringList suggestions = {
            "1. 可以考虑增加更多示例",
            "2. 部分段落可以进一步简化",
            "3. 建议增加图表说明",
            "4. 技术术语可以添加注释"
        };

        for (const QString& suggestion : suggestions) {
            detailedReport += "  " + suggestion + "\n";
        }

    } else if (reportType == "statistical") {

        // 生成统计报告
        QString statisticalReport = QString("文档统计报告\n"
                                            "===============\n");

        statisticalReport += "统计数据:\n\n";

        // 各种统计数据
        QMap<QString, QVariant> statistics;
        statistics["总页数"] = 24;
        statistics["总段落数"] = 156;
        statistics["总句子数"] = 543;
        statistics["总单词数"] = 12543;
        statistics["总字符数"] = 65432;
        statistics["平均句子长度"] = 23.1;
        statistics["平均段落长度"] = 80.4;
        statistics["最长句子"] = 45;
        statistics["最短句子"] = 3;
        statistics["图表数量"] = 12;
        statistics["参考文献数"] = 28;

        for (auto it = statistics.begin(); it != statistics.end(); ++it) {
            statisticalReport += QString("%1: %2\n").arg(it.key()).arg(it.value().toString());
        }

        // 添加统计图表数据（格式化的数据）
        statisticalReport += "\n词频统计（前10）:\n";

    } else if (reportType == "structural") {

        // 文档结构分析
        QString structuralReport = QString("文档结构分析报告\n"
                                           "===================\n");

        // 文档结构
        structuralReport += "文档结构层次:\n\n";

        // 结构分析结果
        structuralReport += "\n结构分析结果:\n";

        QVector<QPair<QString, QString>> structureAnalysis = {
            {"结构完整性", "优秀 (层次清晰，逻辑连贯)"},
            {"章节平衡性", "良好 (各章节长度适中)"},
            {"标题规范性", "符合标准 (使用标准编号系统)"},
            {"引用完整性", "完整 (所有引用都有对应参考文献)"},
            {"图表位置", "合理 (图表紧邻相关文字说明)"}
        };
    }

    // 报告生成耗时
    QThread::msleep(200);
}

void WritingAddItemDialog::batchProcessDocuments(const QStringList& filePaths, int processingMode)
{
    if (filePaths.isEmpty()) {
        qWarning() << "文件列表为空，无法进行批量处理";
        return;
    }

    // 验证处理模式
    if (processingMode < 0 || processingMode > 5) {
        qWarning() << "无效的处理模式:" << processingMode << "，有效范围: 0-5";
        return;
    }

    // 进度跟踪
    int totalFiles = filePaths.size();
    int processedFiles = 0;
    int successfulFiles = 0;
    int failedFiles = 0;

    QVector<QPair<QString, QString>> processingResults;

    // 批量处理每个文件
    for (const QString& filePath : filePaths) {
        processedFiles++;
        qDebug() << QString("处理进度: %1/%2 - 处理文件: %3")
                    .arg(processedFiles)
                    .arg(totalFiles)
                    .arg(QFileInfo(filePath).fileName());

        // 检查文件
        QFileInfo fileInfo(filePath);
        if (!fileInfo.exists()) {
            qWarning() << "文件不存在，跳过:" << filePath;
            failedFiles++;
            processingResults.append({filePath, "失败: 文件不存在"});
            continue;
        }

        // 根据处理模式执行不同的操作
        QString result;

        // 处理结果
        if (result.startsWith("成功")) {
            successfulFiles++;
        } else {
            failedFiles++;
        }

        processingResults.append({filePath, result});

        // 处理耗时
        QThread::msleep(50 + qrand() % 100); // 随机耗时50-150ms
    }

    // 生成批量处理报告
    QString batchReport = QString("批量处理完成报告\n"
                                  "==================\n"
                                  "处理模式: %1\n"
                                  "总文件数: %2\n"
                                  "成功处理: %3\n"
                                  "处理失败: %4\n"
                                  "处理进度: %5%\n\n"
                                  "详细结果:\n")
            .arg(processingMode)
            .arg(totalFiles)
            .arg(successfulFiles)
            .arg(failedFiles)
            .arg((double)processedFiles / totalFiles * 100, 0, 'f', 2);

    // 添加处理统计
    batchReport += "\n处理统计:\n";

    // 添加处理建议
    batchReport += "\n处理建议:\n";

    if (failedFiles > 0) {
        batchReport += QString("1. %1 个文件处理失败，建议检查文件格式和内容\n").arg(failedFiles);
    }

    if (successfulFiles == totalFiles) {
        batchReport += "2. 所有文件处理成功，无需进一步操作\n";
    } else if (successfulFiles > totalFiles * 0.8) {
        batchReport += "2. 大部分文件处理成功，少数失败文件可单独处理\n";
    } else {
        batchReport += "2. 处理成功率较低，建议检查处理模式和文件兼容性\n";
    }

    batchReport += "3. 处理完成时间: " + QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss") + "\n";

    qDebug() << "批量处理完成，报告生成成功";
    qDebug() << batchReport;
}
