<template>
  <div class="toolbar-controls">
    <el-button-group>
      <!-- 放大按钮 -->
      <el-button icon="el-icon-zoom-in" plain @click="zoomIn"></el-button>
      <!-- 缩小按钮 -->
      <el-button icon="el-icon-zoom-out" plain @click="zoomOut"></el-button>
    </el-button-group>
    <!-- 导出PDF按钮 -->
    <int-button icon="el-icon-document" title="导出PDF" @click="showPrintDialog = true"
      :loading="pdfExporting"></int-button>

    <!-- PDF打印对话框 -->
    <int-print-dialog :show-dialog="showPrintDialog" @save="exportToPDF" @close="handleDialogClose">
      <el-checkbox v-model="printAnnotations" label="Print Annotations" />
    </int-print-dialog>
  </div>
</template>

<script>
import { ScalingOptions } from '@int/geotoolkit/scene/exports/ScalingOptions.js';
import { Rect } from '@int/geotoolkit/util/Rect';
import { NodeExport } from '@int/geotoolkit/scene/exports/NodeExport';
import { getPixelScale } from '@int/geotoolkit/base';
import IntButton from '@/components/int-button/index.vue';
import IntPrintDialog from '@/components/int-print-dialog/index.vue';
import { UnitFactory } from '@int/geotoolkit/util/UnitFactory';
import { PaperFormatFactory } from '@int/geotoolkit/scene/exports/PaperFormatFactory';
import { PaperOrientation } from '@int/geotoolkit/scene/exports/PaperOrientation';
import { NodeAdapter } from '@int/geotoolkit/scene/exports/NodeAdapter';
import { PdfExport } from '@int/geotoolkit/pdf/PdfExport';
import { StringStream } from '@int/geotoolkit/util/stream/StringStream';
import { CompositeDocumentElement } from '@int/geotoolkit/scene/exports/CompositeDocumentElement';
import { FreeLayout } from '@int/geotoolkit/scene/exports/FreeLayout';
import { Document } from '@int/geotoolkit/scene/exports/Document';

export default {
  name: 'ToolbarControls',
  components: {
    IntButton,
    IntPrintDialog,
  },
  props: {
    plots: {
      type: Object,
      default: null
    },
    dataLoaded: {
      type: Boolean,
      default: false
    },
    showLineStylePanel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      zoomFactor: 1.08,
      zoomInProgress: false,
      pdfExporting: false,
      showPrintDialog: false,
      printAnnotations: false
    };
  },
  methods: {
    /**
     * 放大视图
     */
    zoomIn() {
      if (this.plots && this.dataLoaded && !this.zoomInProgress) {
        this.zoomInProgress = true;
        const widget = this.plots.getRoot();
        const currentLimits = widget.getModelLimits();

        if (currentLimits != null && !currentLimits.isEmpty()) {
          const center = currentLimits.getCenter();
          const newWidth = currentLimits.getWidth() / this.zoomFactor;
          const newHeight = currentLimits.getHeight() / this.zoomFactor;

          const left = center.x - newWidth / 2;
          const top = center.y - newHeight / 2;
          const right = center.x + newWidth / 2;
          const bottom = center.y + newHeight / 2;

          const scaledRect = new Rect(left, top, right, bottom);
          widget.setModelLimits(scaledRect);

          // 更新视图和滚动条
          widget.invalidate();

          // 确保滚动条更新
          const tool = this.plots.getTool();
          if (tool && tool.getScrollbarTool) {
            const scrollbarTool = tool.getScrollbarTool();
            if (scrollbarTool) {
              scrollbarTool.update();
            }
          }

          if (typeof widget.update === 'function') {
            widget.update();
          }
        }

        setTimeout(() => {
          this.zoomInProgress = false;
        }, 800);
      }
    },

    /**
     * 缩小视图
     */
    zoomOut() {
      if (this.plots && this.dataLoaded && !this.zoomInProgress) {
        this.zoomInProgress = true; // 设置标志，防止重复触发

        const widget = this.plots.getRoot();
        const currentLimits = widget.getModelLimits();
        if (currentLimits != null && !currentLimits.isEmpty()) {
          const center = currentLimits.getCenter();
          const newWidth = currentLimits.getWidth() * this.zoomFactor;
          const newHeight = currentLimits.getHeight() * this.zoomFactor;

          const left = center.x - newWidth / 2;
          const top = center.y - newHeight / 2;
          const right = center.x + newWidth / 2;
          const bottom = center.y + newHeight / 2;

          const scaledRect = new Rect(left, top, right, bottom);
          widget.setModelLimits(scaledRect);

          // 仅调用invalidate方法进行重绘
          widget.invalidate();

          // 如果需要，可能还需要调用widget的其他更新方法
          if (typeof widget.update === 'function') {
            widget.update();
          }
        }

        // 设置延时，确保缩放动画完成后重置标志
        setTimeout(() => {
          this.zoomInProgress = false;
        }, 800); // 比动画时间稍长一些（动画时间已增加到700ms）
      }
    },

    /**
     * 切换线条样式面板
     */
    toggleLineStylePanel() {
      this.$emit('toggleLineStylePanel');
    },

    /**
     * 导出当前视图为图片
     */
    async exportToImage() {
      if (!this.plots || !this.dataLoaded) {
        this.$message.warning('请等待数据加载完成');
        return;
      }

      this.$emit('exporting', true);
      try {
        const canvas = this.$parent.$refs.plot;
        const widget = this.plots.getRoot();

        // 确保widget和pipeline都已初始化
        if (!widget || !widget.getPipeline()) {
          throw new Error('数据未正确初始化');
        }
        // 获取画布尺寸
        const width = canvas.clientWidth || 800;
        const height = canvas.clientHeight || 600;

        // 创建真实DOM中的img元素
        let imgElement = document.createElement('img');
        imgElement.width = width;
        imgElement.height = height;
        imgElement.style.position = 'absolute';
        imgElement.style.left = '-9999px';  // 隐藏图像
        document.body.appendChild(imgElement);

        // 使用Promise处理图像加载和错误
        const downloadImage = () => {
          return new Promise((resolve, reject) => {
            // 添加安全检查，避免错误
            try {
              imgElement.onload = () => {
                try {
                  // 创建下载链接
                  const link = document.createElement('a');
                  link.href = imgElement.src;
                  link.download = 'seismic_image.png';
                  document.body.appendChild(link);
                  link.click();

                  // 清理DOM
                  setTimeout(() => {
                    try {
                      if (document.body.contains(link)) {
                        document.body.removeChild(link);
                      }
                      if (document.body.contains(imgElement)) {
                        document.body.removeChild(imgElement);
                      }
                    } catch (e) {
                      console.error('清理DOM元素失败:', e);
                    }
                    resolve();
                  }, 100);
                } catch (e) {
                  console.error('处理图像下载失败:', e);
                  reject(e);
                }
              };

              imgElement.onerror = (error) => {
                console.error('图像加载失败:', error);
                try {
                  if (document.body.contains(imgElement)) {
                    document.body.removeChild(imgElement);
                  }
                } catch (e) {
                  console.error('清理图像元素失败:', e);
                }
                reject(new Error('图像加载失败'));
              };
            } catch (e) {
              console.error('设置图像事件处理失败:', e);
              reject(e);
            }
          });
        };

        try {
          const imageUrl = await NodeExport.exportToImageUrlAsync(
            widget,
            width * getPixelScale(),
            height * getPixelScale(),
            false,
            false,
            widget.getModelLimits()
          );
          imgElement.src = imageUrl;
          await downloadImage();
          this.$message.success('图片导出成功');
        } catch (error) {
          console.error('导出图像URL失败:', error);
          if (document.body.contains(imgElement)) {
            document.body.removeChild(imgElement);
          }
          throw error;
        }
      } catch (error) {
        console.error('导出图片失败:', error);
        this.$message.error('导出图片失败: ' + (error.message || '未知错误'));
      } finally {
        this.$emit('exporting', false);
      }
    },

    /**
     * 打印到PDF的辅助函数
     */
    printToPdf(plotRoot, exportBounds, printSettings, includeAnnotations = false) {
      try {
        // 使用传入的打印设置，而不是硬编码值
        const mergedSettings = {
          ...printSettings,
          'includeAnnotations': includeAnnotations
        };

        // PDF选项
        const pdfOptions = {
          'footer': null,
          'header': null,
          'output': '导出.pdf',
          'printSettings': mergedSettings,
          'limits': null,
          'scale': 1
        };

        // 创建布局元素并设置其边界
        const plotElement = new NodeAdapter(plotRoot, exportBounds)
          .setBounds(exportBounds);

        // 创建组件数组
        const components = [plotElement];

        // 创建要导出的文档
        const pdfExport = new PdfExport();
        const pdfStream = new StringStream();
        pdfStream.setSaveOptions({
          filename: pdfOptions['output'],
          save: false,
          type: 'application/pdf'
        });

        // 创建复合文档元素
        const root = new CompositeDocumentElement(components,
          new FreeLayout(exportBounds.getWidth(), exportBounds.getHeight()));

        // 创建文档对象
        const document = new Document(root, pdfOptions['header'], pdfOptions['footer'], true);

        // 导出PDF
        const stream = pdfExport.documentExportToPdfStream(document, pdfOptions['printSettings'], pdfStream);
        if (stream) {
          return {
            stream: stream,
            filename: pdfOptions['output']
          };
        }
        return null;
      } catch (error) {
        console.error('PDF生成过程中发生错误:', error);
        throw error;
      }
    },

    /**
     * 导出当前视图为PDF
     */
    async exportToPDF(data) {
      if (!this.plots || !this.dataLoaded) {
        this.$message.warning('请等待数据加载完成');
        return;
      }

      this.pdfExporting = true;
      try {
        const widget = this.plots.getRoot();
        // 确保widget已初始化
        if (!widget) {
          throw new Error('数据未正确初始化');
        }

        // 获取导出边界
        const exportBounds = widget.getBounds();

        // 获取从对话框传来的打印设置
        const printSettings = data.printSettings;

        // 添加日志，用于调试选择的纸张格式和实际使用的设置
        console.log('PDF导出设置:', {
          paperFormat: printSettings.paperFormat ? {
            name: printSettings.paperFormat.getName ? printSettings.paperFormat.getName() : '未知',
            width: printSettings.paperFormat.getWidth ? printSettings.paperFormat.getWidth() : '未知',
            height: printSettings.paperFormat.getHeight ? printSettings.paperFormat.getHeight() : '未知',
            unit: printSettings.units || '未知'
          } : '未设置',
          orientation: printSettings.orientation || '未设置',
          scaling: printSettings.scaling || '未设置',
          keepAspectRatio: printSettings.keepAspectRatio || false,
          continuous: printSettings.continuous || false,
          margins: {
            top: printSettings.top || 0,
            bottom: printSettings.bottom || 0,
            left: printSettings.left || 0,
            right: printSettings.right || 0
          }
        });

        // 确保缩放选项设置为 FitToPage
        if (printSettings.scaling !== ScalingOptions.FitToPage) {
          console.log('注意: 为确保图像完整显示，建议使用 "FitToPage" 缩放选项');
        }

        // 使用辅助函数生成PDF，传入打印设置和是否包含注释参数
        const result = this.printToPdf(widget, exportBounds, printSettings, this.printAnnotations);

        if (result && result.stream) {
          // 保存PDF文件
          result.stream.save(result.filename, false); // 添加false参数，表示显示保存对话框
          this.$message.success('PDF导出成功');
        } else {
          throw new Error('PDF导出失败');
        }
      } catch (error) {
        console.error('导出PDF时发生错误:', error);
        this.$message.error('导出PDF失败: ' + error.message);
      } finally {
        this.pdfExporting = false;
        this.showPrintDialog = false; // 关闭打印对话框
        this.$emit('closePrintDialog');
      }
    },

    /**
     * 处理PDF对话框关闭
     */
    handleDialogClose() {
      this.showPrintDialog = false;
      this.$emit('closePrintDialog');
    }
  }
};
</script>

<style scoped>
.toolbar-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 5px;
}

.is-active {
  background-color: #e6e6e6;
  border-color: #adadad;
}
</style>