<template>
  <!-- 底部导航栏 -->
  <div class="rightfl"  v-show="firstshow" style="right: 0;">
    <div class="rightfl_hei">
    <el-aside width="1.7708rem" class="L_aside L_aside1 asideg asidegbg leftbgimg1" v-show="firstshow">
      <div class="demo-collapse jiance asideg1 jc_header collapseeion jianstyle">
        <el-collapse accordion v-model="activeNames">
          <el-collapse-item name="1" class="imgneon">
            <template #title>
              <el-icon class="iconimg Frame3" fit="contain"></el-icon>
              灾害信息展示
            </template>
            <div class="rg_content">
              <div class="rg-padding">
                <div class="he_pading color1">
              <el-form-item label="物理量:" v-if="props.classradio == 'Fire'">
                <el-select
                  v-model="formInline.region"
                  @change="regionchange($event)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in strResultFormatlist"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="woter" v-else>
                <span>物理量：</span>
                <span>水位</span>
              </div>
            </div>
              <div class="zongji">
                <div class="zongjili img1">{{ warnin2 }}<span>个</span></div>
                <div class="zongjili img2">{{ warnin}}<span>个</span></div>
              </div>
              <div class="asides_content">
                <div class="jc_content tablecolor">
                  <div class="jc_padding">
                    <div class="xian2 btncolor tablefocus ">
                      <!--  -->
                      <el-table
                        :data="tableData"
                        style="width: 100%"
                        :row-class-name="tableRowClassName"
                        :header-cell-style="{ background: 'rgba(13, 22, 57, 0) ' }"
                        @row-click="handleDelete($event)"
                        :highlight-current-row="currentrow1" 
                        :max-height="tableHeight"
                      >
                      <el-table-column prop="chname" label="监测点"  />
                      <el-table-column
                          v-for="(header, index) in dynamicHeaders"
                          :key="index"
                          :prop="header.prop"
                          :label="header.label">
                        </el-table-column>
                      
                        <!-- <el-table-column prop="date" label="监测点"  />
                        <el-table-column prop="name" label="水位（m）"   />
                        <el-table-column prop="name"  label="流量（m³/s）" /> -->
                        <el-table-column   prop="state"  label="预警" >
                          <template #default="scope">
                            <el-image v-if="scope.row.state=='0'" style="height: 100%" :src="bt1" fit="contain"></el-image>
                            <el-image v-if="scope.row.state=='1'" style="height: 100%" :src="bt2" fit="contain"></el-image>
                            <el-image v-if="scope.row.state=='2'"  style="height: 100%" :src="bt3" fit="contain"></el-image>
                            <el-image v-if="scope.row.state=='3'" style="height: 100%" :src="bt4" fit="contain"></el-image>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 监测点 -->
              <div>
                <div class="hedse">
              <el-icon class="iconimg1 Frame3" fit="contain"></el-icon>{{ jcname }}
            </div>
            <div class="zongji2" v-show="noneshow">
                <div class="Firetile" ><span>温度（℃）：</span><span class="text">{{ c}}</span></div>
                <div class="Firetile"><span>压力（Pa）：</span><span class="text2">{{ pa }}</span></div>
              </div>
            <div class="echart">
            <div id="line" style="width: 1.526rem;height:.9375rem;"></div></div>
            <div class="zongji"  v-if="props.classradio=='Water'" >
                <div class="zongjili img3">{{ heightnum }}<span>m</span></div>
                <div class="zongjili img4">
                  <p class="jcshijian">{{datetime}}</p>
                  <p style="text-align: center;font-size: 0.0625rem;">{{ maxtime.steptime }}</p></div>
              </div>
            </div>
            </div>
          </div>
            <!-- <div class="mgsnoe" style="height: 200px"></div> -->
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-aside>
      <!-- 动画 -->
    <el-aside width="1.7708rem" class="L_aside L_aside1 asideg asidegbg leftbgimg1" v-show="firstshow">
      <div class="demo-collapse jiance asideg1 jc_header collapseeion jianstyle">
        <el-collapse accordion v-model="activeNames1" class="bganimation">
          <el-collapse-item name="2" class="imgneon">
            <template #title>
              <el-icon class="iconimg Frame3" fit="contain"></el-icon>
              动画展示
            </template>
            <div class="rg_content">
              <div class="rg-padding">
            
              <div class="animation_s">
              <el-slider
                :max="endtime"
                :min="0"
                v-model="count"
                @change="sliderchange"
              >
              </el-slider>
              <!-- <el-progress type="line" :percentage="percentage" :color="customColor" :stroke-width="4"/> -->
              <div class="tanniu">
                <div><el-image :src="t1" fit="contain" @click="Prev" ></el-image></div>
                <div v-show="suspendshow"><el-image :src="t2" fit="contain"  @click="play(500)" ></el-image></div>
                <div v-show="playshow"><el-image :src="t3" fit="contain"  @click="play(500)" ></el-image></div>
                <div><el-image :src="t4" fit="contain" @click="increment"></el-image></div>
                
              </div>
            </div>
          
            
            </div>
          </div>
            <!-- <div class="mgsnoe" style="height: 200px"></div> -->
          </el-collapse-item>
        </el-collapse>
      </div>
      </el-aside>
    </div>

  </div>
  <htmldialog ref="htmldialogref" :isshow='isshow' @funidshow="funidshow"/>
</template>
<script setup>
import { ref, onMounted, reactive, } from "vue";
import { RouterView, RouterLink } from "vue-router"
import { request, uploadFile } from "@/utils/request";
import { ElMessage, ElButton, ElDialog, ElSelect } from 'element-plus'
import * as echarts from 'echarts'
import { createFireControl } from "@/control/fireControl.js";
import { vtkmodel } from "@/control/vtkModel.js";
import vtkDataArray from "@kitware/vtk.js/Common/Core/DataArray.js";
import bt4 from "@/assets/img/Group1376.png"
import bt1 from "@/assets/img/Group1377.png"
import bt3 from "@/assets/img/Group1395.png"
import bt2 from "@/assets/img/Group1396.png"
import t1 from "@/assets/img/t1.png";
import t2 from "@/assets/img/t2.png";
import t3 from "@/assets/img/t3.png";
import t4 from "@/assets/img/t4.png";
import htmldialog from "./htmldialog.vue"
let firstshow = ref(false);
let activeNames = ref(["1"]);
let activeNames1=ref(["2"])
let tableHeight = ref(130);
let playshow=ref(true);
let suspendshow=ref(false);
let showfalse=ref(false);
let c=ref("0");
let htmldialogref=ref();
let pa=ref("30s");
const isstop = ref(false);
let noneshow=ref(false);
const strResultFormatlist = ref([]);
let count=ref(1);
let starttime = ref(1);
let endtime = ref(60);
let timenum = ref(2);
let aid = ref();
let newcount = ref(0);
let timing = ref(null);
let timing3 = ref(null);
let timing2 = ref(null);
let currentrow1 = ref(false);
let steptimes = ref([]);
let series = ref([]);
let heightnum=ref("0");
let maxtime=ref({
  steptime:"03:02"
});
let datetime=ref();
let jcname=ref("监测点");
let danwei=ref();
let state=ref();
let warnin=ref(0);
let warnin2=ref(0);
const min = ref(0);
const max = ref(1);
let selelist=ref();
let jgSelectPointId=ref(0);
let selobj=ref([]);
let isshow=ref(false);
let maxindex=ref();

const dynamicHeaders = ref([

]);
const props = defineProps({
  
  classradio: {
  type: String,
  // default: '',activeIndex
},
})
let classradio=ref();
const job = ref({
  jid: 0, //	任务ID
  aid: 0, //	事故ID
  starttime: "", //	结束时间
  endtime: "", //	开始时间
  state: "", //	状态
  faildes: "", //	失败原因
  dt: "", //	时间步长
  dx: "", //	空间步长
  reportstep: "", //	输出步长
  interactionstep: "", //	交互步长
  acctime: "", //	事故开始时间
  totaltime: "", //	模拟时长
  coids: "", //	物理属性ID逗号分隔
  cocodes: "", //物理属性code逗号分隔
});
const formInline = ref({
  region: "Temperature",
});

const tableData =ref( [
  // {
  //   date: '检测点',
  //   name: '1',
  //   state: '1',
  //   city: 'Los Angeles',
  //   address: 'No. 189, Grove St, Los Angeles',
  //   v1: 'CA 90036',
  //   v2: 'Home',
  // },
  // {
  //   date: '检测点',
  //   name: '1',
  //   state: '2',
  //   city: 'Los Angeles',
  //   address: 'No. 189, Grove St, Los Angeles',
  //   v1: 'CA 90036',
  //   v2: 'Office',
  // },


])
let myChart;
onMounted(() => {
  lineChart();
//   window.onresize = function() {
//     // 让图表自适应大小
//     myChart.resize();

// };
fcon.step=count.value;
});
const fcon = createFireControl();
// 检测点的结果获取
// 父组件获取的方法初始化 
const indexinit= (id,radio)=>{
  aid.value=id;
//  classradio.value=radio;
  //console.log(classradio.value);
  // fcon.step=count.value;
  // getMonitor();
  // vtkmodel.clearModeAddJg();
  // vtkGridRead()
if(props.classradio=='Fire'){
  formInline.value.region="Temperature";
}else if(props.classradio=='Water'){
  formInline.value.region="Height";
}
myChart.clear();
 readJob();
}
function regionchange(val) {
  // console.log(val)
  let newMap = new Map([
    ["Temperature", "(℃)"],
    ["Pressure", "(kg/s)"],
    ["Pressure", "(kg/s)"],
    ["CO2", "(%)"],
    ["CO2", "(%)"],
    ["H2S", "(%)"],
    ["Flow", "(Pa)"],
    ["Height", "m"],
  ]);
  newMap.forEach((value, key) => {
    // console.log(key, value);
    if (key == val) {
      danwei.value = key + value;
    }
  });
  //getMonitor();
  vtkShow();
}
//获取任务信息
async function readJob() {
const params = {
  transCode: "D10017",
  aid: aid.value,
};
await request(params)
  .then((res) => {
    if (res.returnCode == "000000000") {
      //成功
      datetime.value=res.endtime.slice(0,10);
      if(res.state=='1'){
      //  vtkmodel.clearModeAddJg(); //隐藏模版显示结果
      job.value = res;
      getMonitor();
      vtkmodel.clearModeAddJg();
      reddate(new Date());
      vtkGridRead();
      jgSelect1();
      firstshow.value=true;
      endtime.value= Number(res.totaltime)/Number(res.reportstep);
    }else if(res.state=='-1'){
      firstshow.value=false;
      ElMessage({
        message: " 求解失败",
        type: 'error',
      });
    }else if(res.state=='0'){
      firstshow.value=false;
      ElMessage({ message: "求解未完成",  type: 'error',
      });
    }
    } else {
      ElMessage({
        message: res.returnMsg,
        type: "error",
      });
    }
  })
  .catch((err) => {
    if(err.returnMsg=="任务不存在！"){
      monitor.value=false;
      console.log(1111)
      ElMessage({
        message: "未求解",
        type: 'error',
      });
         }
  });
}
//监测点数据获取
async  function getMonitor() {
  const params = {
    transCode: "D10018",
    aid: aid.value,
    step: fcon.step,
  };
  request(params)
    .then((res) => {
   
      if (res.returnCode == "000000000") {
        strResultFormatlist.value = [];
        let headertable=[];
        //let s=0;
        // dynamicHeaders.value=res.codes;
        console.log(res);
        for (let i = 0; i < res.codes.length; i++) {
          let cocode = res.codes[i];

          strResultFormatlist.value.push({
            id: i,
            name: cocode.code,
            value: cocode.code,
          });
          let num=i+1
          let newMap = new Map([
            ["Temperature", "(℃)"],
            ["Pressure", "(kg/s)"],
            ["Pressure", "(kg/s)"],
            ["CO2", "(%)"],
            ["CO2", "(%)"],
            ["H2S", "(%)"],
            ["Flow", "(Pa)"],
            ["Height", "(m)"],
          ]);
          newMap.forEach((value, key) => {
            if ( key  == res.codes[i].code ) {
              console.log(key);
              res.codes[i].code = key+value;
              
            }
          });
          headertable.push(
            { prop:'v'+num, label: res.codes[i].code },
          )
        }
          
        // strResultFormatlist.value=res.codes;
         dynamicHeaders.value=headertable;
        let warning=[];//一级警告
        let warning2=[];//二级警告
        let warning3=[];//突水发生
        let warning4=[];//安全区域
        for (let j = 0; j < res.vals.length; j++) {
           if(Number(res.vals[j].v1)==0&&Number(res.vals[j].v1)<=0.1){
            res.vals[j].state=0;
            warning4.push(res.vals[j].v1);
          }else if(Number(res.vals[j].v1)>0.1&&Number(res.vals[j].v1)<=0.5){
            res.vals[j].state=1;
            warning3.push(res.vals[j].v1);
          }else if(Number(res.vals[j].v1)>0.5&&Number(res.vals[j].v1)<=1){
            res.vals[j].state=2;
            warning2.push(res.vals[j].v1);
          }else if(Number(res.vals[j].v1)>1){
            res.vals[j].state=3;
            warning.push(res.vals[j].v1);
          }

        }
       warnin2.value=warning2.length;
       warnin.value=warning.length;
        tableData.value=res.vals;
      }
    }) .catch((err) => {
      ElMessage.error(err.returnMsg);
    });
  }
//回到上一页
function Prev() {
  currentrow1.value=false;
  isstop.value = false;
  count.value--;
  fcon.step = count.value;
  newcount.value = count.value;

}
//  下一页
function increment() {
  currentrow1.value=false;
  isstop.value = false;
  if (count.value == endtime.value) {
    return;
  }
  count.value++;
  newcount.value = count.value;
  fcon.step = count.value;
  console.log( newcount.value );

}
// 播放暂停
const play =(time)=>{
  showfalse.value=!showfalse.value;
  currentrow1.value=false;
  if(showfalse.value){
    suspendshow.value=true;
    playshow.value=false;
    isstop.value = true;//播放
  const sleep = (timeout = time) =>
    new Promise((resolve, reject) => {
      setTimeout(resolve, timeout);
    });
  let timer = async (timeout) => {
    while (count.value < endtime.value && isstop.value) {
      if (isstop.value == true) {
        await sleep(time);
        count.value++;
        fcon.step = count.value;
        newcount.value = count.value;
  
      }
    }
  };
  console.log(count.value)
  timer(time); 
  }else{
    isstop.value = false;//暂停
    playshow.value=true;
    suspendshow.value=false;
}
}
function sliderchange(val) {
  suspendshow.value=false;
    playshow.value=true;
  isstop.value = false;
  newcount.value = count.value;
  fcon.step = count.value;
  console.log(count.value);

}
const tableRowClassName=()=>{

}
//获取最大值的下标
function firstOccurrenceOfMax(arr) {
    var max = arr[0];
    //声明了个变量 保存下标值
    var index = 0;
    for (var i = 0; i < arr.length; i++) {
        if (max < arr[i]) {
            max = arr[i];
            index = i;
        }
    }
    maxindex.value=index
    return index;
}

// 随机颜色
const randomColor=()=>{
            var letters = '0123456789ABCDEF';
            var color = '#';
            do {
                for (var i = 0; i < 6; i++) {
                    color += letters[Math.floor(Math.random() * 16)];
                }
            } while (color === '#FFFFFF' || color === '#000000');
          console.log(color);
            return color;
        }
// 批量数据
const handleDelete=(event)=>{
 jcname.value=event.chname;

  currentrow1.value=true;
  const params = {
    transCode: "D10019",
    aid: aid.value,
    chname: event.chname,
  };
  request(params)
    .then((res) => {
      series.value=[];
      steptimes.value=[];
      if (res.returnCode == "000000000") {
        for (let j = 0; j < res.steptimes.length; j++) {
          steptimes.value.push(Object.values(res.steptimes[j]));
        }     
        for (let i = 0; i < res.rows.length; i++) {
          let arr=[];
          for (let k = 0; k < res.rows[i].data.length; k++) {
            if(res.rows[i].data[k].val<0){
              
            }
            arr.push(res.rows[i].data[k].val);
          }
          // var arr = Array.from(Object.values(res.rows[i].data),x=>x);
          series.value.push({
         name:res.rows[i].code,
         type: 'line',
         showSymbol: false,
          smooth: true,
          data:arr,//res.rows[i].data
          })
       }
        firstOccurrenceOfMax(series.value[0].data)
        const max = Math.max(...series.value[0].data);
        maxtime.value= res.steptimes[ maxindex.value];
        console.log(maxtime.value);
        console.log(1111)
        heightnum.value=max;
      }
      lineChart();
    }) .catch((err) => {
      ElMessage.error(err.returnMsg);
    });

}
const funidshow=(val)=>{
  isshow.value=val;
}

// 获取点的数据
function jgSelect1(event) {
 // console.log(event.pageX);
  timing2.value = setInterval(() => {
    //定时器

    if (jgSelectPointId.value != vtkmodel.selectJgPointId) {
    // console.log("pointid",vtkmodel.selectJgPointId);//选择的点数据
      //获取点对应的Scalar
      isshow.value=true;
      htmldialogref.value.X=Number(vtkmodel.epageX)+'px';
      htmldialogref.value.Y=Number(vtkmodel.epageY)+'px';
      
       jgSelectPointId.value = vtkmodel.selectJgPointId;
       
      selobj.value = [];
      for (const key of fcon.scalar.keys()) {
        selobj.value.push({
          name: key,
          value: fcon.scalar.get(key)[vtkmodel.selectJgPointId],
        });
      }
      console.log(selobj.value);
      // console.log(window.style.left )
     // msgval.value = selobj.value;
     htmldialogref.value.getdatahtml(selobj.value);
 }
  }, 1000);
}
const linedata=()=>{

}
const lineChart=()=>{
  // console.log(series.value);
  var chartDom = document.getElementById('line');
 myChart = echarts.init(chartDom);
//  myChart = echarts.init(document.getElementById('line'));
 
let option = {
  tooltip: {
    trigger: 'axis'
  },
  // legend: {
  //   data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
  // },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },

  xAxis: {
    type: 'category',
    boundaryGap: false,
    data:steptimes.value,
  },
  yAxis: {
    type: 'value'
  },
  series: series.value
};
    option && myChart.setOption(option);
   window.onresize = function() {
    // 让图表自适应大小
    myChart.resize();
};
}
function reddate(date) {
  //当前时间
  const timestamp = date.getTime();
  // newtime.value = timestampToTime(timestamp);
  const accstamp = Date.parse(job.value.acctime);
  var timeDifference = parseInt((timestamp - accstamp) / 1000);
  fcon.stepsum = parseInt(job.value.totaltime) / parseInt(job.value.reportstep);
  if (timeDifference < parseInt(job.value.totaltime)) {
    //最长时间范围
    fcon.step = parseInt(timeDifference / parseInt(job.value.reportstep));
  } else {
    fcon.step = fcon.stepsum;
  }
  count.value = fcon.step;
  newcount.value = count.value;
}
function velocityRead() {
  return;
  // clearInterval(arrowtime.value);
   fcon
    .getVelocityByStep(fcon.step)
    .then((result) => {
        vtkmodel.addArrow(fcon.velocitys);
        // arrowtimeStart();
    })
    .catch((err) => {
      console.log(err);
    });
}
function getMinMax(scalars) {
  // console.log("getMinMax:",scalars);
  min.value = 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;
    }
  }
  if( min.value== max.value){
     max.value=min.value+1;
  }
  console.log("max，min:", max.value, min.value);
}
function vtkShow() {

  const scalarBarActor = vtkmodel.scalarBarActor;
  const mapper = vtkmodel.jgMapper;
  const actor = vtkmodel.jgActor;
  if (!fcon.scalar) {
    return;
  }
  const scalarArray = fcon.scalar.get(formInline.value.region);
  if (!scalarArray || !fcon.polydata) {
    return;
  }

  console.log("scalarArray:", scalarArray);
  const dataArray = vtkDataArray.newInstance({
    name: formInline.value.region,
    size: fcon.polydata.getNumberOfPoints(),
  });
  console.log("执行了");
  // console.log(dataArray);
  dataArray.setData(scalarArray);
  fcon.polydata.getPointData().setScalars(dataArray);
  // fcon.polydata.getPointData().setOpacity(dataArray);
  mapper.setInputData(fcon.polydata);
  getMinMax(scalarArray);
  mapper.setScalarRange(
    parseFloat(min.value.toFixed(3)),
    parseFloat(max.value.toFixed(3))
  ); //设置范围
  // actor.setMapper(mapper);
  scalarBarActor.setAxisLabel(formInline.value.region);
  mapper.clearColorArrays(); //强制重建颜色
  actor.getProperty().setOpacity(count.value); //设置错误的透明度使得页面重新加载  不设置不刷新页面
  actor.getProperty().setOpacity(0.5);
  // vtkmodel.renderer.resetCamera();
  vtkmodel.renderWindow.render();
  
}

function vtkGridRead() {
  fcon.aid = aid.value;
  fcon
    .initGemetry()
    .then((result) => {
     vtkScalarRead();
    vtkmodel.renderWindowWith.resize();
    })
    .catch((err) => {});
}
function vtkScalarRead() {
  fcon
    .getScalrsByStep(fcon.step)
    .then((result) => {
      // velocityRead() ;
      vtkShow();
    })
    .catch((err) => {
     // console.log(err);
    });
}
watch(
  newcount,
  (newVal, oldVal) => {
console.log("值改变了", newVal, oldVal);
    fcon.step = newVal;
    getMonitor();
    vtkScalarRead();
 //   vtkScalarRead();
if( newVal>=endtime.value){
  playshow.value=true;
  suspendshow.value=false;
   isstop.value = false;
}
  },
  { deep: true }
); //深度监视
defineExpose({firstshow,isshow,indexinit});
</script>
<style lang="scss" scoped>
.el-slider {
    width: 100%;
    height: 32px;
    display: flex;
    align-items: center;
}

.tanniu{
display: flex;
justify-content:space-between;
align-items: center;

}
</style>
