#include "documenthandler.h"

#include <QtGui/QTextDocument>
#include <QtGui/QTextCursor>
#include <QtGui/QFontDatabase>
#include <QtCore/QFileInfo>
#include <QStandardPaths>
#include <QDir>
#include <QTextBlock>
#include <QTextList>
#include <cmark.h>
DocumentHandler::DocumentHandler()
    : m_target(0)
    , m_doc(0)
    , m_cursorPosition(-1)
    , m_selectionStart(0)
    , m_selectionEnd(0)
{
}

void DocumentHandler::setTarget(QQuickItem *target)
{
    m_doc = 0;
    m_target = target;
    if (!m_target)
        return;

    QVariant doc = m_target->property("textDocument");
    if (doc.canConvert<QQuickTextDocument*>()) {
        QQuickTextDocument *qqdoc = doc.value<QQuickTextDocument*>();
        if (qqdoc)
            m_doc = qqdoc->textDocument();
    }
    emit targetChanged();
}

void DocumentHandler::setFileUrl(const QUrl &arg)
{
    //加载markdown文件并处理
    if (m_fileUrl != arg) {
        m_fileUrl = arg;
        QString fileName = QQmlFile::urlToLocalFileOrQrc(arg);
        if (QFile::exists(fileName)) {
            QFile file(fileName);
            // 打开文件时指定文本模式，避免二进制解析问题
            if (file.open(QFile::ReadOnly | QFile::Text)) {
                QByteArray data = file.readAll();
                QString markdownText;

                // 核心：优先尝试 UTF-8 编码（Markdown 标准编码）
                // 检测是否为带 BOM 的 UTF-8（可选，多数 Markdown 无 BOM）
                bool hasUtf8Bom = data.startsWith("\xef\xbb\xbf");
                if (hasUtf8Bom) {
                    // 移除 BOM 后解析
                    markdownText = QString::fromUtf8(data.mid(3));
                } else {
                    // 无 BOM 时直接尝试 UTF-8
                    markdownText = QString::fromUtf8(data);
                }

                // 若 UTF-8 解析失败（存在无效字符），尝试 GBK 编码（兼容中文常见编码）
                if (markdownText.isNull() || markdownText.contains(QChar::ReplacementCharacter)) {
                    QTextCodec *gbkCodec = QTextCodec::codecForName("GBK");
                    if (gbkCodec) {
                        markdownText = gbkCodec->toUnicode(data);
                    }
                }

                // 确保解析成功后再更新文本
                if (!markdownText.isNull()) {
                    setText(markdownText);  // 设置原始 Markdown 文本（非 HTML）
                    if (m_doc) {
                        m_doc->setModified(false);
                    }
                    // 更新文档标题
                    m_documentTitle = fileName.isEmpty()
                        ? QStringLiteral("untitled.md")  // Markdown 用 .md 后缀
                        : QFileInfo(fileName).fileName();

                    emit textChanged();
                    emit documentTitleChanged();
                    reset();
                } else {
                    // 编码解析失败，发送错误提示
                    emit error(QStringLiteral("无法解析文件编码，请确认文件为 UTF-8 或 GBK 格式"));
                }
            } else {
                // 打开文件失败，发送错误提示
                emit error(QStringLiteral("无法打开文件: %1").arg(file.errorString()));
            }
        }
        emit fileUrlChanged();
    }

}

QString DocumentHandler::documentTitle() const
{
    return m_documentTitle;
}

QString DocumentHandler::editMessage()
{
    return m_editMessage;
}

void DocumentHandler::setDocumentTitle(QString arg)
{
    if (m_documentTitle != arg) {
        m_documentTitle = arg;
        emit documentTitleChanged();
    }
}

void DocumentHandler::replaceText(QString text, int start, int end)
{
    qInfo() << "替换后的文字：" << text;
    QTextCursor cursor = QTextCursor(m_doc);
    cursor.setPosition(start); // 移动光标到起始位置
    cursor.setPosition(end, QTextCursor::KeepAnchor);
    cursor.insertText(text);

    return;
}

void DocumentHandler::insertText(QString text, int position)
{
    qInfo() << "插入的文字：" << text;
    text = "\n" + text + "\n";
    QTextCursor cursor = QTextCursor(m_doc);
    cursor.setPosition(position);
    cursor.insertText(text);

    return;
}

void DocumentHandler::setEditMessage(QString arg)
{
    // KyInfo() << "setEditMessage" << arg;
    if (m_editMessage != arg) {
        m_editMessage = arg;
        emit editMessageChanged();
    }
}

void DocumentHandler::markTextSelected(int start, int end)
{
    if (!m_doc)
        return;

    // 校验范围有效性
    if (start < 0 || end > m_doc->characterCount() || start >= end) {
        return;
    }

    // 白色文字 + 蓝色背景
    QTextCharFormat format;
    format.setForeground(Qt::white);
    format.setBackground(QColor("#3790FA"));

    // 应用格式到指定范围
    QTextCursor cursor(m_doc);
    cursor.setPosition(start);
    cursor.setPosition(end, QTextCursor::KeepAnchor);
    cursor.mergeCharFormat(format);

    return;
}

void DocumentHandler::markTextUnselected(int start, int end)
{
    if (!m_doc)
        return;

    // 校验范围有效性
    if (start < 0 || end > m_doc->characterCount() || start >= end) {
        return;
    }

    // 创建格式：白色文字 + 蓝色背景
    QTextCharFormat format;
    format.setForeground(Qt::black);       // 文字颜色
    format.setBackground(Qt::white);        // 背景颜色

    // 应用格式到指定范围
    QTextCursor cursor(m_doc);
    cursor.setPosition(start);
    cursor.setPosition(end, QTextCursor::KeepAnchor);  // 选中[start, end)范围
    cursor.mergeCharFormat(format);

    return;
}

void DocumentHandler::setText(const QString &arg)
{
    if (m_text != arg) {
        m_text = arg;
        emit textChanged();
    }
}

QString DocumentHandler::getHtmlContent()
{
    return m_doc->toHtml();
}

QString DocumentHandler::getPlainTextContent()
{
    if (!m_doc)
        return "";
    return m_doc->toPlainText();
}

QString DocumentHandler::getMarkdownContent()
{
    if (!m_doc)
        return "";
    return m_doc->toMarkdown();
}

//void DocumentHandler::saveAs(const QString &fileType)
//{
////    bool isHtml = fileType.contains(QLatin1String("htm"));
////    QLatin1String ext(isHtml ? ".html" : ".txt");
////    QString localPath = arg.toLocalFile();
////    if (!localPath.endsWith(ext))
////        localPath += ext;
////    QFile f(localPath);
////    if (!f.open(QFile::WriteOnly | QFile::Truncate | (isHtml ? QFile::NotOpen : QFile::Text))) {
////        emit error(tr("Cannot save: ") + f.errorString());
////        return;
////    }
////    f.write((isHtml ? m_doc->toHtml() : m_doc->toPlainText()).toLocal8Bit());
////    f.close();
////    setFileUrl(QUrl::fromLocalFile(localPath));
//    // 手动指定路径（例如：保存到用户桌面）
//    QString desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
//    QString fileName = "manual_save.md";
//    QString fullPath = QDir(desktopPath).filePath(fileName);

//    // 转换为 QUrl 作为 arg
//    QUrl arg = QUrl::fromLocalFile(fullPath);
//    // 判断是否为Markdown类型
//       bool isMarkdown = fileType.compare(QLatin1String("text/markdown"), Qt::CaseInsensitive) == 0
//                       || fileType.contains(QLatin1String("markdown"), Qt::CaseInsensitive)
//                       || fileType.contains(QLatin1String("md"), Qt::CaseInsensitive);

//       // 确定文件扩展名
//       const QLatin1String ext(isMarkdown ? ".md" : ".txt");
//       QString localPath = arg.toLocalFile();

//       // 验证文件路径
//       if (localPath.isEmpty()) {
//           emit error(tr("Invalid file path"));
//           return;
//       }

//       // 确保文件有正确的扩展名
//       if (!localPath.endsWith(ext, Qt::CaseInsensitive)) {
//           localPath += ext;
//       }

//       // 检查文件是否已存在（可添加覆盖确认）
//       QFileInfo fileInfo(localPath);
//       if (fileInfo.exists()) {
//           // 这里可以添加文件覆盖确认逻辑
//           // if (!confirmOverwrite(localPath)) return;
//       }

//       QFile file(localPath);
//       // 对于Markdown也使用文本模式打开，确保换行符正确处理
//       QIODevice::OpenMode openMode = QFile::WriteOnly | QFile::Truncate | QFile::Text;

//       // 尝试打开文件
//       if (!file.open(openMode)) {
//           emit error(tr("Cannot save file: %1").arg(file.errorString()));
//           return;
//       }

//       // 写入文件内容，使用UTF-8编码确保兼容性
//       QByteArray content;
//       if (isMarkdown) {
//           // 假设m_doc有toMarkdown()方法，如果没有需要实现Markdown转换逻辑
//           // 如果没有专门的Markdown转换，可以先使用纯文本或HTML转Markdown的逻辑
//           content = m_doc->toMarkdown().toUtf8();

//           // 如果没有toMarkdown()方法，可以临时用以下方式替代
//           // content = convertToMarkdown(m_doc).toUtf8();
//       } else {
//           content = m_doc->toPlainText().toUtf8();
//       }

//       qint64 bytesWritten = file.write(content);
//       if (bytesWritten != content.size()) {
//           emit error(tr("Error writing to file: %1").arg(file.errorString()));
//           return;
//       }

//       // 更新文件URL
//       setFileUrl(QUrl::fromLocalFile(localPath));
//}

QUrl DocumentHandler::fileUrl() const
{
    return m_fileUrl;
}

QString DocumentHandler::text() const
{
    return m_text;
}

void DocumentHandler::setCursorPosition(int position)
{
    if (position == m_cursorPosition)
        return;

    m_cursorPosition = position;

    reset();
}

void DocumentHandler::reset()
{
    emit fontFamilyChanged();
    emit alignmentChanged();
    emit boldChanged();
    emit italicChanged();
    emit underlineChanged();
    emit fontSizeChanged();
    emit textColorChanged();
}

QTextCursor DocumentHandler::textCursor() const
{
    if (!m_doc)
        return QTextCursor();
    QTextCursor cursor = QTextCursor(m_doc);
    if (m_selectionStart != m_selectionEnd) {
        cursor.setPosition(m_selectionStart);
        cursor.setPosition(m_selectionEnd, QTextCursor::KeepAnchor);
    } else {
        cursor.setPosition(m_cursorPosition);
    }
    return cursor;
}

void DocumentHandler::mergeFormatOnWordOrSelection(const QTextCharFormat &format)
{
    QTextCursor cursor = textCursor();
    if (!cursor.hasSelection())
         return;
    cursor.mergeCharFormat(format);
}

void DocumentHandler::setSelectionStart(int position)
{
    m_selectionStart = position;
}

void DocumentHandler::setSelectionEnd(int position)
{
    m_selectionEnd = position;
}

void DocumentHandler::setAlignment(Qt::Alignment a)
{
    if (!m_doc)
        return;

    QTextBlockFormat fmt;
    fmt.setAlignment((Qt::Alignment) a);
    QTextCursor cursor = QTextCursor(m_doc);
    cursor.setPosition(m_selectionStart, QTextCursor::MoveAnchor);
    cursor.setPosition(m_selectionEnd, QTextCursor::KeepAnchor);
    cursor.mergeBlockFormat(fmt);
    emit alignmentChanged();
}

Qt::Alignment DocumentHandler::alignment() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return Qt::AlignLeft;
    return textCursor().blockFormat().alignment();
}

bool DocumentHandler::bold() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return false;
    return textCursor().charFormat().fontWeight() == QFont::Bold;
}

bool DocumentHandler::italic() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return false;
    return textCursor().charFormat().fontItalic();
}

bool DocumentHandler::underline() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return false;
    return textCursor().charFormat().fontUnderline();
}

bool DocumentHandler::strikeOut() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return false;
    return textCursor().charFormat().fontStrikeOut();
}

void DocumentHandler::setBold(bool arg)
{
    QTextCharFormat fmt;
    fmt.setFontWeight(arg ? QFont::Bold : QFont::Normal);
    mergeFormatOnWordOrSelection(fmt);
    emit boldChanged();
}

void DocumentHandler::setItalic(bool arg)
{
    QTextCursor cursor = QTextCursor(m_doc);
    cursor.setPosition(m_selectionStart);
    cursor.setPosition(m_selectionEnd, QTextCursor::KeepAnchor);
    qDebug() <<"m_selectionStart:"<< m_selectionStart
            <<"m_selectionEnd"<<m_selectionEnd <<"current set arg:" << arg;
    if( true) {
        QTextCharFormat fmt;
        fmt.setFontItalic(arg);  // 设置斜体状态（arg 为 true 则斜体，false 取消）
        cursor.mergeCharFormat(fmt);  // 仅作用于光标选中的区域
        qDebug() << "222222222222222";
        emit italicChanged();
    }
    else {

        qDebug() << "当前未选择内容";
    }
}

void DocumentHandler::setUnderline(bool arg)
{
    QTextCharFormat fmt;
    fmt.setFontUnderline(arg);
    mergeFormatOnWordOrSelection(fmt);
    emit underlineChanged();
}

void DocumentHandler::setStrikeOut(bool arg)
{
    QTextCharFormat fmt;
    fmt.setFontStrikeOut(arg);
    mergeFormatOnWordOrSelection(fmt);
    emit strikeOutChanged();
}

int DocumentHandler::fontSize() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return 0;
    QTextCharFormat format = cursor.charFormat();
    return format.font().pointSize();
}

// 获取光标所在块的大纲等级
int DocumentHandler::outline() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return 0;

    QTextBlock currentBlock = cursor.block();
    QTextBlockFormat blockFormat = currentBlock.blockFormat();

    // 检查是否是标题格式
    int headingLevel = blockFormat.headingLevel();
    return (headingLevel >= 0 && headingLevel <= 2) ? headingLevel : 0;
}

QTextListFormat::Style DocumentHandler::listStyle() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return QTextListFormat::ListStyleUndefined;

    QTextListFormat listFormat;
    if (cursor.currentList()) {
        listFormat = cursor.currentList()->format();
    }

    return listFormat.style();
}

void DocumentHandler::setFontSize(int arg)
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return;
    QTextCharFormat format;
    format.setFontPointSize(arg);
    mergeFormatOnWordOrSelection(format);
    emit fontSizeChanged();
}

QColor DocumentHandler::textColor() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return QColor(Qt::black);
    QTextCharFormat format = cursor.charFormat();
    return format.foreground().color();
}

void DocumentHandler::setTextColor(const QColor &c)
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return;
    QTextCharFormat format;
    format.setForeground(QBrush(c));
    mergeFormatOnWordOrSelection(format);
    emit textColorChanged();
}

QString DocumentHandler::fontFamily() const
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return QString();
    QTextCharFormat format = cursor.charFormat();
    return format.font().family();
}

void DocumentHandler::setFontFamily(const QString &arg)
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return;
    QTextCharFormat format;
    format.setFontFamily(arg);
    mergeFormatOnWordOrSelection(format);
    emit fontFamilyChanged();
}

void DocumentHandler::setOutline(const int level)
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return;

    QTextBlockFormat blockFormat;
    blockFormat.setHeadingLevel(level);

    // 设置标题字体格式
    QTextCharFormat charFormat;
    switch (level) {
        case 0:
            charFormat.setFontPointSize(10);
            charFormat.setFontWeight(QFont::Normal);
            blockFormat.setTopMargin(6);
            blockFormat.setBottomMargin(6);
            break;
        case 1:
            charFormat.setFontPointSize(20);
            charFormat.setFontWeight(QFont::Bold);
            blockFormat.setTopMargin(0);
            blockFormat.setBottomMargin(0);
            break;
        case 2:
            charFormat.setFontPointSize(15);
            charFormat.setFontWeight(QFont::Bold);
            blockFormat.setTopMargin(0);
            blockFormat.setBottomMargin(0);
            break;
        case 3:
            charFormat.setFontPointSize(12);
            charFormat.setFontWeight(QFont::Bold);
            blockFormat.setTopMargin(0);
            blockFormat.setBottomMargin(0);
            break;
        case 4:
            charFormat.setFontPointSize(10);
            charFormat.setFontWeight(QFont::Bold);
            blockFormat.setTopMargin(0);
            blockFormat.setBottomMargin(0);
            break;
    }

    // 应用格式到当前段落
    cursor.movePosition(QTextCursor::StartOfBlock);
    cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    cursor.mergeBlockFormat(blockFormat);
    cursor.setCharFormat(charFormat);
    qInfo() << "设置文字大纲级别：" << level;
    emit outlineChanged();
}

void DocumentHandler::setListStyle(QTextListFormat::Style style)
{
    QTextCursor cursor = textCursor();
    if (cursor.isNull())
        return ;

    QTextListFormat listFormat;
    if (cursor.currentList()) {
        listFormat = cursor.currentList()->format();
    }

    qInfo() << "对比style， 原 " << listFormat.style() << " 修改后： " << style;

    //再次点击，执行清除样式逻辑
    if (listFormat.style() == style){
        QTextBlockFormat blockFormat = cursor.blockFormat();
        blockFormat.setObjectIndex(-1);
        cursor.setBlockFormat(blockFormat);
//        cursor.mergeBlockFormat(blockFormat);
        return;
    }
    listFormat.setStyle(style);
    cursor.createList(listFormat);
}

void DocumentHandler::setOrderedList()
{
    setListStyle(QTextListFormat::Style::ListDecimal);
}

void DocumentHandler::setUnorderedList()
{
    setListStyle(QTextListFormat::Style::ListDisc);
}

QStringList DocumentHandler::defaultFontSizes() const
{
    // uhm... this is quite ugly
    QStringList sizes;
    QFontDatabase db;
    const auto standardSizes = db.standardSizes();
    for (int size : standardSizes)
        sizes.append(QString::number(size));
    return sizes;
}
