<template>
    <div class="drilling-chart-container" v-loading="loading">
        <!-- 最优值显示区域 - 左上角紧凑版 -->
        <div class="optimal-values">
            <div class="optimal-item">
                <span class="label">机速最优:</span>
                <span class="value">{{ (chartData && chartData.jxzszy) || '--' }}</span>
            </div>
            <div class="optimal-item">
                <span class="label">进尺最优:</span>
                <span class="value">{{ (chartData && chartData.jczy) || '--' }}</span>
            </div>
            <div class="optimal-item">
                <span class="label">综合最优:</span>
                <span class="value">{{ (chartData && chartData.zhzy) || '--' }}</span>
            </div>
        </div>
        <div id="drillingEfficiencyChartDJ" class="chart"></div>
    </div>
</template>

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

export default {
    props: {
        jh: {
            type: String,
            required: true,
        },
        jhs: {
            type: String,
            required: true,
        },
        zbid: {
            type: String,
            required: true,
        },
        qk: {
            type: String,
            required: true,
        },
        ztcc: {
            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 = { zbid: this.zbid, ztccs: this.ztcc, qk: this.qk };
            this.loading = true;
            getDjztqxt(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%;
    position: relative;
    padding: 20px;
    box-sizing: border-box;
}

.optimal-values {
    position: absolute;
    top: 15px;
    left: 10px;
    z-index: 10;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.95) 100%);
    border: 1px solid rgba(64, 158, 255, 0.15);
    border-radius: 4px;
    padding: 6px 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(8px);
    min-width: 120px;
    max-width: 150px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
}

.optimal-values:hover {
    box-shadow: 0 3px 12px rgba(0, 0, 0, 0.12), 0 1px 4px rgba(0, 0, 0, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.8);
    border-color: rgba(64, 158, 255, 0.25);
}

.optimal-item {
    display: block;
    margin-bottom: 3px;
    font-size: 14px;
    padding: 2px 4px;
    border-radius: 3px;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
    text-align: left;
}

.optimal-item:last-child {
    margin-bottom: 0;
}

.optimal-item:hover {
    background: linear-gradient(135deg, rgba(64, 158, 255, 0.08) 0%, rgba(103, 194, 58, 0.08) 100%);
    transform: translateX(2px);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.optimal-item::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 0;
    background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
    border-radius: 2px;
    transition: height 0.2s ease;
}

.optimal-item:hover::before {
    height: 60%;
}

.optimal-item .label {
    color: #5a5e66;
    font-weight: 500;
    margin-right: 6px;
    font-size: 12px;
    letter-spacing: 0.1px;
    opacity: 0.9;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
    display: inline;
}

.optimal-item .value {
    color: #2c3e50;
    font-weight: 700;
    font-size: 12px;
    background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    position: relative;
    word-wrap: break-word;
    word-break: break-all;
    white-space: normal;
    text-align: left;
    display: inline;
}

.optimal-item .value::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 1px;
    background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
    opacity: 0;
    transition: opacity 0.2s ease;
}

.optimal-item:hover .value::after {
    opacity: 0.3;
}

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