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

export interface LineDataItem {
    time: Date;
    value: number;
    type: string;
    unit: string;
}

// 定义组件属性
const props = defineProps({
    enterpriseInfo: {
        type: Object,
        default: {}
    },
    lineData: {
        type: Array<LineDataItem>,
        default: () => []
    }
});

const sanctionList = ref([])
const lineTypes = ref([])
const lineType = ref()
const chartDom = ref()

let myChart = null

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

onUnmounted(() => myChart?.dispose())

watch(() => [props.lineData, sanctionList.value], async () => {
    lineTypes.value = [...new Set(props.lineData.map(t => t.type))]
    if (lineTypes.value.length > 0) {
        lineType.value = lineTypes.value[0]
    }
    updateCharts(lineType.value, props.lineData, sanctionList.value)
})

async function intData() {
    const { data } = await getSanctionList(props.enterpriseInfo.id)
    sanctionList.value = data ?? []
    sanctionList.value.forEach(t => t.time = new Date(t.sanctionDate))
}

// 辅助函数：获取制裁年份对应的Y值
function getSanctionYValue(sanctionDate: Date, filteredList: LineDataItem[], defaultYValue: number) {
    const year = sanctionDate.getFullYear()
    const yearData = filteredList.find(d => d.time.getFullYear() === year)
    return yearData ? yearData.value : 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 getLineSeries(filteredList: LineDataItem[]) {
    return {
        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)'
                }
            ])
        },
        color: '#80B5FF',
        data: filteredList.map(t => [t.time, t.value])
    }
}

// 辅助函数：获取散点图数据
function getScatterSeries(filteredList: LineDataItem[], dataSanction: LineDataItem[], yValue: number) {
    // 计算散点图数据
    const xyData = dataSanction.map(t => {
        const currentYValue = getSanctionYValue(t.time, filteredList, yValue) + yValue / 3
        return [t.time, currentYValue, t]
    })
    return {
        type: 'scatter',
        tooltip: { show: false },
        data: xyData,
        // 绘制垂直虚线
        markLine: {
            lineStyle: {
                color: '#ff4d4f',
                type: 'dashed',
                width: 1
            },
            data: xyData.map(t => {
                return [{
                    coord: [t[0], 0],
                    symbol: 'none'
                }, {
                    coord: [t[0], t[1]],
                    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 updateCharts(type: string, dataStudy: LineDataItem[], dataSanction: LineDataItem[]) {
    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.value))

    // 计算x轴范围，扩大活动空间
    const allDates = [
        ...filteredList.map(t => t.time.getTime()),
        ...dataSanction.map(t => t.time.getTime())
    ]

    // 计算x轴范围，扩大活动空间
    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: [
            getScatterSeries(filteredList, dataSanction, yValue),
            getLineSeries(filteredList),
        ]

    })
}

// 辅助函数：处理研究类型改变事件
function handleStudyTypesChange() {
    updateCharts(lineType.value, props.lineData, sanctionList.value)
}
</script>

<template>
    <analysis-box title="被制裁时间轴">
        <template v-if="lineTypes.length > 1" v-slot:header-btn>
            <el-radio-group class="radio-group-as-gap-btn" v-model="lineType" @change="handleStudyTypesChange">
                <el-radio-button v-for="item in lineTypes" :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
                v-if="enterpriseInfo.id === '914403001922038216'">近年来，华为遭遇了严峻的外部技术封锁，其核心源于某些国家的持续制裁。这主要包括被列入“实体清单”，禁止其未经许可从美国公司获取芯片等关键技术；以及遭受更严格的“外国直接产品规则”打击，旨在切断其利用美国工具、软件和技术设计或制造先进芯片的渠道。这些措施不仅限制了华为自身产品的设计与生产，也影响了其全球供应链，使其在获取先进半导体、移动操作系统生态（如GMS）及基础软件工具等方面面临巨大挑战，意图从根本上遏制其技术发展。</ai-tip-pane>
        </div>
    </analysis-box>
</template>

<style lang="scss" scoped>
@use '@/styles/radio.scss';


.content-box {
    padding: 10px;
    gap: 10px;
    flex-direction: column;
}

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