<!-- 标段解析 -->
<template>
    <div class="analysis-bid-view">
        <!-- 头部导航 -->
        <AnalysisHeader @back="handleBack" />

        <el-card>
            <!-- 解析结果标题 -->
            <div class="result-header">
                <img src="@/assets/enterpriseLibrary/basic-info.png" alt="基本信息">
                <h3>解析结果</h3>
            </div>

            <!-- 一级标签页 - 占满整行 -->
            <div class="main-tabs-container">
                <el-tabs v-model="activeMainTab" @tab-click="handleMainTabClick" class="main-tabs">
                    <el-tab-pane v-for="tab in mainTabs" :key="tab.name" :label="tab.label" :name="tab.name" />
                </el-tabs>
            </div>

            <!-- 主内容区域 - 左右各占50% -->
            <div class="main-content">
                <!-- 左侧：解析结果面板（包含二级tab和内容） -->
                <div class="left-panel">
                    <AnalysisResultPanel ref="resultPanel" :main-tabs="mainTabs" :default-main-tab="activeMainTab"
                        :default-sub-tab="defaultSubTab" @main-tab-change="handleMainTabChange"
                        @sub-tab-change="handleSubTabChange" :hide-main-tabs="true" :hide-header="true"
                        :key="activeMainTab" />
                </div>

                <!-- 右侧：文档预览面板 -->
                <div class="right-panel">
                    <DocumentPreviewPanel :tender-document-url="tenderDocumentUrl"
                        :tender-document-title="tenderDocumentTitle" :tender-document-key="tenderDocumentKey"
                        :bid-document-url="bidDocumentUrl" :bid-document-title="bidDocumentTitle"
                        :bid-document-key="bidDocumentKey" @document-switch="handleDocumentSwitch"
                        @search="handleSearch" />
                </div>
            </div>
        </el-card>
    </div>
</template>

<script>
import { decryptWithSM4, encryptWithSM4 } from '@/utils/sm'
import AnalysisHeader from './child/AnalysisHeader.vue'
import AnalysisResultPanel from './child/AnalysisResultPanel.vue'
import DocumentPreviewPanel from './child/DocumentPreviewPanel.vue'
import analysisResultMock from '../analysisResultMock.json'
// import { getBidDetailAPI } from '@/api/analysis/analysis'

const HTML_TAG_REG = /<\/?[a-z][\s\S]*>/i
const MAX_PARSE_DEPTH = 5

function formatSectionValue(raw, depth = 0) {
    const fallback = { content: '--', isHtml: false, tableRows: null, hasScoreRange: false }
    if (raw === undefined || raw === null) {
        return fallback
    }
    if (depth > MAX_PARSE_DEPTH) {
        const content = String(raw)
        return { content, isHtml: HTML_TAG_REG.test(content), tableRows: null, hasScoreRange: false }
    }
    if (typeof raw === 'string') {
        const trimmed = raw.trim()
        if (!trimmed) {
            return fallback
        }
        try {
            const parsed = JSON.parse(trimmed)
            return formatSectionValue(parsed, depth + 1)
        } catch (error) {
            return { content: trimmed, isHtml: HTML_TAG_REG.test(trimmed), tableRows: null, hasScoreRange: false }
        }
    }
    if (Array.isArray(raw)) {
        const { rows: tableRows, hasScoreRange } = buildTableRows(raw, depth)
        if (tableRows.length > 0) {
            return { content: '', isHtml: false, tableRows, hasScoreRange }
        }
        const lines = raw.map(item => {
            if (typeof item === 'object' && item !== null) {
                const label = item.name || item.label || item.title || item.key || ''
                const valueField = item.content ?? item.value ?? item.text ?? ''
                const formatted = formatSectionValue(valueField, depth + 1)
                return label ? `${label}：${formatted.content}` : formatted.content
            }
            return formatSectionValue(item, depth + 1).content
        }).filter(Boolean)
        const content = lines.length > 0 ? lines.join('\n') : '--'
        return { content, isHtml: false, tableRows: null, hasScoreRange: false }
    }
    if (typeof raw === 'object') {
        if (Object.prototype.hasOwnProperty.call(raw, 'value')) {
            return formatSectionValue(raw.value, depth + 1)
        }
        const lines = Object.entries(raw).map(([key, value]) => {
            const formatted = formatSectionValue(value, depth + 1)
            return `${key}：${formatted.content}`
        }).filter(Boolean)
        const content = lines.length > 0 ? lines.join('\n') : '--'
        return { content, isHtml: false, tableRows: null, hasScoreRange: false }
    }
    const content = String(raw)
    return { content, isHtml: HTML_TAG_REG.test(content), tableRows: null, hasScoreRange: false }
}

function hasScoreValue(value) {
    return value !== undefined && value !== null && value !== ''
}

function buildTableRows(items, depth) {
    const rows = items.map(item => {
        if (typeof item !== 'object' || item === null) {
            return null
        }
        const title = item.name ?? item.label ?? item.title ?? item.key ?? ''
        if (title === '' || title === undefined) {
            return null
        }
        const valueSource = item.content ?? item.value ?? item.text ?? item.desc ?? item.detail
        const formatted = formatSectionValue(valueSource, depth + 1)
        const nestedTable = formatted.tableRows && formatted.tableRows.length > 0
            ? formatted.tableRows.map(row => `${row.title}：${row.value}`).join('\n')
            : ''
        const value = nestedTable || formatted.content || '--'
        const minScore = item.minScore ?? item.scoreMin ?? item.min ?? item.lowScore
        const maxScore = item.maxScore ?? item.scoreMax ?? item.max ?? item.highScore
        const scoreRange = item.scoreRange ?? item.range ?? item.score ?? null
        return {
            title,
            value,
            isHtml: formatted.isHtml,
            minScore,
            maxScore,
            scoreRange
        }
    }).filter(Boolean)
    const hasScoreRange = rows.some(row =>
        hasScoreValue(row.minScore) ||
        hasScoreValue(row.maxScore) ||
        hasScoreValue(row.scoreRange)
    )
    return { rows, hasScoreRange }
}

const collectSectionsFromNode = (node) => {
    const sections = []
    const traverse = (target) => {
        if (!target) return
        if (Object.prototype.hasOwnProperty.call(target, 'tagValue')) {
            const formatted = formatSectionValue(target.tagValue)
            sections.push({
                id: target.id,
                title: target.name,
                content: formatted.content,
                isHtml: formatted.isHtml,
                tableRows: formatted.tableRows,
                hasScoreRange: formatted.hasScoreRange
            })
        }
        if (target.children && target.children.length) {
            sortByWeight(target.children).forEach(child => traverse(child))
        }
    }
    traverse(node)
    return sections
}

const sortByWeight = (list = []) => {
    return [...list].sort((a, b) => {
        const weightA = a?.weight ?? 0
        const weightB = b?.weight ?? 0
        return weightA - weightB
    })
}

const buildTabsFromTree = (tree = []) => {
    return sortByWeight(tree).map(node => {
        const subTabs = sortByWeight(node.children || []).map(child => ({
            name: child.id,
            label: child.name,
            sections: collectSectionsFromNode(child)
        }))
        return {
            name: node.id,
            label: node.name,
            subTabs,
            sections: subTabs.length === 0 ? collectSectionsFromNode(node) : []
        }
    })
}

export default {
    name: 'AnalysisBidView',
    components: {
        AnalysisHeader,
        AnalysisResultPanel,
        DocumentPreviewPanel
    },
    data() {
        return {
            proId: decryptWithSM4(this.$route.query.proId),
            bidId: decryptWithSM4(this.$route.query.bidId),
            activeMainTab: '',
            defaultSubTab: '', // 初始为空，由 AnalysisResultPanel 组件自动获取第一个子标签
            tenderDocumentUrl: '',
            tenderDocumentTitle: '',
            tenderDocumentKey: '',
            bidDocumentUrl: '',
            bidDocumentTitle: '',
            bidDocumentKey: '',
            mainTabs: []
        }
    },
    created() {
        this.getBidDetail()
    },
    methods: {
        handleBack() {
            const obj = { name: "AnalysisBidIndex", query: { proId: encryptWithSM4(this.proId) } }
            this.$tab.closeOpenPage(obj)
        },
        // 获取标段详情
        async getBidDetail() {
            try {
                // TODO: 根据实际API调整，获取标段解析结果数据
                // const res = await getBidDetailAPI({ proId: this.proId, bidId: this.bidId })
                // if (res.code === 200) {
                //     this.mainTabs = buildTabsFromTree(res.data || [])
                //     this.initDocumentData(res.data)
                // }

                // 临时使用本地 mock 数据
                const parsedTabs = buildTabsFromTree(analysisResultMock)
                this.mainTabs = parsedTabs
                if (parsedTabs.length > 0) {
                    this.activeMainTab = parsedTabs[0].name
                    this.defaultSubTab = parsedTabs[0].subTabs?.[0]?.name || ''
                }
            } catch (error) {
                console.error('获取标段详情失败:', error)
            }
        },
        // 初始化文档数据
        initDocumentData(data) {
            if (data) {
                this.tenderDocumentUrl = data.tenderDocumentUrl || ''
                this.tenderDocumentTitle = data.tenderDocumentTitle || ''
                this.tenderDocumentKey = data.tenderDocumentKey || ''
                this.bidDocumentUrl = data.bidDocumentUrl || ''
                this.bidDocumentTitle = data.bidDocumentTitle || ''
                this.bidDocumentKey = data.bidDocumentKey || ''
            }
        },
        handleMainTabClick(tab) {
            this.activeMainTab = tab.name
            // 获取当前主标签的第一个子标签
            const currentMainTab = this.mainTabs.find(t => t.name === tab.name)
            const firstSubTab = currentMainTab && currentMainTab.subTabs && currentMainTab.subTabs.length > 0
                ? currentMainTab.subTabs[0].name
                : ''
            // 强制更新 defaultSubTab，确保子标签切换
            this.$nextTick(() => {
                this.defaultSubTab = firstSubTab
            })
            this.handleMainTabChange(tab.name, firstSubTab)
        },
        handleMainTabChange(mainTab, subTab) {
            console.log('主标签切换:', mainTab, subTab)
        },
        handleSubTabChange(mainTab, subTab) {
            console.log('子标签切换:', mainTab, subTab)
        },
        handleDocumentSwitch(type) {
            console.log('文档切换:', type)
        },
        handleSearch() {
            console.log('搜索')
        }
    },
}
</script>
<style scoped lang="scss">
.analysis-bid-view {
    height: calc(100vh - 84px);
    display: flex;
    flex-direction: column;
    background: linear-gradient(180deg, #F1F6FF 0%, #E5EFFF 100%);
    overflow: hidden;
    padding: 20px;

    ::v-deep .el-card {
        margin: 0;
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    ::v-deep .el-card__body {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        padding: 0;
    }

    // 解析结果标题
    .result-header {
        flex-shrink: 0;
        padding: 16px 20px;
        border-bottom: 1px solid #EBEEF5;
        background: #FFFFFF;
        display: flex;
        align-items: center;
        gap: 8px;

        img {
            width: 34px;
            height: 34px;
            object-fit: contain;
        }

        h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #303133;
        }
    }

    // 一级标签页容器 - 占满整行
    .main-tabs-container {
        flex-shrink: 0;
        // background: #F5F7FA;
        padding: 12px 20px;
        border-bottom: 1px solid #EBEEF5;

        // 使用最具体的选择器确保第一个标签的圆角生效
        ::v-deep .main-tabs .el-tabs__nav .el-tabs__item:first-child {
            border-top-left-radius: 6px !important;
            border-bottom-left-radius: 6px !important;
        }

        ::v-deep .main-tabs .el-tabs__nav .el-tabs__item.is-active:first-child {
            border-top-left-radius: 6px !important;
            border-bottom-left-radius: 6px !important;
        }

        // 使用最具体的选择器确保第二个标签的圆角生效并设置左边框
        ::v-deep .main-tabs .el-tabs__nav .el-tabs__item:nth-child(2) {
            border-top-left-radius: 6px !important;
            border-bottom-left-radius: 6px !important;
            border-top-right-radius: 0px !important;
            border-bottom-right-radius: 0px !important;
            border-left: 1px solid #d9d9d9 !important;
        }

        ::v-deep .main-tabs .el-tabs__nav .el-tabs__item.is-active:nth-child(2) {
            border-top-left-radius: 6px !important;
            border-bottom-left-radius: 6px !important;
            border-top-right-radius: 0px !important;
            border-bottom-right-radius: 0px !important;
            border-left: 1px solid #1F72EA !important;
        }

        ::v-deep .main-tabs {
            .el-tabs__header {
                margin: 0;
                padding: 0;
                border-bottom: none;
                background: transparent;
            }

            .el-tabs__nav-wrap {
                &::after {
                    display: none;
                }
            }

            // 禁用下划线动画
            .el-tabs__active-bar {
                display: none !important;
            }

            .el-tabs__nav {
                border: none;
                display: flex;
                align-items: center;
                gap: 0;
            }

            .el-tabs__item {
                height: 36px;
                line-height: 36px;
                padding: 0 20px;
                font-size: 14px;
                color: #606266;
                background: #FFFFFF;
                border: 1px solid #d9d9d9;
                margin-right: 0;
                position: relative;
                transition: none;
                cursor: pointer;
                box-shadow: none;

                // 默认所有标签无圆角（除了第一个）
                &:not(:first-child) {
                    border-radius: 0;
                }

                // 第一个标签左圆角（所有状态）- 使用更具体的选择器
                &:first-child {
                    border-top-left-radius: 6px !important;
                    border-bottom-left-radius: 6px !important;
                    border-top-right-radius: 0 !important;
                    border-bottom-right-radius: 0 !important;
                }

                // 第二个标签圆角（所有状态）- 只有左上角和左下角，并设置左边框
                &:nth-child(2) {
                    border-top-left-radius: 6px !important;
                    border-bottom-left-radius: 6px !important;
                    border-top-right-radius: 0 !important;
                    border-bottom-right-radius: 0 !important;
                    border-left: 1px solid #d9d9d9 !important;
                }

                // 最后一个标签右圆角
                &:last-child {
                    border-top-right-radius: 6px;
                    border-bottom-right-radius: 6px;
                }

                // 中间标签移除左边框，避免重复（排除第二个）
                &:not(:first-child):not(:nth-child(2)) {
                    border-left: none;
                }

                // 激活状态：蓝色背景 + 白色文字
                &.is-active {
                    color: #FFFFFF;
                    background: #1F72EA;
                    font-weight: 500;
                    z-index: 1;
                    border-color: #1F72EA;

                    // 激活标签如果是第一个，确保保持左圆角
                    &:first-child {
                        border-top-left-radius: 6px !important;
                        border-bottom-left-radius: 6px !important;
                    }

                    // 激活标签如果是第二个，保持圆角（只有左上角和左下角）并设置左边框
                    &:nth-child(2) {
                        border-top-left-radius: 6px !important;
                        border-bottom-left-radius: 6px !important;
                        border-top-right-radius: 0 !important;
                        border-bottom-right-radius: 0 !important;
                        border-left: 1px solid #1F72EA !important;
                    }

                    // 激活标签如果是最后一个，保持右圆角
                    &:last-child {
                        border-top-right-radius: 6px;
                        border-bottom-right-radius: 6px;
                    }

                    // 激活标签需要恢复左边框（如果它不是第一个和第二个）
                    &:not(:first-child):not(:nth-child(2)) {
                        border-left: 1px solid #1F72EA;
                    }
                }

                // 非激活状态：白色背景 + 深色文字
                &:not(.is-active) {
                    background: #FFFFFF;
                    color: #606266;

                    // 非激活状态的第一个标签保持圆角
                    &:first-child {
                        border-top-left-radius: 6px !important;
                        border-bottom-left-radius: 6px !important;
                    }

                    &:hover {
                        background: #F0F4FF;
                        color: #1F72EA;
                    }
                }
            }
        }
    }

    .main-content {
        flex: 1;
        display: flex;
        gap: 20px;
        padding: 20px;
        overflow: hidden;

        .left-panel {
            flex: 0 0 50%;
            min-width: 0;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .right-panel {
            flex: 0 0 50%;
            min-width: 0;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
    }
}
</style>