<template>
<div class="vtk">
    <!-- <div id="vtkContainer" /> -->

  </div>

</template>

<script setup>

import * as d3 from "d3-scale";
import { formatDefaultLocale } from "d3-format";
import { ref, onMounted, reactive } from "vue";
import "@kitware/vtk.js/Rendering/Profiles/Geometry";
import vtkRenderWindowWithControlBar from "@kitware/vtk.js/Rendering/Misc/RenderWindowWithControlBar";
import vtkFullScreenRenderWindow from "@kitware/vtk.js/Rendering/Misc/FullScreenRenderWindow";

import vtkActor from "@kitware/vtk.js/Rendering/Core/Actor";
import vtkMapper from "@kitware/vtk.js/Rendering/Core/Mapper";
import vtkUnstructuredDataReader from "../reader/UnstructuredDataReader.js";
import { createFireControl } from "../control/fireControl.js";
import vtkScalarBarActor from "@kitware/vtk.js/Rendering/Core/ScalarBarActor";
import vtkLookupTable from "@kitware/vtk.js/Common/Core/LookupTable";
import vtkDataArray from "@kitware/vtk.js/Common/Core/DataArray.js";
import vtkColorTransferFunction from "@kitware/vtk.js/Rendering/Core/ColorTransferFunction";
import { I } from "@kitware/vtk.js/macros2.js";
import { Representation } from "@kitware/vtk.js/Rendering/Core/Property/Constants";
import evolutionView from "./evolutionView.vue";

import vtkConeSource from "@kitware/vtk.js/Filters/Sources/ConeSource";
import vtkSphereMapper from "@kitware/vtk.js/Rendering/Core/SphereMapper";
import vtkPixelSpaceCallbackMapper from "@kitware/vtk.js/Rendering/Core/PixelSpaceCallbackMapper";
import vtkSphereSource from "@kitware/vtk.js/Filters/Sources/SphereSource";

import vtkAxesActor from "@kitware/vtk.js/Rendering/Core/AxesActor";
import vtkCubeAxesActor from "@kitware/vtk.js/Rendering/Core/CubeAxesActor";
import vtk2DShape from '@kitware/vtk.js/Filters/Sources/Arrow2DSource';
import vtkTriangleFilter from '@kitware/vtk.js/Filters/General/TriangleFilter';
// const props = {};
let time = 3 * 60;
const props= defineProps({
  vatkval:{
        type: Object,
    },
    arrvalue:{
      type: Array,
     
    }
 });
// let title1=ref("我是父组件")
let dialogVisible = ref(false);
// let num = ref(4);
// let starttime = ref(1);
// let endtime = ref(60);
// let timenum = ref(2);
// let isstop = ref(false);
 let arrvalue = reactive([]);

// 响应式状态
const count = ref(0);
const opacity = ref(0.1);
const min = ref(0);
const max = ref(1);
const scalarFAll = ref([]); //火灾标量
const scalarWAll = ref([]); //水灾标量
/*
Temperature：温度
Pressure：压强
SO2：SO2
CO2：CO2
Height：水位高度
*/
// const scalarName = ref("CO2");
//  const filedir =ref("data/Fire/");
//const scalarName = ref("Height");
const filedir = ref("data/Water/");
// const renderWindowWith = vtkRenderWindowWithControlBar.newInstance({
//     controlSize: 11,
//   });

const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance();
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();
const mapper = vtkMapper.newInstance();
const actor = vtkActor.newInstance();

// actor.getProperty().setRepresentation(Representation.WIREFRAME);//线
// actor.getProperty().setRepresentation(Representation.POINTS);//点
actor.getProperty().setRepresentation(Representation.SURFACE); //面

// 用来修改状态、触发更新的函数
function inOpacity() {
  opacity.value = opacity.value + 0.1;
  actor.getProperty().setOpacity(opacity.value);
  renderWindow.render();
}
function getMinMax(scalars) {
  // console.log("getMinMax:",scalars);
  min.value = scalars[0];
  max.value = scalars[0];
  for (let index = 0; index <= scalars.length; index++) {
    let scalar = scalars[index];
    if (min.value > scalar) {
      min.value = scalar;
    }
    if (max.value < scalar) {
      max.value = scalar;
    }
  }
  // console.log("max，min:", max.value, min.value);
}
//时间
function sleep(numberMillis) {
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  console.log(exitTime);
}





// 用来修改状态、触发更新的函数
function increment() {
  isstop.value = false;
  if (count.value == endtime.value) {
    return;
  }
  count.value++;
  changeScalar();
}
function changeScalar() {
  console.log(props.arrvalue)
  var scalars;
  if (props.arrvalue[0] == "fire") {
    scalars = scalarFAll.value[count.value];
  } else {
    scalars = scalarWAll.value[count.value];
  }
  const polydata = mapper.getInputData();
  const scalarArray = scalars.get(props.arrvalue[1]);
  // console.log("scalarArray:", scalarArray);
  const dataArray = vtkDataArray.newInstance({
    name: props.arrvalue[1],
    size: polydata.getNumberOfPoints(),
  });
  dataArray.setData(scalarArray);
  getMinMax(scalarArray);
  mapper.setScalarRange(min.value, max.value); //设置范围
  scalarBarActor.setAxisLabel(props.arrvalue[1]);
  polydata.getPointData().setScalars(dataArray);
  mapper.clearColorArrays(); //强制重建颜色
  actor.getProperty().setOpacity(count.value); //设置错误的透明度使得页面重新加载  不设置不刷新页面
  renderWindow.render();
}
//加载所有 标量数据
function loadScalarAll() {
  //水灾
  // for (let index = 0; index <= 15; index++) {
    //   const reader = vtkUnstructuredDataReader.newInstance();
  //   const url="http://192.168.0.131:8187/TransServlet?channelNo=service&clientToken=e47b87eec69545559d1e81e56626da68&transCode=D00009&userId=5f06c8bc77234f969d13e160b54c27e3&aid=5&stype=Water&step="
  //   reader.setUrl(url + index ).then(() => {
  //     const scalars = reader.getOutputData(1);
  //     scalarWAll.value[index] = scalars;
  //   });
  // }
  //火灾
  for (let index = 1; index <= 4; index++) {
    const reader = vtkUnstructuredDataReader.newInstance();
    const url =
      "http://192.168.0.131:8187/TransServlet?channelNo=service&clientToken=e47b87eec69545559d1e81e56626da68&transCode=D00009&userId=5f06c8bc77234f969d13e160b54c27e3&aid=5&stype=Fire&step=";
    reader.setUrl(url + index).then(() => {
      console.log("url + index ", index);
      const scalars = reader.getOutputData(1);
      scalarFAll.value[index] = scalars;
      console.log(scalars);
      console.log(2222)
      console.log("url end  ");
    });
  }
  console.log("scalarAll.value:", scalarFAll);
}
//设置
function generateTicks(numberOfTicks) {
  return (helper) => {
    const lastTickBounds = helper.getLastTickBounds();
    // compute tick marks for axes
    const scale = d3
      .scaleLinear()
      .domain([0.0, 1.0])
      .range([lastTickBounds[0], lastTickBounds[1]]);
    const samples = scale.ticks(numberOfTicks);
    const ticks = samples.map((tick) => scale(tick));
    // Replace minus "\u2212" with hyphen-minus "\u002D" so that parseFloat() works
    formatDefaultLocale({ minus: "\u002D" });
    const format = scale.tickFormat(ticks[0], ticks[ticks.length - 1], numberOfTicks);
    const tickStrings = ticks
      .map(format)
      .map((tick) => Number(parseFloat(tick).toPrecision(12)).toPrecision()); // d3 sometimes adds unwanted whitespace
    helper.setTicks(ticks);
    helper.setTickStrings(tickStrings);
  };
}
//安装时
onMounted(() => {
  arrvalue = ["Water", "Height"];
  // const sphereSource = vtkSphereSource.newInstance({
  //   center: [495960.36, 5402540.18, -424.27],
  //   radius: 3.02,
  //   phiResolution: 20,
  //   thetaResolution:20,
  // });

  // const mapper1 = vtkMapper.newInstance();
  // mapper1.setInputConnection(sphereSource.getOutputPort());
  // const actor1 = vtkActor.newInstance();
  // actor1.setMapper(mapper1);
  // actor1.getProperty().setColor([0.95, 0.45, 0.95]);
  // renderer.addActor(actor1);

// choices include triangle, star, arrow4points, arrow6points
  const initialValues = { base:-0.1,shape: 'arrow4points',center: [495960.36, 5402540.18, -424.27],width: 20.0,height:20,direction:[0,1,1] };
   
  // const triangleFilter = vtkTriangleFilter.newInstance();
  const shapeSource2 = vtk2DShape.newInstance(initialValues);
  // triangleFilter.setInputConnection(shapeSource2.getOutputPort());

  const mapper2 = vtkMapper.newInstance();
  mapper2.setInputConnection(shapeSource2.getOutputPort());
  const actor2 = vtkActor.newInstance();
  actor2.setMapper(mapper2);
  renderer.addActor(actor2);

  // const cubeAxes = vtkCubeAxesActor.newInstance();
  // cubeAxes.setCamera(renderer.getActiveCamera());
  // cubeAxes.setDataBounds(actor1.getBounds());
  // renderer.addActor(cubeAxes);


  // const axesActor = vtkAxesActor.newInstance();
  // renderer.addActor(axesActor);



  renderer.resetCamera();
  renderWindow.render();
  fireRead();
});

function fireRead() {
  var fcon = createFireControl();
  fcon
    .initGemetry()
    .then((result) => {
      fcon
        .initScalrs()
        .then((result) => {
         // console.log(fcon.scalars)
          const scalarArray = fcon.scalars[3].get("Pressure");
          //console.log("scalarArray:", scalarArray);
          const dataArray = vtkDataArray.newInstance({ 
            name: arrvalue[1],
            size: fcon.polydata.getNumberOfPoints(),
          });
          console.log(dataArray)
          dataArray.setData(scalarArray);
          fcon.polydata.getPointData().setScalars(dataArray);
          mapper.setInputData(fcon.polydata);
          getMinMax(scalarArray);
          mapper.setScalarRange(min.value, max.value); //设置范围
          actor.setMapper(mapper);
          renderer.addActor(actor);

          initScalarBar();
          renderer.resetCamera();
          renderWindow.render();
        })
        .catch((err) => {});
    })
    .catch((err) => {});
}

// 初始化 bar
function initScalarBar() {
  const scalarBarActor = vtkScalarBarActor.newInstance();
  let lut = mapper.getLookupTable();
  scalarBarActor.setScalarsToColors(lut);
  // console.log("lut:", lut.getRange());
  // Change the number of ticks (TODO: add numberOfTicks to ScalarBarActor)
  scalarBarActor.setGenerateTicks(generateTicks(5));
  scalarBarActor.setAxisLabel(arrvalue[1]);
  scalarBarActor.setDrawAboveRangeSwatch(true);
  //修改设条颜色
  const ctf = vtkColorTransferFunction.newInstance();
  ctf.addRGBPoint(0.0, 0.0, 0.0, 1.0);
  ctf.addRGBPoint(1.0, 0.0, 1.0, 0.5);
  ctf.addRGBPoint(2.0, 0.0, 1.0, 0.0);
  ctf.addRGBPoint(3.0, 1.0, 0.5, 0.0);
  ctf.addRGBPoint(4.0, 1.0, 0.0, 0.0);
  mapper.setLookupTable(ctf);
  lut = mapper.getLookupTable();
  scalarBarActor.setScalarsToColors(lut);
  renderer.addActor(scalarBarActor);
}
defineExpose({changeScalar})
</script>

<style>
#vtkContainer{
  position: relative;
}
.vtk{
  position: relative;
}
.controls {
  position: absolute;
  top: 25px;
  left: 25px;
  background: white;
  padding: 12px;
}
.haha {
  color: #fff;
}
.tool {
  position: fixed;
  top: 50px;
  left: 20px;

  z-index: 205;
}
.img {
  width: 48px;
  margin: -6px 0;
  padding: 8px 10px;
  background-color: rgba(255, 255, 255, 0.1);
  font-size: 12px;
  transform: scale(0.9);
}
.img span {
  color: #fff;
  display: inline-block;
}
.img .el-image {
  width: 34px;
}
.leftdialong {
  padding: 15px;
  width: 300px;
  position: relative;
  top: -248px;
  left: 69px;
  border-radius: 5px;
  box-shadow: 0px 3px 10px rgba(255, 255, 255, 0.1);
}
.leftdialong .el-form-item__label {
  font-size: 12px;
  color: #fff !important;
  padding-left: 6px;
}
.time {
  color: #fff;
  font-size: 12px;
  margin-bottom: 30px;
}
.itemlist {
  display: flex;
}
.item {
  background-color: rgba(255, 255, 255, 0.1);
  margin: 5px;
  padding: 5px 9px;
  border-radius: 5px;
  font-size: 14px;
  transform: scale(0.8);
  color: #fff;
}
.dialog-footer {
  margin-top: 30px;
  text-align: right;
}
.block {
  display: flex;
}
.demonstration {
  padding: 5px 5px 5px 0;
  font-size: 12px;
  color: #fff;
  display: inline-block;
  width: 100px;
  height: 24px;
  line-height: 24px;
}
.block .el-slider {
  padding: 0 5px;
}
.cascadeer .el-cascader {
  width: 100%;
}
.cascadeer .asterisk-left {
  width: 100% !important;
  font-size: 12px;
}
.btn {
  background-color: rgba(255, 255, 255, 0.1);
  margin: 5px;
  padding: 5px 9px;
  border-radius: 5px;
  font-size: 14px;
  transform: scale(0.8);
  color: #fff;
}
</style>
