<template>
    <div style="width: 100%; height: 260px;">
        <div ref="elRef" style="width: 100%; height: 100%;"></div>
    </div>
    <ExamWordsDetailCard v-model="detailVisible" :id="detailId" />
</template>

<script setup>
import { defineProps, ref, onMounted, onUnmounted, watch } from 'vue'
import ExamWordsDetailCard from '@/layouts/components/ExamWordsDetailCard.vue'

const props = defineProps({
    data: {
        type: Array,
        default: () => []
    }
})

const elRef = ref(null)
let chart = null
let echartsLib = null
const detailVisible = ref(false)
const detailId = ref(null)

function sortData(arr) {
    return Array.isArray(arr)
        ? arr.slice().sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime())
        : []
}

function toSource(arr) {
    return sortData(arr).map(it => ({
        startDate: it.startDate,
        correctWordCount: Number(it.correctWordCount) || 0,
        wrongWordCount: Number(it.wrongWordCount) || 0,
        examWordsId: it.examWordsId ?? null,
        id: it.id ?? null
    }))
}

function buildOption(source) {
    return {
        dataset: [
            {
                id: 'dataset_history',
                source: source
            }
        ],
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            top: 8
        },
        xAxis: {
            type: 'category',
            nameLocation: 'middle'
        },
        yAxis: {
            name: 'Word Count',
            min: 0
        },
        series: [
            {
                type: 'line',
                datasetId: 'dataset_history',
                showSymbol: false,
                name: '正确词数',
                encode: {
                    x: 'startDate',
                    y: 'correctWordCount',
                    itemName: 'startDate',
                    tooltip: ['correctWordCount']
                }
            },
            {
                type: 'line',
                datasetId: 'dataset_history',
                showSymbol: false,
                name: '错误词数',
                encode: {
                    x: 'startDate',
                    y: 'wrongWordCount',
                    itemName: 'startDate',
                    tooltip: ['wrongWordCount']
                }
            }
        ]
    }
}

function resize() {
    if (chart) chart.resize()
}

async function ensureEcharts() {
    try {
        const mod = await import('echarts')
        echartsLib = mod
    } catch (e) {
        if (window.echarts) {
            echartsLib = window.echarts
        } else {
            await new Promise(resolve => {
                const s = document.createElement('script')
                s.src = 'https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js'
                s.onload = resolve
                document.head.appendChild(s)
            })
            echartsLib = window.echarts
        }
    }
}

async function render() {
    if (!elRef.value) return
    await ensureEcharts()
    if (!echartsLib) return
    if (!chart) {
        chart = echartsLib.init(elRef.value)
        chart.on('click', handlePointClick)
        window.addEventListener('resize', resize)
    }
    const source = toSource(props.data)
    const option = buildOption(source)
    chart.setOption(option)
}

function handlePointClick(params) {
    const row = params?.data
    console.log(row)
    const id = row?.id ?? null
    if (id !== null && id !== undefined) {
        detailId.value = id
        detailVisible.value = true
    }
}

onMounted(() => {
    render()
})

onUnmounted(() => {
    window.removeEventListener('resize', resize)
    if (chart) {
        chart.off('click', handlePointClick)
        chart.dispose()
        chart = null
    }
})

watch(() => props.data, () => {
    render()
}, { deep: true })
</script>
