<template>
    <div class="box" v-loading="loading">
        <div>
            <div style="position: relative">
                <canvas ref="plot" style="height: 700px; width: 100%; position: relative" />

                <!-- 添加层位表头 -->
                <div style="position: absolute; top: 20px; left: 50px; 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 style="position: absolute; top: 5px; left: 450px; display: flex; margin-top: -4px; z-index: 2;">
                    <div style="display: flex; width: 80px;">
                        <div
                            style="width: 78px; 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";

export default {
    name: "cjqx",
    props: {
        jh: {
            type: String,
            required: true
        }
    },
    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()
                }
            }
        }
    },
    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 = '700px';
                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;
            getCjqxDatadcyx({ jh: this.jh }).then(res => {
                this.scale = res.scale;
                this.scale1 = res.scale1;
                this.curveData = {};

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

                // 处理其他指标数据
                this.curveData['单轴线压强度'] = this.filterValidData(this.processData(res.dzkyList, '单轴线压强度'), '单轴线压强度');
                this.curveData['岩石可钻性级值'] = this.filterValidData(this.processData(res.yskzxjzList, '岩石可钻性级值'), '岩石可钻性级值');
                this.curveData['研磨性系数'] = this.filterValidData(this.processData(res.ymzsList, '研磨性系数'), '研磨性系数');
                this.curveData['均质性系数'] = this.filterValidData(this.processData(res.cjzsList, '均质性系数'), '均质性系数');

                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);
            }

            // 均质性系数轨道
            const cjzsTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(80);
            const cjzsCurve = this.createCurve(0, 20, '均质性系数', 'orange');
            if (cjzsCurve !== null) {
                cjzsTrack.addChild(cjzsCurve);
            }

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

            widget.setLayoutStyle({
                'top': 0,
                'left': 0,
                'bottom': 0,
                'width': 1200
            });

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

            widget.fitToHeight();
            plot.getTool().add(widget.getTool());

            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((value, index) => {
                    const depth = this.scale1 + index * 0.5;

                    if (value && value !== currentLayer) {
                        if (currentLayer) {
                            layerRanges.push({
                                layer: currentLayer,
                                startDepth: startDepth,
                                endDepth: depth
                            });
                        }
                        currentLayer = value;
                        startDepth = depth;
                    }
                });

                if (currentLayer) {
                    layerRanges.push({
                        layer: currentLayer,
                        startDepth: startDepth,
                        endDepth: this.scale
                    });
                }

                return layerRanges;
            }

            const validData = [];
            data.forEach((value, index) => {
                if (value !== 0) {
                    validData.push({
                        depth: this.scale1 + index * 0.5,
                        value: value
                    });
                }
            });

            return validData.map(item => item.value);
        },

        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;
    min-height: 600px;
    overflow-y: auto;
}

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>