import MarkdownIt from '@/packageA/lib/markdown-it.min.js';
import hljs from '@/packageA/lib/highlight/highlight-uni.min.js';
import parseHtml from '@/packageA/lib/html-parser.js';
import { jobMoreMap } from '@/utils/jobMoreMap.js';

export { jobMoreMap } from '@/utils/jobMoreMap.js';
export let codeDataList = []
export let jobCardsList = []

const md = new MarkdownIt({
    html: true, // 允许 HTML 标签
    linkify: true, // 自动解析 URL
    typographer: true, // 美化标点符号
    tables: true,
    breaks: true, // 让 \n 自动换行
    langPrefix: 'language-', // 代码高亮前缀
    // 如果结果以 <pre ... 开头，内部包装器则会跳过。
    highlight: function(str, lang) {
        if (lang === 'job-json') {
            const result = safeExtractJson(str);
            if (result) { // json解析成功
                let encryptJobId = result.appJobUrl;
                // If appJobUrl contains 'jobId=', extract the value after it, otherwise use it directly
                if (encryptJobId && encryptJobId.includes('jobId=')) {
                    encryptJobId = encryptJobId.split('jobId=')[1];
                    // 如果还有额外的参数，只取encryptJobId部分
                    if (encryptJobId.includes('&')) {
                        encryptJobId = encryptJobId.split('&')[0];
                    }
                }
                console.log('Job JSON result:', result, 'Extracted encryptJobId:', encryptJobId);

                // 确保encryptJobId有效
                if (!encryptJobId || encryptJobId === 'undefined' || encryptJobId === 'null') {
                    console.error('Invalid encryptJobId extracted:', encryptJobId, 'from appJobUrl:', result.appJobUrl);
                    // 尝试从其他字段获取encryptJobId
                    if (result.jobId) {
                        encryptJobId = result.jobId;
                        console.log('Using jobId from result.jobId as encryptJobId:', encryptJobId);
                    }
                }

                // 添加到岗位卡片列表，供小程序端单独渲染
                jobCardsList.push({
                    jobId: encryptJobId,
                    encryptJobId,
                    jobTitle: result.jobTitle,
                    salary: result.salary,
                    location: result.location,
                    companyName: result.companyName,
                    education: result.education,
                    experience: result.experience
                });

                // 生成岗位卡片HTML，注意：微信小程序rich-text组件只支持部分HTML属性
                // 使用普通的href属性，微信小程序rich-text会将其转换为可点击链接
                // 添加data-encrypt-job-id属性，方便获取encryptJobId
                // 为所有平台添加onclick事件，微信小程序可能会忽略，但H5端会生效
                // 内联基础样式确保在所有平台上正确显示（使用px单位以确保H5兼容性）
                let domContext = `<a class="custom-card" href="/packageA/pages/post/post?encryptJobId=${encryptJobId}" data-encrypt-job-id="${encryptJobId}" onclick="if(typeof uni !== 'undefined'){uni.navigateTo({url: '/packageA/pages/post/post?encryptJobId=${encryptJobId}'});return false;}" style="display: flex; flex-direction: column; margin-bottom: 11px; background: #FFFFFF; box-shadow: 0 0 4px rgba(0,0,0,0.04); border-radius: 10px; padding: 14px 12px; font-weight: 400; font-size: 14px; color: #333333; text-decoration: none; overflow: hidden; box-sizing: border-box; width: 100%; max-width: 100%;"><div class="card-title" style="font-weight: 600; display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;"><span class="title-text" style="font-family: 'PingFangSC-Medium', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif; font-size: 16px; line-height: 1.4; color: #333333; max-width: calc(100% - 80px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${result.jobTitle}</span><div class="card-salary" style="font-family: DIN-Medium; font-size: 16px; color: #4C6EFB; line-height: 1.4; font-weight: 500;">${result.salary}</div></div><div class="card-company" style="margin-bottom: 9px; font-size: 14px; color: #6C7282; line-height: 1.4; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${result.location}·${result.companyName}</div><div class="card-info" style="display: flex; align-items: center; justify-content: space-between; padding-right: 20px;"><div class="info-item" style="display: flex; position: relative; align-items: center;"><div class="card-tag" style="font-weight: 400; font-size: 12px; color: #6C7282; width: fit-content; background: #F4F4F4; border-radius: 2px; padding: 3px 10px; margin-right: 10px; display: inline-flex; align-items: center; justify-content: center; height: 15px; line-height: 15px;">${result.education}</div><div class="card-tag" style="font-weight: 400; font-size: 12px; color: #6C7282; width: fit-content; background: #F4F4F4; border-radius: 2px; padding: 3px 10px; display: inline-flex; align-items: center; justify-content: center; height: 15px; line-height: 15px;">${result.experience}</div></div><div class="info-item">查看详情<div class="position-nav" style="width: 14px; height: 14px; background: url('@/static/svg/position-nav.svg') center center no-repeat; background-size: 100% 100%; margin-left: 10px;padding-right: 50rpx"></div></div></div></a>`
                if (result.data) {
                    jobMoreMap.set(encryptJobId, result.data)
                    domContext += `<a class="custom-more" href="/packageA/pages/moreJobs/moreJobs?encryptJobId=${encryptJobId}" data-encrypt-job-id="${encryptJobId}" onclick="if(typeof uni !== 'undefined'){uni.navigateTo({url: '/packageA/pages/moreJobs/moreJobs?encryptJobId=${encryptJobId}'});return false;}" style="display: flex; justify-content: center; align-items: center; color: #FFFFFF; background: linear-gradient(135deg, #256BFA 0%, #9E74FD 100%); border-radius: 25px; padding: 10px 16px; margin: 10px 0; font-size: 14px; font-weight: 600; box-shadow: 0 4px 12px rgba(37, 107, 250, 0.3); text-decoration: none; box-sizing: border-box; width: 100%;">查看更多岗位<div class="more-icon" style="width: 16px; height: 16px; background: url('@/static/svg/seemore.svg') center center no-repeat; background-size: 100% 100%; margin-left: 6px;"></div></a>`
                }
                return domContext
            }
        }
        // 代码块
        let preCode = ""
        try {
            preCode = hljs.highlightAuto(str).value
        } catch (err) {
            preCode = md.utils.escapeHtml(str);
        }
        // 以换行进行分割 , 按行拆分代码
        const lines = preCode.split(/\n/).slice(0, -1);
        const html = lines
            .map((line, index) =>
                line ?
                `<li><span class="line-num" data-line="${index + 1}"></span>${line}</li>` :
                '<li></li>'
            )
            .join('');

        // 代码复制功能
        const cacheIndex = codeDataList.length;
        codeDataList.push(str);
        return `
            <div class="code-container">
                <div class="code-header">
                    <span class="lang-label">${lang || 'plaintext'}</span>
                    <a class="copy-btn" data-copy-index="${cacheIndex}">复制代码</a>
                </div>
                <pre class="hljs"><code><ol>${html}</ol></code></pre>
            </div>
        `;
    }
})

function extractFirstJson(text) {
    let stack = [];
    let startIndex = -1;
    let endIndex = -1;

    for (let i = 0; i < text.length; i++) {
        const char = text[i];

        if (char === '{') {
            if (stack.length === 0) startIndex = i; // 记录第一个 '{' 的位置
            stack.push(char);
        } else if (char === '}') {
            stack.pop();
            if (stack.length === 0) {
                endIndex = i; // 找到配对的 '}'
                break;
            }
        }
    }

    if (startIndex !== -1 && endIndex !== -1) {
        const jsonString = text.slice(startIndex, endIndex + 1);
        try {
            const jsonObject = JSON.parse(jsonString);
            return jsonObject;
        } catch (e) {
            return null; // 如果不是有效的 JSON
        }
    }

    return null; // 如果没有找到有效的 JSON 对象
}


function safeExtractJson(text) {
    try {
        const jsonObject = extractFirstJson(text);
        return jsonObject
    } catch (e) {
        console.error('JSON 解析失败:', e);
    }
    return null;
}

export function parseMarkdown(content) {
    if (!content) {
        return [] //处理特殊情况，比如网络异常导致的响应的 content 的值为空
    }
    
    // 过滤掉<think>标签及其内容，这些是AI内部思考过程，不应该显示给用户
    // 1. 处理原始标签（支持多行）
    content = content.replace(/<\s*think\s*>[\s\S]*?<\s*\/\s*think\s*>/gi, '')
    // 2. 处理HTML编码的标签
    content = content.replace(/&lt;\s*think\s*&gt;[\s\S]*?&lt;\s*\/\s*think\s*&gt;/gi, '')
    // 3. 处理部分编码的标签
    content = content.replace(/&lt;\s*think\s*>/gi, '')
    content = content.replace(/<\s*\/\s*think\s*&gt;/gi, '')
    
    codeDataList = []
    jobCardsList = [] // 清空岗位卡片列表，避免重复
    const unsafeHtml = md.render(content || '')
    
    // 在markdown渲染后再次过滤，确保没有遗漏
    let filteredHtml = unsafeHtml
    // 1. 处理原始标签（支持多行）
    filteredHtml = filteredHtml.replace(/<\s*think\s*>[\s\S]*?<\s*\/\s*think\s*>/gi, '')
    // 2. 处理HTML编码的标签
    filteredHtml = filteredHtml.replace(/&lt;\s*think\s*&gt;[\s\S]*?&lt;\s*\/\s*think\s*&gt;/gi, '')
    // 3. 处理部分编码的标签
    filteredHtml = filteredHtml.replace(/&lt;\s*think\s*>/gi, '')
    filteredHtml = filteredHtml.replace(/<\s*\/\s*think\s*&gt;/gi, '')
    // 4. 单独处理剩余的think标签对
    filteredHtml = filteredHtml.replace(/&lt;think&gt;/gi, '')
    filteredHtml = filteredHtml.replace(/&lt;\/think&gt;/gi, '')
    filteredHtml = filteredHtml.replace(/<think>/gi, '')
    filteredHtml = filteredHtml.replace(/<\/think>/gi, '')
    
    // 根据平台返回不同的内容格式
    // 微信小程序：返回rich-text组件支持的nodes格式
    // H5：直接返回HTML字符串，避免HTML解析错误
    if (process.env.UNI_PLATFORM === 'mp-weixin') {
        try {
            return parseHtml(filteredHtml)
        } catch (error) {
            console.error('HTML解析失败:', error)
            // 解析失败时返回空数组，避免页面崩溃
            return []
        }
    } else {
        // H5端直接返回HTML字符串
        return filteredHtml
    }
}
