<template>
    <div class="formation-curve-chart" v-loading="loading">
        <!-- 图表控制区域 -->
        <div class="chart-controls">
            <div class="control-item">
                <label>井深范围(m):</label>
                <el-input v-model="chartForm.startDepth" placeholder="起始深度" style="width: 150px; margin-right: 10px;" />
                <span>-</span>
                <el-input v-model="chartForm.endDepth" placeholder="结束深度" style="width: 150px; margin-left: 10px;" />
            </div>

            <div class="action-buttons">
                <el-button type="primary" size="small" @click="handleRefreshChart">查询</el-button>
                <el-button type="success" size="small" @click="handleCalculate">计算</el-button>
                <el-button type="danger" size="small" @click="handleExportData">下载数据文档</el-button>
                <el-button type="success" size="small" @click="handleNeighborWell">邻井映射</el-button>
            </div>
        </div>

        <!-- 图表展示区域 -->
        <div class="chart-container">
            <div style="position: relative">
                <canvas ref="plot" style="height: 700px; width: 100%; position: relative" />

                <!-- 表头区域 -->
                <div style="position: absolute; top: 5px; left: 50px; 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: 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 { WellBoreData } from '@int/geotoolkit/schematics/data/WellBoreData';
import { LogAbstractVisual } from '@int/geotoolkit/welllog/LogAbstractVisual';
import { WellBoreNode, ViewMode } from '@int/geotoolkit/schematics/scene/WellBoreNode';
import { TrackType } from '@int/geotoolkit/welllog/TrackType';
import { HeaderType } from '@int/geotoolkit/welllog/header/LogAxisVisualHeader';
import { Rect } from '@int/geotoolkit/util/Rect';
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 { AnchorType } from '@int/geotoolkit/util/AnchorType';
import { CssStyle } from '@int/geotoolkit/css/CssStyle';
import { TooltipTool } from '@/views/wellTest/wellCurveData/tooltipTool';
import { getCjqxDatadcyx } from "@/api/system/cjsjLas";
export default {
    name: 'FormationCurveChart',
    data() {
        return {
            loading: false,
            chartForm: {
                startDepth: '2603',
                endDepth: '6000'
            },
            plot: null,
            // 模拟数据
            curveData: {
                // 层位数据
                '层位': [
                    { layer: '八道湾组', startDepth: 2603, endDepth: 2900 },
                    { layer: '白碱滩组', startDepth: 2900, endDepth: 3200 },
                    { layer: '百口泉组', startDepth: 3200, endDepth: 5500 },
                    { layer: '下克拉玛依组', startDepth: 5500, endDepth: 6000 }
                ],
                // 单轴线压强度数据
                '单轴线压强度': Array.from({ length: 100 }, (_, i) => {
                    const depth = 2603 + i * 34;
                    return {
                        depth: depth,
                        value: 50 + Math.random() * 150 + Math.sin(depth / 100) * 20
                    };
                }),
                // 岩石可钻性级值数据
                '岩石可钻性级值': Array.from({ length: 100 }, (_, i) => {
                    const depth = 2603 + i * 34;
                    return {
                        depth: depth,
                        value: 3 + Math.random() * 7 + Math.sin(depth / 200) * 2
                    };
                }),
                // 研磨性系数数据
                '研磨性系数': Array.from({ length: 100 }, (_, i) => {
                    const depth = 2603 + i * 34;
                    return {
                        depth: depth,
                        value: 0.5 + Math.random() * 1.5 + Math.sin(depth / 150) * 0.3
                    };
                })
            },
            // 层位颜色映射
            layerColors: {
                '八道湾组': '#fbd860',
                '白碱滩组': '#f3a43a',
                '百口泉组': '#5fc0de',
                '下克拉玛依组': '#d74f4a'
            },
            uniqueLayers: ['八道湾组', '白碱滩组', '百口泉组', '下克拉玛依组'],
            // 深度范围
            scale: 6000,
            scale1: 2603
        }
    },
    mounted() {
        this.initChart()
    },
    beforeDestroy() {
        if (this.plot) {
            this.plot.dispose()
        }
    },
    methods: {
        initChart() {
            this.createScene(this.$refs.plot)
        },

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

            // 设置深度范围
            const startDepth = parseFloat(this.chartForm.startDepth) || 2603;
            const endDepth = parseFloat(this.chartForm.endDepth) || 6000;
            widget.setDepthLimits(startDepth, endDepth);

            // 应用样式
            this.applyModernThemeCSS(widget);

            // 添加工具提示
            widget.connectTool(new TooltipTool(widget));

            // 添加坐标轴
            widget.addTrack(TrackType.IndexTrack);

            // 1. 层位轨道
            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['层位'] && 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
                                    );
                                    const color = layerInfo ? this.layerColors[layerInfo.layer] : '#FFFFFF';
                                    return color;
                                },
                                'textstyles': {
                                    'color': '#FFFFFF !important',
                                    'font': 'bold 14px Arial',
                                    'alignment': 'center',
                                    'baseline': 'middle',
                                    'angle': 0,
                                    'fillstyle': {
                                        'color': '#FFFFFF !important'
                                    },
                                    '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('')
                        )
                );
            }

            // 2. 单轴线压强度轨道
            const dzkTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100)
                .addChild(
                    new Group()
                        .setLayout(new CssLayout())
                        .setLayoutStyle({
                            'left': '0%',
                            'right': '0%',
                            'top': '-45px',
                            'height': '45px'
                        })
                );

            // 添加单轴线压强度曲线
            const dzkCurve = this.createCurve('单轴线压强度', 'red');
            if (dzkCurve !== null) {
                dzkTrack.addChild(dzkCurve);
            }

            // 3. 岩石可钻性级值轨道
            const yskzTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100)
                .addChild(
                    new Group()
                        .setLayout(new CssLayout())
                        .setLayoutStyle({
                            'left': '0%',
                            'right': '0%',
                            'top': '-45px',
                            'height': '45px'
                        })
                );

            // 添加岩石可钻性级值曲线
            const yskzCurve = this.createCurve('岩石可钻性级值', 'red');
            if (yskzCurve !== null) {
                yskzTrack.addChild(yskzCurve);
            }

            // 4. 研磨性系数轨道
            const ymzsTrack = widget.addTrack(TrackType.LinearTrack)
                .setWidth(100)
                .addChild(
                    new Group()
                        .setLayout(new CssLayout())
                        .setLayoutStyle({
                            'left': '0%',
                            'right': '0%',
                            'top': '-45px',
                            'height': '45px'
                        })
                );

            // 添加研磨性系数曲线
            const ymzsCurve = this.createCurve('研磨性系数', 'red');
            if (ymzsCurve !== null) {
                ymzsTrack.addChild(ymzsCurve);
            }

            // 添加层位图例
            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);

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

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

            // 适应大小
            widget.fitToHeight();

            return this.plot;
        },

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

                // 提取深度和值
                const depths = data.map(item => item.depth);
                const values = data.map(item => item.value);

                // 创建数据对象
                const logData = new LogData(depths, values);

                // 计算限制
                let limits;
                try {
                    limits = MathUtil.calculateNeatLimits(logData.getMinValue(), logData.getMaxValue(), false, false);
                } catch (e) {
                    console.warn(`计算 ${curveMnemonic} 的限制时出错:`, e);
                    limits = [0, 1];
                }

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

        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('')
            }))
        },

        handleRefreshChart() {
            console.log('查询图表')
            this.initChart()
        },

        handleCalculate() {
            console.log('计算')
            // 这里可以实现计算功能
        },

        handleExportData() {
            console.log('下载数据文档')
            // 这里可以实现数据导出功能
        },

        handleNeighborWell() {
            console.log('邻井映射')
            // 这里可以实现邻井映射功能
        }
    }
}
</script>

<style lang="scss" scoped>
.formation-curve-chart {
    padding: 20px;

    .chart-controls {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding: 15px;
        background-color: #f5f7fa;
        border-radius: 4px;

        .control-item {
            display: flex;
            align-items: center;

            label {
                margin-right: 10px;
                font-weight: bold;
                color: #333;
            }
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }
    }

    .chart-container {
        background-color: #fff;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 20px;
        position: relative;
    }
}

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>
