<template>
    <div class="drilling-chart-container">
        <div v-if="jh" class="well-number-display">
            <span class="well-label">井号:</span>
            <span class="well-number">{{ jh }}</span>
        </div>
        <div class="chart-wrapper">
            <el-button type="primary" icon="el-icon-download" size="small" class="export-btn" @click="exportChart"
                :disabled="!myChart">
                导出图片
            </el-button>
            <div id="drillingEfficiencyChart" class="chart"></div>
        </div>
    </div>
</template>

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

export default {
    props: {
        jh: {
            type: String,
            required: true,
        }
    },
    data() {
        return {
            chartData: null,
            myChart: null,
            resizeHandler: null
        };
    },
    mounted() {
        this.getList();
        this.$once('hook:beforeDestroy', this.cleanup);
    },
    methods: {
        getList() {
            const params = { jhe: this.jh };
            getqxt(params)
                .then(res => {
                    console.log('接口返回数据:', res);
                    this.chartData = res;
                    this.initChart();
                })
                .catch(error => {
                    console.error('接口请求失败:', error);
                    this.chartData = null;
                    this.initChart();
                });
        },

        initChart() {
            if (!this.chartData) {
                const chartDom = document.getElementById('drillingEfficiencyChart');
                if (chartDom && this.myChart) {
                    this.myChart.clear();
                }
                return;
            }
            const chartDom = document.getElementById('drillingEfficiencyChart');
            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;
            // 数据顺序：[speed, depth, drillType, jh, cc]
            const scatter = scatterData.map(item => [item.speed, item.depth, item.drillType, item.jh, item.cc]);
            // 折线数据必须为数组格式：[[钻速, 进尺], ...]
            const targetLine = targetLineData.map(item => [item.speed, item.depth]);
            const drillTypes = [...new Set(scatterData.map(item => item.drillType))];
            const colorPalette = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#14b8a6', '#ec4899', '#6366f1', '#f97316', '#0ea5e9'];
            const typeColorMap = drillTypes.reduce((acc, type, index) => {
                acc[type] = colorPalette[index % colorPalette.length];
                return acc;
            }, {});

            // 十字线及中心点配置
            const crosshairLines = [];
            const crosshairCenter = [];
            if (crosshair) {
                crosshairLines.push({
                    name: '十字线',
                    type: 'line',
                    data: [[crosshair.y - 10, crosshair.x], [crosshair.y + 10, crosshair.x]],
                    lineStyle: { color: 'black', width: 1, type: 'dashed' },
                    symbol: 'none',
                    tooltip: { show: false } // 十字线不显示tooltip
                });
                crosshairLines.push({
                    name: '十字线',
                    type: 'line',
                    data: [[crosshair.y, crosshair.x - 500], [crosshair.y, crosshair.x + 500]],
                    lineStyle: { color: 'black', width: 1, type: 'dashed' },
                    symbol: 'none',
                    tooltip: { show: false } // 十字线不显示tooltip
                });
                crosshairCenter.push({
                    name: '十字线中心',
                    type: 'scatter',
                    data: [[crosshair.y, crosshair.x]],
                    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) {
                            const [speed, depth, drillType, jh, cc] = scatterData.data;
                            result += `井号：${jh}<br>机械钻速m/h：${speed} m/h<br>进尺m：${depth}<br>钻头型号：${drillType}<br>钻头尺寸mm：${cc}`;
                        }
                        // // 中心点数据（如果鼠标在中心点上）
                        // if (centerData) {
                        //     result += `均值<br>钻速：${centerData.data[0]} m/h<br>进尺：${centerData.data[1]}<br>`;
                        // }
                        return result;
                    }
                },
                legend: {
                    data: ['指标', '钻速均值', '进尺均值', '优化曲线',],
                    top: '10%',
                    right: '5%'
                },
                grid: {
                    left: '2%',
                    right: '5%',
                    top: '15%',
                    bottom: '10%',
                    containLabel: true
                },
                xAxis: {
                    name: '钻速 (m/h)',
                    type: 'value',
                    min: axisRange.xAxis.min,
                    max: axisRange.xAxis.max,
                    interval: axisRange.xAxis.interval,
                    axisLabel: { formatter: '{value} m/h' },
                    nameLocation: 'center',
                    nameGap: 30,
                    axisTick: { show: true },
                    axisLine: { show: true }
                },
                yAxis: {
                    name: '进尺',
                    type: 'value',
                    min: axisRange.yAxis.min,
                    interval: axisRange.yAxis.interval,
                    nameLocation: 'center',
                    nameGap: 40,
                    axisTick: { show: true },
                    axisLine: { show: true }
                },
                series: [
                    {
                        name: '优化曲线',
                        type: 'line',
                        data: targetLine, // 确保数据正确
                        smooth: true,
                        // 彻底隐藏所有点（包括悬浮时）
                        symbol: 'none',
                        showSymbol: false,
                        emphasis: { showSymbol: false },
                        lineStyle: { color: 'red', width: 2 }
                    },
                    {
                        name: '钻速均值',
                        type: 'line',
                        data: [[crosshair.x, axisRange.yAxis.min], [crosshair.x, axisRange.yAxis.max]],
                        lineStyle: { color: '#9eca7f', width: 2, type: 'dashed' },
                        symbol: 'none',
                        tooltip: { show: false }
                    },
                    {
                        name: '进尺均值',
                        type: 'line',
                        data: [[crosshair.x - 500, crosshair.y], [crosshair.x + 500, crosshair.y]],
                        lineStyle: { color: '#f2ca6b', width: 2 },
                        symbol: 'none',
                        tooltip: { show: false }
                    },
                    ...crosshairLines,
                    ...crosshairCenter,
                    ...drillTypes.map(type => {
                        const color = typeColorMap[type];
                        return {
                            name: type,
                            type: 'scatter',
                            data: scatter.filter(item => item[2] === type),
                            symbolSize: 12,
                            itemStyle: {
                                color,
                                borderColor: color,
                                borderWidth: 3,
                                shadowColor: color,
                                shadowBlur: 8
                            },
                            label: {
                                show: true,
                                position: 'top',
                                formatter: type,
                                fontSize: 10,
                                color
                            }
                        };
                    })
                ]
            };

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

        exportChart() {
            if (!this.myChart) {
                this.$message.warning('图表未初始化，无法导出');
                return;
            }
            try {
                // 获取图表的 base64 图片数据
                const url = this.myChart.getDataURL({
                    type: 'png',
                    pixelRatio: 2, // 提高图片清晰度
                    backgroundColor: '#fff'
                });

                // 创建下载链接
                const link = document.createElement('a');
                link.href = url;
                link.download = `钻头钻进能效分析_${this.jh}_${new Date().getTime()}.png`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                this.$message.success('图片导出成功');
            } catch (error) {
                console.error('导出图片失败:', error);
                this.$message.error('导出图片失败，请重试');
            }
        },

        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;
    box-sizing: border-box;
}

.well-number-display {
    position: absolute;
    top: 20px;
    left: 10px;
    z-index: 10;
    /* background: white; */
    padding: 4px 8px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.well-number-label {
    color: #606266;
    font-weight: normal;
    font-size: 12px;
    margin-right: 4px;
}

.well-number-value {
    color: #409EFF;
    font-weight: bold;
    font-size: 13px;
    text-shadow: 0 0 2px rgba(64, 158, 255, 0.3);
    position: relative;
}

.well-number-value::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(64, 158, 255, 0.1) 0%, rgba(64, 158, 255, 0.05) 100%);
    border-radius: 2px;
    z-index: -1;
}

.optimal-values {
    position: absolute;
    top: 5px;
    left: 5px;
    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: 4px 8px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(6px);
    min-width: 120px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

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

.optimal-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2px;
    font-size: 10px;
    padding: 1px 4px;
    border-radius: 3px;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
}

.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: 10px;
    letter-spacing: 0.1px;
    opacity: 0.9;
}

.optimal-item .value {
    color: #2c3e50;
    font-weight: 700;
    font-size: 10px;
    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;
}

.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-wrapper {
    position: relative;
    width: 100%;
    height: calc(100vh - 230px);
    min-height: 600px;
}

.chart {
    width: 100%;
    height: 100%;
}

.export-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 100;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 井号显示样式 */
.well-number-display {
    position: absolute;
    top: 16px;
    left: 16px;
    z-index: 5;
    background: transparent;
    padding: 8px 12px;
    display: flex;
    align-items: center;
    gap: 6px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    transition: all 0.3s ease;
    opacity: 0.9;
}

.well-number-display:hover {
    opacity: 1;
}

.well-label {
    color: #6b7280;
    font-size: 13px;
    font-weight: 500;
    white-space: nowrap;
}

.well-number {
    color: #3b82f6;
    font-size: 14px;
    font-weight: 600;
}
</style>