<template>
  <div>
    <el-tooltip content="设置" placement="bottom" effect="light">
      <el-button @click="editProperties" :class="{ 'active': showLineStylePanel }">
        <i class="el-icon-setting"></i>
      </el-button>
    </el-tooltip>
    <el-tooltip content="上传文件" placement="bottom" effect="light">
      <el-button @click="triggerFileUpload">
        <i class="el-icon-upload"></i>
      </el-button>
    </el-tooltip>
    <el-dialog title="设置" :visible.sync="showPropertiesDialog" width="100%">
      <el-form ref="form" label-width="130px">
        <el-row>

          <el-col :span="5">
            <el-form-item label="颜色集合">
              <el-select v-model="colorMapSelect" placeholder="请选择颜色集合" @change="changeColor">
                <el-option v-for="item in listNameColorMaps" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="归一化类型">
              <el-select v-model="NormalizationType" @change="changeNor" placeholder="请选择归一化类型">
                <el-option v-for="item in NormalizationTypeData" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="归一化比例">
              <el-slider @change="changeNor" style="width: 180px;" v-model="NormalizationBl" :min="0.1" :max="5"
                :step="0.1" show-stops>
              </el-slider>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="每英寸道数">
              <el-input v-model="mycds" @blur="changeMycds"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="每秒英寸数">
              <el-input v-model="msycs" @blur="changeMycds"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="采样插值类型">
              <el-select v-model="samplesType" @change="changeInt" placeholder="请选择采样插值类型">
                <el-option v-for="item in InterpolationType" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="采样插值边缘">
              <el-select v-model="samplesEdge" @change="changeInt" placeholder="请选择采样插值边缘">
                <el-option v-for="item in InterpolationEdge" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="道插值类型">
              <el-select v-model="tracesEdge" @change="changeInt" placeholder="请选择道插值类型">
                <el-option v-for="item in InterpolationType" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="道插值边缘">
              <el-select v-model="tracesType" @change="changeInt" placeholder="请选择道插值边缘">
                <el-option v-for="item in InterpolationEdge" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="绘图类型">
              <el-checkbox v-model="Wiggle" @change="changePlotType">Wiggle</el-checkbox>
              <el-checkbox v-model="Reversed" @change="changePlotType">Reversed</el-checkbox>
              <el-checkbox v-model="PositiveFill" @change="changePlotType">Positive fill</el-checkbox>
              <el-checkbox v-model="NegativeFill" @change="changePlotType">Negative fill</el-checkbox>
              <el-checkbox v-model="PositiveColorFill" @change="changePlotType">Positive color fill</el-checkbox>
              <el-checkbox v-model="NegativeColorFill" @change="changePlotType">Negative color fill</el-checkbox>
              <el-checkbox v-model="SimpleDensity" @change="changePlotType">Simple density</el-checkbox>
              <el-checkbox v-model="InterpolatedDensity" @change="changePlotType">Interpolated density</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="Wiggle-裁剪因子">
              <el-input v-model="ClippingFactor" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="Wiggle-抽取间距">
              <el-input v-model="DecimationSpacing" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="Wiggle-密度抽取">
              <el-checkbox v-model="densityDecimation" @change="changePlotType">Density decimation（密度抽取）</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="Clipping mode（裁剪模式）">
              <el-select v-model="ClippingMode" @change="changePlotType" placeholder="请选择裁剪模式">
                <el-option v-for="item in ClippingModeData" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <el-form-item label="TaperFilter（滤波）">
              <el-checkbox v-model="TaperFilterEnbled" @change="changePlotType">启用滤波</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="f1">
              <el-input v-model="f1" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="f2">
              <el-input v-model="f2" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="f3">
              <el-input v-model="f3" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label="f4">
              <el-input v-model="f4" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="采样率">
              <el-input v-model="sampleRate" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="带通模式">
              <el-checkbox v-model="passFlag" @change="changePlotType">带通模式</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="3">
            <el-form-item label="AGC">
              <el-checkbox v-model="AGCEnbled" @change="changePlotType">启用AGC</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="AGC length">
              <el-input v-model="AGCLength" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="Desired average">
              <el-input v-model="DesiredAverage" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="Noise reduction">
              <el-select v-model="NoiseReduction" @change="changePlotType" placeholder="请选择降噪">
                <el-option v-for="item in NoiseReductionData" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="Noise reduction percentage">
              <el-input v-model="NoiseReductionPercentage" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="Start sample">
              <el-input v-model="StartSample" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="Step">
              <el-input v-model="Step" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="Units">
              <el-select v-model="Units" @change="changePlotType" placeholder="请选择单位">
                <el-option v-for="item in UnitsData" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="Window length">
              <el-input v-model="WindowLength" style="width: 80px" @blur="changePlotType"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="3">
            <el-form-item label="Reverse">
              <el-checkbox v-model="ReverseEnbled" @change="changePlotType">启用Reverse</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="inverted">
              <el-checkbox v-model="inverted" @change="changePlotType">启用inverted</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="reversed">
              <el-checkbox v-model="reversed" @change="changePlotType">启用reversed</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showPropertiesDialog = false">取 消</el-button>
        <el-button type="primary" @click="showPropertiesDialog = false">确 定</el-button>
      </div>
    </el-dialog>



    <canvas ref="plot" id="canvas" />

    <!--    <PropertiesDialog-->
    <!--      :show-dialog="showPropertiesDialog"-->
    <!--      :node-props="nodeProps"-->
    <!--      :ajv="ajv"-->
    <!--      :schema="schema"-->
    <!--      @close="applyProps"-->
    <!--    />-->
  </div>
</template>

<script>
import { SeismicPlot } from './App.js';
import PropertiesDialog from './ui/PropertiesDialog.vue';
import { getAjv, setNodeProps, getNodeProps } from './ui/DialogPropertyUtils';
import { getToken } from "@/utils/auth";

import { SegyReader } from '@int/geotoolkit/seismic/data/SegyReader';
import { LocalFile } from '@int/geotoolkit/seismic/data/LocalFile';
import { Reverse } from '@int/geotoolkit/seismic/pipeline/processor/Reverse';
import { AGC } from '@int/geotoolkit/seismic/pipeline/processor/AGC';
import { TaperFilterProcess } from '@int/geotoolkit/seismic/analysis/filters/TaperFilterProcess';
import { NormalizationType } from '@int/geotoolkit/seismic/pipeline/NormalizationType';
import { SeismicPipeline } from '@int/geotoolkit/seismic/pipeline/SeismicPipeline';
import { SeismicColors } from '@int/geotoolkit/seismic/util/SeismicColors';

let seismicPlot = null;
export default {
  name: "index",
  components: {
    PropertiesDialog
  },
  data() {
    return {
      showLineStylePanel: false,
      showPropertiesDialog: false,
      nodeProps: null,
      ajv: null,
      schema: null,
      chartIsActive: false,
      tableIsActive: false,
      listNameColorMaps: [
        "WhiteBlack",
        "RedWhiteBlack",
        "RedWhiteBlue",
        "Saddleback",
        "Angles5color",
        "BlackRedYellowWhite",
        "GreyOrange",
        "IntervalVelocity",
        "IntervalVelocity16",
        "IntervalVelocity32",
        "Rainbow",
        "RedGreenBlue",
        "RedWhiteBlueExtremes",
        "RedWhiteBlueHot",
        "RedYellowBlue",
        "SaddlebackHot",
        "Spectrum"
      ],
      colorMapSelect: "",
      _colorMap: "",
      pipeline: null,
      _seismicWidget: null,
      NormalizationType: null,
      NormalizationBl: 0.1,
      NormalizationTypeData: [
        {
          "label": "None",
          "value": 0,
        },
        {
          "label": "Maximum",
          "value": 1,
        },
        {
          "label": "TraceMaximum",
          "value": 2,
        },
        {
          "label": "Average",
          "value": 3,
        },
        {
          "label": "TraceAverage",
          "value": 4,
        }, {
          "label": "RMS",
          "value": 5,
        }, {
          "label": "TraceRMS",
          "value": 6,
        }, {
          "label": "Limits",
          "value": 7,
        }
      ],
      mycds: null,
      msycs: null,
      samplesType: null,
      samplesEdge: null,
      tracesType: null,
      tracesEdge: null,
      InterpolationType: [
        {
          "label": "Linear",
          "value": 1,
        }, {
          "label": "Quadratic",
          "value": 2,
        }, {
          "label": "Step",
          "value": 3,
        }, {
          "label": "CenteredStep",
          "value": 4,
        }, {
          "label": "Cubic",
          "value": 5,
        }, {
          "label": "Logarithmic",
          "value": 6,
        },
      ],
      InterpolationEdge: [
        {
          "label": "Zero",
          "value": 0,
        }, {
          "label": "Duplicate",
          "value": 1,
        }
      ],
      Wiggle: false,
      Reversed: false,
      PositiveFill: false,
      NegativeFill: false,
      PositiveColorFill: false,
      NegativeColorFill: false,
      SimpleDensity: false,
      InterpolatedDensity: true,
      ClippingFactor: 4,
      DecimationSpacing: 5,
      densityDecimation: false,
      ClippingMode: null,
      ClippingModeData: [
        {
          "label": "Connected",
          "value": "Connected"
        }, {
          "label": "Disconnected",
          "value": "Disconnected"
        },
      ],
      TaperFilterEnbled: false,
      f1: 10,
      f2: 20,
      f3: 60,
      f4: 70,
      sampleRate: 0,
      passFlag: false,
      AGCEnbled: false,
      AGCLength: 0,
      DesiredAverage: 1,
      NoiseReductionPercentage: 3,
      NoiseReduction: null,
      StartSample: 0,
      Step: 1,
      Units: "",
      WindowLength: 250,
      UnitsData: [
        {
          "label": "Sample",
          "value": 0
        }, {
          "label": "Time",
          "value": 1
        },
      ],
      NoiseReductionData: [
        {
          "label": "disable",
          "value": "disable"
        }, {
          "label": "enable",
          "value": "enable"
        }, {
          "label": "auto",
          "value": "auto"
        },
      ],

      ReverseEnbled: false,
      inverted: false,
      reversed: false,

      // 文件上传相关
      uploadUrl: process.env.VUE_APP_BASE_API + '/ndy/dz/upload',
      uploadHeaders: {
        Authorization: "Bearer " + getToken()
      },
      fileList: []

    }
  },
  mounted() {
    // this.init()
  },
  methods: {
    init() {
      //创建
      seismicPlot = new SeismicPlot({
        'canvas': this.$refs.plot,
        'errorCallback': this.onCreateWidgetError,
        'fileOpenedCallback': this.onFileOpen
      });
      // 不再自动加载默认文件，等待用户上传文件
    },

    handleFileSelect() {
      let url = process.env.VUE_APP_BASE_API + "/ndy/dz/getSegyDataFile3?fileName=density.segy";
      let fileName = 'density.segy';
      return fetch(url, {
        headers: {
          Authorization: "Bearer " + getToken()
        }
      }).then((response) => {
        if (!response.ok) {
          throw new Error(`网络请求失败: ${response.status} ${response.statusText}`);
        }
        return response.blob();

      }).then((blob) => {
        if (!blob || blob.size === 0) {
          throw new Error('获取到的文件数据为空');
        }
        let fileInput = new File([blob], fileName, { type: blob.type, lastModified: Date.now() });
        // seismicPlot.createWidgetFromFile(filesObj)
        const file = new LocalFile(fileInput);
        this._fileSize = file.fileSize;
        const segyReader = new SegyReader(file);
        segyReader.loadMetaData((reader) => {
          if (reader instanceof Error && this.errorCallback != null) {
            this.errorCallback(reader.message);
            return;
          }
          // this.createRemotePipeline(reader)
          reader.readDataSetStatistics((reader, statistics) => {
            if (reader.getModelLimits().getHeight() === 0 && this.warningCallback != null) {
              return this.$message.error("加载失败");
            }
            // return this.createPipelineFromFile(file.getFileName(), reader, statistics);
            this.pipeline = new SeismicPipeline(file.getFileName(), reader, statistics)
            seismicPlot.createPipelineFromFile2(this.pipeline, file.getFileName(), reader, statistics);
            console.log(this.pipeline)
          });
        });

      })
    },
    onCreateWidgetError(errorMsg) {
      this.$message.error(errorMsg);
    },
    editProperties() {
      // console.log(seismicPlot)
      // this.ajv = getAjv({chartNames: seismicPlot.getChartNames()});
      // console.log(this.ajv)
      // this.schema = this.ajv.getSchema(`/${seismicPlot.getWidget().getClassName()}`).schema;
      // console.log(this.schema)
      // this.nodeProps = getNodeProps(seismicPlot);
      // console.log(this.nodeProps)
      this.showPropertiesDialog = true;
    },

    applyProps(props) {
      if (props) {
        setNodeProps(seismicPlot, props);
      }
      this.showPropertiesDialog = false;
    },

    onFileOpen() {

    },

    changeColor(val) {
      var colorMap = SeismicColors.getDefault().createNamedColorMap(val, 256)
      this.pipeline.setColorMap(colorMap);
      if (seismicPlot._seismicWidget) {
        seismicPlot._seismicWidget.invalidate(); // 使组件重新渲染
        seismicPlot._seismicWidget.fitToBounds(); // 调整视图以适应数据
      } else {
        console.error('Widget不可用，无法更新视图');
      }
      // 如果plots对象存在redraw方法，使用它来触发重绘
      if (seismicPlot.plots && typeof seismicPlot.plots.redraw === 'function') {
        seismicPlot.plots.redraw();
      }
    },
    //归一化
    changeNor(val) {
      if (this.NormalizationType == 7) {
        this.pipeline.setOptions({
          'normalization': {
            'type': this.NormalizationType,
            'scale': this.NormalizationBl
          }
        })
      } else {
        this.pipeline.setOptions({
          'normalization': {
            'type': this.NormalizationType,
            'scale': this.NormalizationBl
          }
        })
      }

    },
    changeMycds() {
      seismicPlot.openPipeline(this.pipeline, {
        'tracescale': this.mycds,
        'samplescale': this.msycs,
        'deviceunit': 'in',
        'sampleunit': 's',
      });
    },
    changeInt() {
      console.log(this.pipeline.getOptions())
      this.pipeline.setOptions({
        'interpolation': {
          'samples': {
            "type": this.samplesType,//采样插值类型,
            "edge": this.samplesEdge,//采样插值边缘,
          },
          'traces': {
            "type": this.tracesType,//道插值类型
            "edge": this.tracesEdge,//道插值边缘
          },
        }
      })
    },
    changePlotType() {
      this.pipeline.setOptions({
        'plot': {
          'type': {
            "Wiggle": this.Wiggle,
            "Reversed": this.Reversed,
            "PositiveFill": this.PositiveFill,
            "NegativeFill": this.NegativeFill,
            "PositiveColorFill": this.PositiveColorFill,
            "NegativeColorFill": this.NegativeColorFill,
            "SimpleDensity": this.SimpleDensity,
            "InterpolatedDensity": this.InterpolatedDensity,
          },
          "clippingFactor": this.ClippingFactor,
          "decimationSpacing": this.DecimationSpacing,
          "densityDecimation": this.densityDecimation,
        },
        "clippingmode": this.ClippingMode,
        "dataProcessors": {
          "TaperFilter": {
            "apply": this.TaperFilterEnbled,
            "f1": Number(this.f1),
            "f2": Number(this.f2),
            "f3": Number(this.f3),
            "f4": Number(this.f4),
            "sampleRate": Number(this.sampleRate),
            "passFlag": this.passFlag,
          },
          "AGC": {
            "agcLength": this.AGCLength,
            "apply": this.AGCEnbled,
            "desiredAverage": this.DesiredAverage,
            "noiseReduction": this.NoiseReduction,
            "noiseReductionPercentage": this.NoiseReductionPercentage,
            "startSample": this.StartSample,
            "step": this.Step,
            "units": this.Units,
            "windowLength": this.WindowLength,
          },
          "Reverse": {
            "apply": this.ReverseEnbled,
            "inverted": this.inverted,
            "reversed": this.reversed,
          }
        }
      })

      console.log(this.pipeline.getOptions())
    },

    // 文件上传相关方法
    triggerFileUpload() {
      // 创建隐藏的文件输入元素
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.segy,.sgy';
      input.style.display = 'none';

      input.onchange = (event) => {
        const file = event.target.files[0];
        if (file) {
          this.handleFileUpload(file);
        }
      };

      document.body.appendChild(input);
      input.click();
      document.body.removeChild(input);
    },

    handleFileUpload(file) {
      // 检查文件类型
      const allowedTypes = ['.segy', '.sgy'];
      const fileName = file.name.toLowerCase();
      const isValidType = allowedTypes.some(type => fileName.endsWith(type));

      if (!isValidType) {
        this.$message.error('只能上传segy、sgy文件');
        return;
      }

      // 检查文件大小 (例如限制为100MB)
      const maxSize = 100 * 1024 * 1024; // 100MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过100MB');
        return;
      }

      // 创建FormData
      const formData = new FormData();
      formData.append('file', file);

      // 上传文件
      this.$message.info('正在上传文件...');

      fetch(this.uploadUrl, {
        method: 'POST',
        headers: this.uploadHeaders,
        body: formData
      })
        .then(response => {
          if (!response.ok) {
            throw new Error(`上传失败: ${response.status} ${response.statusText}`);
          }
          return response.json();
        })
        .then(data => {
          this.$message.success('文件上传成功');
          console.log('上传成功:', data);
          // 这里可以处理上传成功后的逻辑，比如重新加载数据
          this.loadNewFile(data.fileName);
          this.init()
        })
        .catch(error => {
          console.error('上传失败:', error);
          this.$message.error('文件上传失败: ' + error.message);
        });
    },

    loadNewFile(fileName) {
      // 加载新文件的逻辑
      let url = process.env.VUE_APP_BASE_API + "/ndy/dz/getSegyDataFile3?fileName=" + fileName;

      return fetch(url, {
        headers: {
          Authorization: "Bearer " + getToken()
        }
      }).then((response) => {
        if (!response.ok) {
          throw new Error(`网络请求失败: ${response.status} ${response.statusText}`);
        }
        return response.blob();
      }).then((blob) => {
        if (!blob || blob.size === 0) {
          throw new Error('获取到的文件数据为空');
        }
        let fileInput = new File([blob], fileName, { type: blob.type, lastModified: Date.now() });
        const file = new LocalFile(fileInput);
        this._fileSize = file.fileSize;
        const segyReader = new SegyReader(file);
        segyReader.loadMetaData((reader) => {
          if (reader instanceof Error && this.errorCallback != null) {
            this.errorCallback(reader.message);
            return;
          }
          reader.readDataSetStatistics((reader, statistics) => {
            if (reader.getModelLimits().getHeight() === 0 && this.warningCallback != null) {
              return this.$message.error("加载失败");
            }
            this.pipeline = new SeismicPipeline(fileName, reader, statistics)
            seismicPlot.createPipelineFromFile2(this.pipeline, fileName, reader, statistics);
            console.log(this.pipeline)
          });
        });
      }).catch(error => {
        console.error('加载文件失败:', error);
        this.$message.error('加载文件失败: ' + error.message);
      });
    }

  }
}
</script>

<style scoped>
#canvas {
  width: 100% !important;
  height: calc(85vh - 35px) !important;
  margin-top: 20px;
}
</style>
