<template>
  <!-- 底部导航栏 -->
  <div class="first-right l_Dialog tablebk"  v-show="firstshow">
    <el-aside width="340px" class="L_aside L_aside1 asideg asidegbg leftbgimg1" v-show="firstshow">
      <div class="demo-collapse jiancedian1 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:1.03rem;"></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">2024-03-20</p><p>14:23:00</p></div>
              </div>
            </div>
            </div>
          </div>
            <!-- <div class="mgsnoe" style="height: 200px"></div> -->
          </el-collapse-item>
        </el-collapse>
        <el-collapse accordion v-model="activeNames" class="bganimation">
          <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="animation_s">
              <el-slider
                :max="60"
                :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><el-image :src="t2" fit="contain" v-show="suspendshow" @click="play(500)" ></el-image></div>
                <div><el-image :src="t4" fit="contain" v-show="playshow" @click="play(500)" ></el-image></div>
                <div><el-image :src="t3" 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>
    <!-- 动画 -->
    <!-- <el-aside width="340px" class="L_aside L_aside1 asideg asidegbg leftbgimg1" v-show="firstshow">
      <div class="demo-collapse jiancedian1 asideg1 jc_header collapseeion jianstyle">
      
      </div>
    </el-aside> -->
  </div>
</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/bt.png";
let firstshow = ref(false);
let activeNames = ref(["1"]);
let tableHeight = ref(130);
let playshow=ref(true);
let suspendshow=ref(false);
let showfalse=ref(false);
let c=ref("0");
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 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();
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(() => {
//   window.onresize = function() {
//     // 让图表自适应大小
//     myChart.resize();

// };
fcon.step=count.value;
});
const fcon = createFireControl();
// 检测点的结果获取
// 父组件获取的方法初始化 
const indexinit= (id,radio)=>{
  aid.value=id;
console.log(props.classradio);
//  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";
}
 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,
};
console.log(111112222233343433+1)
await request(params)
  .then((res) => {
    if (res.returnCode == "000000000") {
      //成功
    
      if(res.state=='1'){
      //  vtkmodel.clearModeAddJg(); //隐藏模版显示结果
      job.value = res;
      getMonitor();
      vtkmodel.clearModeAddJg();
      reddate(new Date());
      vtkGridRead();
  
      endtime.value= Number(res.totaltime)/Number(res.reportstep);
      console.log( endtime.value);
    }else if(res.state=='-1'){
      ElMessage({
        message: " 求解失败",
        type: 'error',
      });
    }else if(res.state=='0'){
      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(res.vals[j].v1<=1&&res.vals[j].v1<2){
            res.vals[j].state=0;
          }else{
            if(res.vals[j].v1 >= 2&&res.vals[j].v1< 10){
            res.vals[j].state=1;
          }else if(res.vals[j].v1>=10&&res.vals[j].v1<120){
            res.vals[j].state=2;
            warning2.push(res.vals[j].v1)
          }else if(res.vals[j].v1>160){
            warning.push(res.vals[j].v1)
            res.vals[j].state=3;

          }
     
          }
          // else{
          //   console.log(22222)

          // }

        }
       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{
    playshow.value=true;
    suspendshow.value=false;
    isstop.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=()=>{

}
// 批量数据
const handleDelete=(event)=>{
 jcname.value=event.chname;

 series.value=[];
 steptimes.value=[];
  currentrow1.value=true;
//let arr=[];
  const params = {
    transCode: "D10019",
    aid: aid.value,
    chname: event.chname,
  };
  request(params)
    .then((res) => {
      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
         itemStyle:{
           normal:{
             color: {
               type: 'linear',
               x: 0,
               y: 0,
               x2: 0,
               y2: 1,
               colorStops: [
               {
                 offset:1, color: '#ACD6FF ' // 0% 处的颜色
               },
               {
                 offset:0.7, color: '#105CF0 '// 100% 处的颜色
               },
               {
                 offset:0.66, color: '#FF7A00 '// 100% 处的颜色
               },
               {
                 offset:0.2, color: '#FF0000 '// 100% 处的颜色
               },
               {
                 offset:0, color: '#CE0000' // 0% 处的颜色FF7A00
               }, 
              
              ],
            
               global: false // 缺省为 false
             }
           }
         },
         lineStyle: {
                    width: 3, // 设置线条宽度
                },
          })
        }
        const max = Math.max(...series.value[0].data);
        heightnum.value=max;
      }
      lineChart();
    }) .catch((err) => {
      ElMessage.error(err.returnMsg);
    });

}
const linedata=()=>{

}
const lineChart=()=>{
  // console.log(series.value);

 myChart = echarts.init(document.getElementById('line'));
  let option = {
     tooltip: {
       trigger: 'axis',
     },
     grid: {
       left: '0',
       right: '0',
       bottom: '10',
       top:'20',
       containLabel: true
     },
     xAxis: [
       {
         type: 'category',
         data:steptimes.value,
         splitLine: {
           show: false,
         },
         axisLine: {
           lineStyle: {
             type: 'solid',
             color: '#E6E7EC',//左边线的颜色
             width:'1'//坐标线的宽度
           }
         },
         axisLabel: {
           textStyle: {
             color: '#B8CED6',//坐标值得具体的颜色
           }
         }
       }
     ],
     yAxis: [
       {
         type: 'value',
         minInterval:1,
         splitNumber: 5, 
         max: 700,
         splitLine: {
           show: true,
           lineStyle:{
             type:'dashed'
           }
         },
         axisLine: {
           lineStyle: {
             type: 'solid',
              color: '#E6E7EC',//左边线的颜色
             width:1 //坐标线的宽度
           }
         },
         axisLabel: {
          type: 'value',
           textStyle: {
          color: function (value, index) {
            if(value >=300){
              return '#CE0000 '
            } else{
              return  '#ACD6FF'
            }
              // return value >= 120 ? '#CE0000  ': '#ACD6FF';
          }
           
           }
         }
       }
     ],
     color: 'rgba(37, 190, 171, 1)',
     series:series.value
   }
   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;

  // console.log(formInline.value.region);

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

  },
  { deep: true }
); //深度监视
defineExpose({firstshow,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>
