<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElSpace, ElRadioGroup, ElRadio, ElRadioButton } from 'element-plus';
import * as echarts from 'echarts';
import { getStudyList, getSanctionList } from '@/api/companyPages';
import AnalysisBox from '@/components/base/boxBackground/analysisBox.vue';
import AiTipPane from '@/components/base/panes/AiTipPane.vue'

// 定义组件属性
const props = defineProps({
    enterpriseInfo: {
        type: Object,
        default: {}
    }
});

const studyList = ref([])
const sanctionList = ref([])
const studyTypes = ref([])
const studyType = ref()
const chartDom = ref()

let myChart = null

onMounted(async () => {
    await intData()
    // await initChart()
})

onUnmounted(() => myChart?.dispose())
async function intData() {
    const { data } = await getStudyList(props.enterpriseInfo.id)
    studyList.value = data ?? []
    data.forEach(t => t.time = new Date(t.year, 1, 1))
    studyTypes.value = [...new Set(data.map(t => t.type))]
    const { data: sanctionData } = await getSanctionList(props.enterpriseInfo.id)
    sanctionList.value = sanctionData ?? []
    sanctionList.value.forEach(t => t.time = new Date(t.sanctionDate))
    if (studyTypes.value.length > 0) {
        studyType.value = studyTypes.value[0]
    }
    updateCharts(studyType.value, studyList.value, sanctionList.value)
}
// 辅助函数：获取制裁年份对应的Y值
function getSanctionYValue(sanctionDate, filteredList, defaultYValue) {
    const year = sanctionDate.getFullYear()
    const yearData = filteredList.find(d => d.year === year)
    return yearData ? yearData.currentValue : defaultYValue
}

// 辅助函数：格式化文本内容，实现智能换行（考虑中英文混合）
function formatContent(content, maxWidth = 26) {
    if (!content) return ''

    const lines = []
    let currentLine = ''
    let currentWidth = 0

    // 中文字符宽度设为2，英文字符宽度设为1
    for (let i = 0; i < content.length; i++) {
        const char = content[i]
        const charWidth = /[\u4e00-\u9fa5]/.test(char) ? 2 : 1

        if (currentWidth + charWidth <= maxWidth) {
            currentLine += char
            currentWidth += charWidth
        } else {
            lines.push(currentLine)
            currentLine = char
            currentWidth = charWidth
        }
    }

    if (currentLine) {
        lines.push(currentLine)
    }

    return lines.join('\n')
}
function updateCharts(type, dataStudy, dataSanction) {
    const filteredList = dataStudy.filter(t => t.type === type)

    if (!filteredList.length) return

    // 销毁现有图表实例
    if (myChart) {
        myChart.dispose()
    }

    myChart = echarts.init(chartDom.value)

    // y轴单位
    const unit = filteredList[0].unit
    const yValue = Math.max(...filteredList.map(d => d.currentValue))

    // 计算x轴范围，扩大活动空间
    const allDates = [
        ...filteredList.map(t => t.time),
        ...dataSanction.map(t => t.time)
    ]
    const minDate = new Date(Math.min(...allDates))
    const maxDate = new Date(Math.max(...allDates))

    // 向前扩展1年，向后扩展1年
    minDate.setFullYear(minDate.getFullYear() - 1)
    maxDate.setFullYear(maxDate.getFullYear() + 1)

    myChart.setOption({
        textStyle: {
            fontSize: 14
        },
        grid: {
            left: 60,
            right: 110,
        },
        tooltip: {
            trigger: 'axis',
            position: function (pt) {
                return [pt[0], '10%'];
            },
        },
        dataZoom: [
            {
                type: 'inside',
                start: 0,
                end: 100
            },
            {
                start: 0,
                end: 100
            }
        ],
        xAxis: {
            type: 'time',
            boundaryGap: false,
            min: minDate,
            max: maxDate
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, '100%'],
            // 显示y轴单位在顶部
            name: unit,
            nameLocation: 'end'
        },
        series: [
            {
                type: 'line',
                //从上到下填充颜色
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(128, 181, 255, 0.8)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(128, 181, 255, 0)'
                        }
                    ])
                },
                data: filteredList.map(t => [t.time, t.currentValue])
            },
            {
                type: 'scatter',
                tooltip: { show: false },
                data: dataSanction.map(t => {
                    const currentYValue = getSanctionYValue(t.time, filteredList, yValue) + yValue / 3
                    return [t.time, currentYValue, t]
                }),
                markLine: {
                    lineStyle: {
                        color: '#ff4d4f',
                        type: 'dashed',
                        width: 1
                    },
                    data: dataSanction.map(t => {
                        const currentYValue = getSanctionYValue(t.time, filteredList, yValue) + yValue / 3
                        return [{
                            coord: [t.time, 0],
                            symbol: 'none'
                        }, {
                            coord: [t.time, currentYValue],
                            symbol: 'none',
                        }]
                    })
                },
                coordinateSystem: 'cartesian2d',
                symbolSize: 1,
                label: {
                    show: true,
                    position: 'insideBottomLeft',
                    formatter: function (params) {
                        const title = params.data[2].sanctionDate;
                        const content = params.data[2].content;
                        const formattedContent = formatContent(content);
                        return `{title|${title}}\n{content|${formattedContent}}`;
                    },
                    rich: {
                        title: {
                            fontSize: 16,
                            lineHeight: 22,
                            color: '#CE4F51'
                        },
                        content: {
                            fontSize: 15,
                            fontWeight: 'bold',
                            width: 200, // 限制宽度
                            color: '#CE4F51',
                            lineHeight: 22,
                            overflow: 'break' // 超出宽度自动换行
                        }
                    },
                    backgroundColor: 'rgba(255, 241, 240, 1)',
                    borderColor: 'rgba(255, 204, 199, 1)',
                    borderRadius: 4,
                    padding: [8, 12],
                    distance: -1
                }
            }
        ],

    })
}
function handleStudyTypesChange() {
    updateCharts(studyType.value, studyList.value, sanctionList.value)
}
</script>

<template>
    <analysis-box title="被制裁时间轴">
        <template v-slot:header-btn>
            <el-radio-group v-model="studyType" @change="handleStudyTypesChange">
                <el-radio-button v-for="item in studyTypes" :key="item" :label="item">{{ item }}</el-radio-button>
            </el-radio-group>
        </template>
        <div class="flex-display content-box">
            <div ref="chartDom" class="chart-container"></div>
            <ai-tip-pane>123</ai-tip-pane>
        </div>
    </analysis-box>
</template>

<style lang="scss" scoped>
.content-box {
    padding: 10px;
    gap: 10px;
    flex-direction: column;
}

.chart-container {
    height: 500px;
    width: 100%;
}
</style>