<template>
    <div class="drilling-chart-container" v-loading="loading">
        <div id="drillingEfficiencyChartdj" class="chart"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import { getdjqxt } from '@/api/optimization/initialization';

export default {
    props: {
        jh: {
            type: String,
            required: true,
        },
        jhs: {
            type: String,
            required: true,
        }
    },
    data() {
        return {
            chartData: null,
            myChart: null,
            resizeHandler: null,
            loading: false // 新增loading状态
        };
    },
    mounted() {
        // this.getList(); // 移除自动加载
        this.$once('hook:beforeDestroy', this.cleanup);
    },
    methods: {
        /**
         * 外部调用：加载数据
         */
        loadData() {
            this.loading = true;
            this.getList();
        },

        getList() {
            const params = {
                jhs: `${this.jh},${this.jhs}`
            };
            this.loading = true;
            getdjqxt(params)
                .then(res => {
                    console.log('接口返回数据:', res);
                    this.chartData = res;
                    this.initChart();
                })
                .catch(error => {
                    console.error('接口请求失败:', error);
                    this.chartData = null;
                    this.initChart();
                })
                .finally(() => {
                    this.loading = false;
                });
        },

        initChart() {
            if (!this.chartData) {
                const chartDom = document.getElementById('drillingEfficiencyChartdj');
                if (chartDom && this.myChart) {
                    this.myChart.clear();
                }
                return;
            }

            const chartDom = document.getElementById('drillingEfficiencyChartdj');
            if (!chartDom) {
                console.error('未找到图表容器');
                return;
            }

            if (chartDom.offsetWidth === 0 || chartDom.offsetHeight === 0) {
                console.log('容器尺寸为0，200ms后重试');
                setTimeout(() => this.initChart(), 200);
                return;
            }

            if (this.myChart) {
                this.myChart.dispose();
            }
            this.myChart = echarts.init(chartDom);

            // 解析接口数据（确保折线数据格式正确）
            const { axisRange, scatterData, targetLineData, crosshair } = this.chartData;
            const scatter = scatterData.map(item => [item.speed, item.depth, item.drillType]);
            // 折线数据必须为数组格式：[[钻速, 进尺], ...]
            const targetLine = targetLineData.map(item => [item.speed, item.depth]);
            const drillTypes = [...new Set(scatterData.map(item => item.drillType))];

            // 十字线及中心点配置
            const crosshairLines = [];
            const crosshairCenter = [];
            if (crosshair) {
                crosshairLines.push({
                    name: '十字线',
                    type: 'line',
                    data: [[crosshair.x - 10, crosshair.y], [crosshair.x + 10, crosshair.y]],
                    lineStyle: { color: 'black', width: 1, type: 'dashed' },
                    symbol: 'none',
                    tooltip: { show: false } // 十字线不显示tooltip
                });
                crosshairLines.push({
                    name: '十字线',
                    type: 'line',
                    data: [[crosshair.x, crosshair.y - 500], [crosshair.x, crosshair.y + 500]],
                    lineStyle: { color: 'black', width: 1, type: 'dashed' },
                    symbol: 'none',
                    tooltip: { show: false } // 十字线不显示tooltip
                });
                crosshairCenter.push({
                    name: '十字线中心',
                    type: 'scatter',
                    data: [[crosshair.x, crosshair.y]],
                    symbolSize: 12,
                    itemStyle: { color: 'orange', borderColor: '#fff', borderWidth: 2 }
                });
            }

            // 图表配置项（核心：坐标轴触发，确保折线悬浮显示）
            const option = {
                title: { text: '钻头钻进能效分析', left: 'center' },
                tooltip: {
                    trigger: 'axis', // 基于坐标轴触发（不依赖数据点）
                    axisPointer: {
                        type: 'line', // 显示轴线指示器，辅助定位折线数据点
                        snap: true // 强制吸附到最近的折线数据点
                    },
                    formatter: (params) => {
                        // 遍历所有系列数据，找到折线图的信息
                        const lineData = params.find(p => p.seriesName === '优化曲线');
                        const scatterData = params.find(p => drillTypes.includes(p.seriesName));
                        const centerData = params.find(p => p.seriesName === '十字线中心');

                        let result = '';
                        // 折线图数据（必显）
                        if (lineData) {
                            result += `优化曲线<br>钻速：${lineData.data[0]} m/h<br>进尺：${lineData.data[1]}<br>`;
                        }
                        // 散点数据（如果鼠标在散点上）
                        if (scatterData) {
                            result += `钻头类型：${scatterData.data[2]}<br>钻速：${scatterData.data[0]} m/h<br>进尺：${scatterData.data[1]}<br>`;
                        }
                        // 中心点数据（如果鼠标在中心点上）
                        if (centerData) {
                            result += `均值<br>钻速：${centerData.data[0]} m/h<br>进尺：${centerData.data[1]}<br>`;
                        }
                        return result;
                    }
                },
                legend: {
                    data: ['优化曲线',],
                    top: '10%',
                    left: 'center'
                },
                xAxis: {
                    name: '钻速 (m/h)',
                    type: 'value',
                    min: axisRange.xAxis.min,
                    max: axisRange.xAxis.max,
                    interval: axisRange.xAxis.interval,
                    axisLabel: { formatter: '{value} m/h' }
                },
                yAxis: {
                    name: '进尺m',
                    type: 'value',
                    min: axisRange.yAxis.min,
                    interval: axisRange.yAxis.interval
                },
                series: [
                    {
                        name: '优化曲线',
                        type: 'line',
                        data: targetLine, // 确保数据正确
                        smooth: true,
                        // 彻底隐藏所有点（包括悬浮时）
                        symbol: 'none',
                        showSymbol: false,
                        emphasis: { showSymbol: false },
                        lineStyle: { color: 'red', width: 2 }
                    },
                    ...crosshairLines,
                    ...crosshairCenter,
                    ...drillTypes.map(type => ({
                        name: type,
                        type: 'scatter',
                        data: scatter.filter(item => item[2] === type),
                        symbolSize: 10,
                        itemStyle: { color: 'blue' }
                    }))
                ]
            };

            this.myChart.setOption(option);

            this.resizeHandler = () => this.myChart.resize();
            window.addEventListener('resize', this.resizeHandler);
        },

        cleanup() {
            if (this.myChart) {
                this.myChart.dispose();
                this.myChart = null;
            }
            if (this.resizeHandler) {
                window.removeEventListener('resize', this.resizeHandler);
                this.resizeHandler = null;
            }
        }
    }
};
</script>

<style scoped>
.drilling-chart-container {
    width: 100%;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
}

.chart {
    width: 100%;
    height: calc(100vh - 220px);
    min-height: 600px;
}
</style>