<template>
    <div class="box" v-loading="loading">
        <div>
            <div style="position: relative; height: 100%; width: 100%;">
                <canvas ref="plot" style="height: 100%; width: 100%; position: relative" />
                <!-- 添加层位表头 -->
                <div style="position: absolute; top: 20px; left: 90px; display: flex;margin-top: -4px;">
                    <div style="display: flex; width: 100px;">
                        <div
                            style="width: 70px; align-items: center; justify-content: center; font-size: 10px; font-weight: bold;">
                            层位
                        </div>
                    </div>
                </div>

                <!-- 添加单轴线压强度表头 -->
                <div style="position: absolute; top: 5px; left: 150px; display: flex; margin-top: -4px; z-index: 2;">
                    <div style="display: flex; width: 100px;">
                        <div
                            style="width: 98px; height: 20px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: bold; background-color: #f3f8ff;">
                            抗剪强度
                        </div>
                    </div>
                </div>

                <!-- 添加岩石可钻性级值表头 -->
                <div style="position: absolute; top: 5px; left: 250px; display: flex; margin-top: -4px; z-index: 2;">
                    <div style="display: flex; width: 100px;">
                        <div
                            style="width: 98px; height: 20px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: bold; background-color: #f3f8ff;">
                            抗压强度
                        </div>
                    </div>
                </div>

                <!-- 添加研磨性系数表头 -->
                <div style="position: absolute; top: 5px; left: 350px; display: flex; margin-top: -4px; z-index: 2;">
                    <div style="display: flex; width: 100px;">
                        <div
                            style="width: 98px; height: 20px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: bold; background-color: #f3f8ff;">
                            内摩擦角
                        </div>
                    </div>
                </div>

            </div>
            <div id="tooltip-container" style="display: none;position: absolute"></div>
        </div>
    </div>
</template>

<script>
import { ComponentNodeFactoryRegistry } from '@int/geotoolkit/schematics/factory/ComponentNodeFactoryRegistry';
import { v3 as WellLogWidget } from '@int/impl/geotoolkit.welllog.widgets.js';
import { LogAbstractVisual } from '@int/geotoolkit/welllog/LogAbstractVisual';
import { WellBoreNode } from '@int/geotoolkit/schematics/scene/WellBoreNode';
import { TrackType } from '@int/geotoolkit/welllog/TrackType';
import { HeaderType } from '@int/geotoolkit/welllog/header/LogAxisVisualHeader';
import { LogData } from '@int/geotoolkit/welllog/data/LogData';
import { LogCurve } from '@int/geotoolkit/welllog/LogCurve';
import { Group } from '@int/geotoolkit/scene/Group';
import { CssLayout } from '@int/geotoolkit/layout/CssLayout';
import { Plot } from '@int/geotoolkit/plot/Plot';
import { MathUtil } from '@int/geotoolkit/util/MathUtil';
import { LogMudLogSection } from '@int/geotoolkit/welllog/LogMudLogSection';
import { Text } from '@int/geotoolkit/scene/shapes/Text';
import { getCjqxDatadcyx } from "@/api/system/cjsjLas";
import { CssStyle } from '@int/geotoolkit/css/CssStyle';

export default {
    name: "cjqx",
    props: {
        jh: {
            type: String,
            required: true
        },
        ksjs: {
            type: [String, Number],
            default: ''
        },
        jsjs: {
            type: [String, Number],
            default: ''
        }
    },
    data() {
        return {
            loading: false,
            curveData: {},
            scale: '',
            scale1: '',
            layerColors: {},
            uniqueLayers: [],
            predefinedColors: [
                '#fbd860', '#f3a43a', '#5fc0de', '#d74f4a', '#c6e679',
                '#fce913',
            ]
        }
    },
    mounted() {
        this.onSearch()
    },
    watch: {
        jh: {
            handler(newVal) {
                if (newVal) {
                    this.onSearch()
                }
            }
        },
        ksjs: {
            handler() {
                if (this.jh) {
                    this.onSearch()
                }
            }
        },
        jsjs: {
            handler() {
                if (this.jh) {
                    this.onSearch()
                }
            }
        }
    },
    methods: {
        onSearch() {
            const canvas = this.$refs.plot;
            if (!canvas) {
                console.warn('Canvas element not found, skipping canvas manipulation');
                // this.getWelllogData();
                return;
            }

            const parent = canvas.parentElement;
            if (canvas && parent) {
                parent.removeChild(canvas);
                this.newCanvas = document.createElement('canvas');
                this.newCanvas.style.height = '100%';
                this.newCanvas.style.width = '100%';
                this.newCanvas.style.position = 'relative';
                this.newCanvas.setAttribute('ref', 'plot');
                parent.appendChild(this.newCanvas);
                this.$refs.plot = this.newCanvas;
            }
            this.getWelllogData()
        },

        getWelllogData() {
            this.loading = true;
            const params = {
                jh: this.jh
            };
            // 如果有开始深度和结束深度参数，添加到请求中
            if (this.ksjs) {
                params.ksjs = this.ksjs;
            }
            if (this.jsjs) {
                params.jsjs = this.jsjs;
            }
            getCjqxDatadcyx(params).then(res => {
                this.scale = res.scale;
                this.scale1 = res.scale1;
                this.curveData = {};

                // 处理层位数据
                this.curveData['层位'] = this.filterValidData(this.processData(res.cwList2, '层位'), '层位');
                this.processLayerData(this.curveData['层位']);

                // 处理其他指标数据
                this.curveData['抗剪强度'] = this.filterValidData(this.processData(res.kjqdList, '抗剪强度'), '抗剪强度');
                this.curveData['抗压强度'] = this.filterValidData(this.processData(res.kyqdList, '抗压强度'), '抗压强度');
                this.curveData['内摩擦角'] = this.filterValidData(this.processData(res.nmcjList, '内摩擦角'), '内摩擦角');

                this.createScene(this.$refs.plot);
            }).catch(error => {
                console.error('获取数据失败:', error);
                this.$message.error('获取数据失败');
            }).finally(() => {
                this.loading = false;
            });
        },

        createScene(canvas) {
            const widget = new WellLogWidget({
                'header': { 'visible': true },
                'footer': { 'visible': false },
                'border': { 'visible': true },
                'horizontalscrollable': false,
                'verticalscrollable': false,
                'nodefilter': (node) => node instanceof LogAbstractVisual || node instanceof WellBoreNode
            })
                .setAxisHeaderType(HeaderType.Simple)
                .setHeaderHeight(90)
                .setIndexUnit('m');

            widget.setDepthLimits(this.scale1, this.scale);
            this.applyModernThemeCSS(widget);
            widget.addTrack(TrackType.IndexTrack);

            // 层位轨道
            const layerTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100)
                .addChild(
                    new Group()
                        .setLayout(new CssLayout())
                        .setLayoutStyle({
                            'left': '0%',
                            'right': '0%',
                            'top': '-45px',
                            'height': '45px'
                        })
                );

            if (this.curveData['层位'] && Array.isArray(this.curveData['层位']) && this.curveData['层位'].length > 0) {
                layerTrack.addChild(
                    new Group()
                        .setLayout(new CssLayout())
                        .addChild(
                            new LogMudLogSection({
                                'fillstyles': (depth, text, i) => {
                                    const layerInfo = this.curveData['层位'].find(
                                        range => depth >= range.startDepth && depth < range.endDepth
                                    );
                                    return layerInfo ? this.layerColors[layerInfo.layer] : '#FFFFFF';
                                },
                                'textstyles': {
                                    'color': '#FFFFFF !important',
                                    'font': 'bold 14px Arial',
                                    'alignment': 'center',
                                    'baseline': 'middle',
                                    'angle': 0,
                                    'css': {
                                        'writing-mode': 'vertical-rl',
                                        'text-orientation': 'upright',
                                        'white-space': 'nowrap',
                                        'text-shadow': '1px 1px 2px rgba(0,0,0,0.8)',
                                        'color': '#FFFFFF !important'
                                    }
                                },
                                'displaytext': (depth, text) => {
                                    const layerInfo = this.curveData['层位'].find(
                                        range => depth >= range.startDepth && depth < range.endDepth
                                    );
                                    if (!layerInfo) return '';
                                    return `<div style="color: white !important; font-weight: bold; font-size: 14px; writing-mode: vertical-rl; text-orientation: upright; text-shadow: 1px 1px 3px black; width: 100%; text-align: center;">${layerInfo.layer}</div>`;
                                },
                                'textposition': 'center',
                                'textoptions': {
                                    'horizontaloffset': 0,
                                    'sectionheight': 20,
                                    'verticaloffset': 0,
                                    'wordwrap': false,
                                    'useHTML': true
                                }
                            })
                                .setDepthsAndValues(
                                    this.curveData['层位'].reduce((acc, layer) => {
                                        acc.push(layer.startDepth);
                                        acc.push(layer.endDepth);
                                        return acc;
                                    }, []),
                                    this.curveData['层位'].reduce((acc, layer) => {
                                        acc.push(layer.layer);
                                        acc.push(layer.layer);
                                        return acc;
                                    }, [])
                                )
                                .setEllipsisString('')
                        )
                );
            }

            // 单轴线压强度轨道
            const dzkTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100);
            const dzkCurve = this.createCurve(0, 20, '抗剪强度', 'orange');
            if (dzkCurve !== null) {
                dzkTrack.addChild(dzkCurve);
            }

            // 岩石可钻性级值轨道
            const yskzTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100);
            const yskzCurve = this.createCurve(0, 20, '抗压强度', 'orange');
            if (yskzCurve !== null) {
                yskzTrack.addChild(yskzCurve);
            }

            // 研磨性系数轨道
            const ymzsTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100);
            const ymzsCurve = this.createCurve(0, 20, '内摩擦角', '#7cb342');
            if (ymzsCurve !== null) {
                ymzsTrack.addChild(ymzsCurve);
            }

            // 添加层位图例
            this.addLayerLegend(widget);

            widget.setLayoutStyle({
                'top': 0,
                'left': 0,
                'bottom': 0,
                'right': 0,
                'width': '100%',
                'height': '100%'
            });

            const plot = new Plot({
                'canvasElement': canvas,
                'autosize': false,
                'root': widget
            });

            widget.fitToHeight();

            // 添加 widget 的工具到 plot 以支持 tooltip 等交互功能
            // 拖拽功能将通过事件监听来阻止
            try {
                const widgetTool = widget.getTool();
                if (widgetTool) {
                    plot.getTool().add(widgetTool);
                }
            } catch (e) {
                console.warn('无法添加 widget 工具:', e);
            }

            // 通过事件监听阻止拖拽，但保留鼠标悬浮功能
            const canvasElement = canvas;
            const headerHeight = 120; // header 高度，稍微大一点确保覆盖
            let isDragging = false; // 标记是否正在拖拽
            let dragStartPos = null; // 拖拽起始位置

            // 判断是否在 header 区域
            const isInHeaderArea = (e) => {
                const rect = canvasElement.getBoundingClientRect();
                const y = e.clientY - rect.top;
                return y < headerHeight;
            };

            // 阻止拖拽相关的事件
            const blockDragStart = (e) => {
                if (e.type === 'mousedown') {
                    // 在header区域阻止拖拽
                    if (isInHeaderArea(e)) {
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                    }
                    // 其他区域也阻止拖拽，但允许点击等交互
                    dragStartPos = { x: e.clientX, y: e.clientY };
                    isDragging = false;
                }
            };

            const blockDragMove = (e) => {
                if (e.type === 'mousemove' && dragStartPos) {
                    // 如果鼠标移动距离超过阈值，认为是拖拽
                    const deltaX = Math.abs(e.clientX - dragStartPos.x);
                    const deltaY = Math.abs(e.clientY - dragStartPos.y);
                    if (deltaX > 5 || deltaY > 5) {
                        isDragging = true;
                        // 阻止拖拽
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                    }
                }
            };

            const blockDragEnd = (e) => {
                if (e.type === 'mouseup') {
                    if (isDragging) {
                        // 如果正在拖拽，阻止mouseup事件
                        e.preventDefault();
                        e.stopPropagation();
                        e.stopImmediatePropagation();
                        return false;
                    }
                    dragStartPos = null;
                    isDragging = false;
                }
            };

            // 阻止所有拖动事件
            const blockDragEventsAll = (e) => {
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
                return false;
            };

            // 使用捕获阶段，设置为非 passive，确保可以阻止默认行为
            const eventOptions = { capture: true, passive: false };

            // 阻止拖拽相关的事件，但不阻止 mousemove（用于tooltip）
            // 注意：mousemove事件只在检测到拖拽时才阻止，否则允许用于tooltip
            canvasElement.addEventListener('mousedown', blockDragStart, eventOptions);
            canvasElement.addEventListener('mousemove', blockDragMove, eventOptions);
            canvasElement.addEventListener('mouseup', blockDragEnd, eventOptions);

            // 阻止所有拖动事件
            canvasElement.addEventListener('dragstart', blockDragEventsAll, eventOptions);
            canvasElement.addEventListener('drag', blockDragEventsAll, eventOptions);
            canvasElement.addEventListener('dragend', blockDragEventsAll, eventOptions);
            canvasElement.addEventListener('dragover', blockDragEventsAll, eventOptions);
            canvasElement.addEventListener('drop', blockDragEventsAll, eventOptions);

            // 阻止 header 区域的点击事件
            canvasElement.addEventListener('click', (e) => {
                if (isInHeaderArea(e)) {
                    e.preventDefault();
                    e.stopPropagation();
                }
            }, eventOptions);

            // 通过 CSS 禁用用户选择
            canvasElement.style.userSelect = 'none';
            canvasElement.style.webkitUserSelect = 'none';
            canvasElement.style.mozUserSelect = 'none';
            canvasElement.style.msUserSelect = 'none';
            canvasElement.style.pointerEvents = 'auto'; // 确保事件可以捕获

            return plot;
        },

        addLayerLegend(widget) {
            const legendGroup = new Group()
                .setLayout(new CssLayout())
                .setLayoutStyle({
                    'position': 'absolute',
                    'top': '10px',
                    'right': '10px',
                    'background': 'rgba(255, 255, 255, 0.9)',
                    'padding': '10px',
                    'border': '1px solid #ccc',
                    'borderRadius': '4px',
                    'width': '120px'
                });

            const legendTitle = new Text({
                text: '层位图例',
                textbaseline: 'top',
                textalign: 'left'
            })
                .setTextStyle({
                    'color': '#000000',
                    'font': 'bold 12px Roboto'
                })
                .setLayoutStyle({
                    'position': 'absolute',
                    'left': '5px',
                    'top': '5px'
                });
            legendGroup.addChild(legendTitle);

            this.uniqueLayers.forEach((layer, index) => {
                const legendItemGroup = new Group()
                    .setLayout(new CssLayout())
                    .setLayoutStyle({
                        'position': 'absolute',
                        'left': '5px',
                        'top': `${index * 25 + 30}px`,
                        'width': '110px',
                        'height': '20px'
                    });

                const colorBox = new Group()
                    .setLayout(new CssLayout())
                    .setLayoutStyle({
                        'position': 'absolute',
                        'left': '0px',
                        'top': '2px',
                        'width': '15px',
                        'height': '15px',
                        'background': this.layerColors[layer],
                        'border': '1px solid #ccc'
                    });

                const legendText = new Text({
                    text: layer,
                    textbaseline: 'top',
                    textalign: 'left'
                })
                    .setTextStyle({
                        'color': '#000000',
                        'font': '10px Roboto'
                    })
                    .setLayoutStyle({
                        'position': 'absolute',
                        'left': '25px',
                        'top': '2px'
                    });

                legendItemGroup.addChild(colorBox);
                legendItemGroup.addChild(legendText);
                legendGroup.addChild(legendItemGroup);
            });

            widget.addChild(legendGroup);
        },

        applyModernThemeCSS(widget) {
            widget.setCss(new CssStyle({
                'css': [
                    '* {',
                    '  textstyle-font : 10px Roboto;',
                    '  textstyle-color : #000;',
                    '}',
                    '.geotoolkit.welllog.header.AdaptiveLogCurveVisualHeader {',
                    '   element-tracking-textstyle-font : bold 10px Roboto;',
                    '   element-tracking-textstyle-color : #000;',
                    '}',
                    '.geotoolkit.welllog.header.LogTrackHeader {',
                    '   borderfillstyle-style: lineargradient;',
                    '   borderfillstyle-unittype: absoluteCoordinates;',
                    '   borderfillstyle-startpoint-x: 0;',
                    '   borderfillstyle-startpoint-y: 0;',
                    '   borderfillstyle-startcolor: rgba(255, 255, 255, 0);',
                    '   borderfillstyle-endpoint-x: 0;',
                    '   borderfillstyle-endpoint-y: 500;',
                    '   borderfillstyle-endcolor: rgba(255, 255, 255, 0);',
                    '   borderlinestyle: null;',
                    '   isbordervisible: true;',
                    '   borders-left: true;',
                    '   borders-top: true;',
                    '   borders-right: true;',
                    '   borders-bottom: true;',
                    '}',
                    '.geotoolkit.welllog.LogTrack {',
                    '   backgroundcolor-style: lineargradient;',
                    '   backgroundcolor-unittype: absoluteCoordinates;',
                    '   backgroundcolor-startpoint-x: 0;',
                    '   backgroundcolor-startpoint-y: 0;',
                    '   backgroundcolor-startcolor: rgba(255, 255, 255, 0);',
                    '   backgroundcolor-endpoint-x: 0;',
                    '   backgroundcolor-endpoint-y: 500;',
                    '   backgroundcolor-endcolor: rgba(255, 255, 255, 0);',
                    '   clipping : true;',
                    '   borderstrategy: top;',
                    '   border-visible : true;',
                    '   border-borderstyle: visible-bounds;',
                    '   border-linestyle-color: #000;',
                    '   border-linestyle-weight: blod;',
                    '   border-linestyle-pixelsnapmode-x: true;',
                    '   border-linestyle-pixelsnapmode-y: true;',
                    '   border-borders-left : true;',
                    '   border-borders-right : true;',
                    '   border-borders-top : true;',
                    '   border-borders-bottom : true;',
                    '}',
                    '.geotoolkit.welllog.LogAxis {',
                    '   tickgenerator-major-labelstyle-color: red;',
                    '   tickgenerator-major-labelstyle-font: 10px Roboto;',
                    '   tickgenerator-major-tickstyle-color: #C8C8C8;',
                    '   tickgenerator-major-tickstyle-width: 1;',
                    '   tickgenerator-major-tickstyle-pixelsnapmode-x: true;',
                    '   tickgenerator-major-tickstyle-pixelsnapmode-y: true;',
                    '   tickgenerator-minor-tickstyle-color: #646464;',
                    '   tickgenerator-edge-labelstyle-color: red;',
                    '   tickgenerator-edge-tickstyle-color: #EFFFFF;',
                    '   tickgenerator-edge-labelstyle-font: 10px Roboto;',
                    '}',
                    '.geotoolkit.welllog.LogCurve:highlight {',
                    '   linestyle-width: 2;',
                    '   linestyle-shadow-enable: true;',
                    '   linestyle-shadow-blur: 2;',
                    '   linestyle-shadow-offsetx: 0;',
                    '   linestyle-shadow-offsety: 0;',
                    '}',
                    '.geotoolkit.welllog.LogTrack:highlight {',
                    '   borderstrategy: top;',
                    '   linestyle-color: grey;',
                    '   linestyle-width: 2;',
                    '   linestyle-shadow-enable: true;',
                    '   linestyle-shadow-blur: 2;',
                    '   linestyle-shadow-offsetx: 0;',
                    '   linestyle-shadow-offsety: 0;',
                    '}'
                ].join('')
            }))
        },

        processData(data, key) {
            if (!data) {
                console.warn(`${key} 数据为空`);
                return [];
            }
            if (Array.isArray(data)) {
                return data;
            }
            console.warn(`${key} 数据格式不正确:`, data);
            return [];
        },

        filterValidData(data, name) {
            if (!data || !Array.isArray(data)) {
                console.warn(`${name} 数据无效或为空`);
                return [];
            }

            if (name === '层位') {
                if (!data || !Array.isArray(data)) {
                    console.warn('层位数据无效或为空');
                    return [];
                }

                const layerRanges = [];
                let currentLayer = null;
                let startDepth = null;

                // 修改这里以适应新的数据格式
                data.forEach((item) => {
                    if (item.cw && item.cw !== currentLayer) {
                        if (currentLayer) {
                            layerRanges.push({
                                layer: currentLayer,
                                startDepth: startDepth,
                                endDepth: item.dept
                            });
                        }
                        currentLayer = item.cw;
                        startDepth = item.dept;
                    }
                });

                // 处理最后一个层位
                if (currentLayer) {
                    layerRanges.push({
                        layer: currentLayer,
                        startDepth: startDepth,
                        endDepth: this.scale
                    });
                }

                return layerRanges;
            }

            // 对于非层位数据，直接返回原始数组，保留所有数据点（包括0值）
            // 这样可以确保深度和值的对应关系正确
            return data;
        },

        createCurve(from, step, curveMnemonic, color) {
            try {
                if (!this.curveData) {
                    console.warn('curveData 对象不存在');
                    return null;
                }

                const values = this.curveData[curveMnemonic];
                if (!values || !Array.isArray(values) || values.length === 0) {
                    console.warn(`${curveMnemonic} 的数据无效:`, values);
                    return null;
                }

                const depths = Array.from({ length: values.length }, (_, i) => from + i * step);
                const data = new LogData(depths, values);
                const limits = MathUtil.calculateNeatLimits(data.getMinValue(), data.getMaxValue(), false, false);

                return new LogCurve(data)
                    .setName(curveMnemonic)
                    .setNormalizationLimits(limits)
                    .setLineStyle({
                        'color': color,
                        'width': 1
                    });
            } catch (e) {
                console.error(`创建曲线 ${curveMnemonic} 时出错:`, e);
                return null;
            }
        },

        generateRandomColor(index) {
            if (index < this.predefinedColors.length) {
                return this.predefinedColors[index];
            }

            const letters = '0123456789ABCDEF';
            let color = '#';
            for (let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        },

        processLayerData(layerRanges) {
            if (!layerRanges || !Array.isArray(layerRanges) || layerRanges.length === 0) {
                this.uniqueLayers = [];
                this.layerColors = {};
                return { uniqueLayers: [], layerColors: {}, layerRanges: [] };
            }

            const uniqueLayers = [...new Set(layerRanges.map(item => item.layer))];
            const layerColors = {};
            uniqueLayers.forEach((layer, index) => {
                const color = this.generateRandomColor(index);
                this.$set(layerColors, layer, color);
            });

            this.uniqueLayers = uniqueLayers;
            this.layerColors = layerColors;

            return { uniqueLayers, layerColors, layerRanges };
        }
    }
};
</script>

<style lang="scss" scoped>
.image {
    width: 100%;
    height: 450px;
}

@media screen and (min-width: 1400px),
screen and (min-height: 800px) {
    .image {
        height: 650px;
    }
}

.box {
    margin: 0 5px;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    >div {
        flex: 1;
        overflow: hidden;
    }
}

div#tooltip-container {
    z-index: 100;
    margin-left: 5px;
    opacity: 1;
    text-align: left;
    color: rgb(73, 73, 73);
    padding-left: 5px;
    padding-right: 5px;
    background: rgba(255, 255, 204, 0.5);
    border-radius: 4px;
    border-width: 1px;
    border-style: solid;
    border-color: grey;
    border-image: initial;
    width: 150px;
}
</style>