<template>
  <div class="p-2">
    <el-row :gutter="28">
      <el-col :span="4.3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="workUnitName"
            placeholder="请输入计量设备名称"
            clearable

            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="monitorInfoOptions"
            :props="monitorProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
                 label-width="100px"
        >
          <!--          <el-form-item label="计量设备编号" prop="monitorCode">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.monitorCode"-->
          <!--              placeholder="请输入计量设备编号"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item label="采集时间">
            <el-date-picker
              v-model="daterangeCollectTime"
              style="width: 340px"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <Chart ref="Chart1" class="chart1"/>
        <Chart ref="Chart2" class="chart2"/>
        <Chart ref="Chart3" class="chart3"/>
        <Chart ref="Chart4" class="chart4"/>
      </el-col>
    </el-row>


  </div>
</template>

<script>

import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo'
import Treeselect from 'vue3-treeselect';
import 'vue3-treeselect/dist/vue3-treeselect.css';
import { parseTime } from '@/utils/ruoyi'
import Chart from '@/components/chart.vue'
import * as echarts from 'echarts'
import { vibrationInstantList } from '@/api/ems/record/recordVibrationInstant'

export default {
  name: 'currentVibrationCurve',
  dicts: ['collect_type'],
  computed: {
    collect_type() {
      return this.useDict('collect_type').collect_type;
    },
  },
  components: {
    Chart,
    Treeselect
  },
  data() {
    return {
      //下拉树List
      baseMonitorInfoOptions: [],
      //左侧树结构List
      monitorInfoOptions: [],
      workUnitName: undefined,
      //左侧树结构 检索设备名称
      selectMonitorName: null,
      //计量设备信息
      baseMonitorInfoList: [],
      // 采集方式时间范围
      daterangeCollectTime: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电实时数据表格数据
      dataList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        objId: null,
        collectTime: null,
        sensorId: null,
        speed: null,
        displacement: null,
        acceleration: null,
        temperature: null,
        recodeTime: null,
        remark: null
      },
      // 表单参数
      form: {},
      monitorProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        objId: [
          { required: true, message: '编号不能为空', trigger: 'blur' }
        ]
      },
      columns: [
        { key: 0, label: `主键标识`, visible: false },
        { key: 1, label: `采集时间`, visible: true },
        { key: 2, label: `振动传感器编号编号`, visible: true },
        { key: 3, label: `速度(mm/s)`, visible: true },
        { key: 4, label: `位移(um)`, visible: true },
        { key: 5, label: `加速度(g)`, visible: true },
        { key: 6, label: `温度(℃)`, visible: true },
        { key: 7, label: `记录时间`, visible: true },
        { key: 8, label: `备注`, visible: true },
      ]
    }
  },
  created() {
    const nowDate = parseTime(new Date(), '{y}-{m}-{d}')
    this.daterangeCollectTime[0] = nowDate + ' 00:00:00'
    this.daterangeCollectTime[1] = nowDate + ' 23:59:59'
    this.getTreeselect()
    this.getList()
  },
  watch: {
    // 根据名称筛选计量设备树
    workUnitName(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    /** 转换计量设备信息数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.monitorCode,
        label: node.monitorName,
        children: node.children
      }
    },
    /** 查询电实时数据列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCollectTime && '' != this.daterangeCollectTime) {
        this.queryParams.params['beginCollectTime'] = this.daterangeCollectTime[0]
        this.queryParams.params['endCollectTime'] = this.daterangeCollectTime[1]
      }
      // 将monitorCode改为sensorId
      if (this.queryParams.sensorId !== null) {
        this.queryParams.params['sensorId'] = this.queryParams.sensorId;
      }
      this.getChart()
    },

    // 取消按钮
    cancel() {
      dialogOpen.value = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        objId: null,
        collectTime: null,
        sensorId: null,
        speed: null,
        displacement: null,
        acceleration: null,
        temperature: null,
        recodeTime: null,
        remark: null
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.monitorCode = null
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/record/recordVibrationInstant/export', {
        ...this.queryParams
      }, `recordVibrationInstant_${new Date().getTime()}.xlsx`)
    },

    /** 查询计量设备信息下拉树结构 */
    getTreeselect() {
      getMonitorInfoTree({ monitorType: 10 }).then(response => {
        this.monitorInfoOptions = response.data
      })
    },

    /** 筛选节点 */
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    /** 节点单击事件 */
    handleNodeClick(data) {
    /*  this.queryParams.monitorCode = data.code*/
      this.queryParams.sensorId = data.code
      console.log("this.queryParams.sensorId"+this.queryParams.sensorId)

      this.selectMonitorName = data.label
      this.handleQuery()
    },

    /** 震动曲线 */
    async getChart() {
      if (this.queryParams.sensorId == null) {
        return
      }
      let query = JSON.parse(JSON.stringify(this.queryParams))
      const {data} = await vibrationInstantList(query)
      const timeData = data.map(e => e.collectTime);
      const chartGridConfig = {
        top: 50,
        bottom: 70,
        left: 20,
        right: 20,
        containLabel: true
      };
      const chartDataZoom = [
        { type: 'slider', height: 18, bottom: 8, start: 0, end: 100 },
        { type: 'inside', zoomOnMouseWheel: true, moveOnMouseMove: true }
      ];
      const xAxisConfig = {
        type: 'category',
        data: timeData,
        axisLine: { show: true, lineStyle: { color: '#000000' } },
        axisTick: { show: true, alignWithLabel: true },
        axisLabel: {
          show: true,
          color: '#000000',
          rotate: timeData.length > 20 ? 45 : 0,
          interval: 'auto',
          formatter: function(value) {
            if (value && value.length > 16) return value.substring(11, 19);
            return value;
          }
        }
      };
      const createYAxisConfig = (name) => ({
        type: 'value',
        name: name,
        nameTextStyle: { color: '#000000' },
        splitLine: { show: true, lineStyle: { type: 'dashed', color: '#e0e0e0' } },
        axisTick: { show: true },
        axisLine: { show: true, lineStyle: { color: '#000000' } },
        axisLabel: { show: true, color: '#000000' },
        scale: true,
        splitNumber: 5
      });

      let option1 = {
        title: { text: this.selectMonitorName + ' 速度曲线', x: 'center' },
        grid: chartGridConfig,
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { show: true } } },
        dataZoom: chartDataZoom,
        legend: { right: 0, top: 5 },
        xAxis: xAxisConfig,
        yAxis: [createYAxisConfig('速度(mm/s)')],
        series: [{
          name: '速度(mm/s)',
          type: 'line',
          smooth: true,
          showAllSymbol: true,
          symbol: 'circle',
          symbolSize: 6,
          data: data.map(e => e.speed)
        }]
      }
      let option2 = {
        title: { text: this.selectMonitorName + ' 温度曲线', x: 'center' },
        grid: chartGridConfig,
        dataZoom: chartDataZoom,
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { show: true } } },
        legend: { right: 0, top: 5 },
        xAxis: xAxisConfig,
        yAxis: [createYAxisConfig('温度(℃)')],
        series: [{
          name: '温度(℃)',
          type: 'line',
          smooth: true,
          showAllSymbol: true,
          symbol: 'circle',
          symbolSize: 6,
          data: data.map(e => e.temperature)
        }]
      }
      let option3 = {
        title: { text: this.selectMonitorName + ' 位移曲线', x: 'center' },
        grid: chartGridConfig,
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { show: true } } },
        dataZoom: chartDataZoom,
        legend: { right: 0, top: 5 },
        xAxis: xAxisConfig,
        yAxis: [createYAxisConfig('位移(um)')],
        series: [{
          name: '位移(um)',
          type: 'line',
          smooth: true,
          showAllSymbol: true,
          symbol: 'circle',
          symbolSize: 6,
          data: data.map(e => e.displacement)
        }]
      }
      let option4 = {
        title: { text: this.selectMonitorName + ' 加速度曲线', x: 'center' },
        grid: chartGridConfig,
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { show: true } } },
        dataZoom: chartDataZoom,
        legend: { right: 0, top: 5 },
        xAxis: xAxisConfig,
        yAxis: [createYAxisConfig('加速度(g)')],
        series: [{
          name: '加速度(g)',
          type: 'line',
          smooth: true,
          showAllSymbol: true,
          symbol: 'circle',
          symbolSize: 6,
          data: data.map(e => e.acceleration)
        }]
      }
      this.$refs.Chart1.setData(option1)
      this.$refs.Chart2.setData(option2)
      this.$refs.Chart3.setData(option3)
      this.$refs.Chart4.setData(option4)
      echarts.connect(this.$refs.Chart1.chart, this.$refs.Chart2.chart, this.$refs.Chart3.chart, this.$refs.Chart4.chart)
      this.$refs.Chart1.chart.on('datazoom', (e) => {
        option2.dataZoom[0].start = e.start
        option2.dataZoom[0].end = e.end
        this.$refs.Chart2.setData(option2)
        option3.dataZoom[0].start = e.start
        option3.dataZoom[0].end = e.end
        this.$refs.Chart3.setData(option3)
        option4.dataZoom[0].start = e.start
        option4.dataZoom[0].end = e.end
        this.$refs.Chart4.setData(option4)
      })
      this.$refs.Chart2.chart.on('datazoom', (e) => {
        option1.dataZoom[0].start = e.start
        option1.dataZoom[0].end = e.end
        this.$refs.Chart1.setData(option1)
        option3.dataZoom[0].start = e.start
        option3.dataZoom[0].end = e.end
        this.$refs.Chart3.setData(option3)
        option4.dataZoom[0].start = e.start
        option4.dataZoom[0].end = e.end
        this.$refs.Chart4.setData(option4)
      })
      this.$refs.Chart3.chart.on('datazoom', (e) => {
        option2.dataZoom[0].start = e.start
        option2.dataZoom[0].end = e.end
        this.$refs.Chart2.setData(option2)
        option1.dataZoom[0].start = e.start
        option1.dataZoom[0].end = e.end
        this.$refs.Chart1.setData(option1)
        option4.dataZoom[0].start = e.start
        option4.dataZoom[0].end = e.end
        this.$refs.Chart4.setData(option4)
      })
      this.$refs.Chart4.chart.on('datazoom', (e) => {
        option2.dataZoom[0].start = e.start
        option2.dataZoom[0].end = e.end
        this.$refs.Chart2.setData(option2)
        option3.dataZoom[0].start = e.start
        option3.dataZoom[0].end = e.end
        this.$refs.Chart3.setData(option3)
        option1.dataZoom[0].start = e.start
        option1.dataZoom[0].end = e.end
        this.$refs.Chart4.setData(option1)
      })
    }
  }
}
</script>
<style scoped>
.chart1,
.chart2,
.chart3,
.chart4 {
  display: inline-block;
  width: calc(50% - 5px);
  height: calc(45vh - 60px);
  min-height: 280px;
  max-height: 380px;
  vertical-align: top;
}

@media screen and (max-width: 1200px) {
  .chart1,
  .chart2,
  .chart3,
  .chart4 {
    width: 100%;
    height: calc(40vh - 50px);
    min-height: 260px;
  }
}

@media screen and (max-width: 768px) {
  .chart1,
  .chart2,
  .chart3,
  .chart4 {
    height: 35vh;
    min-height: 240px;
  }
}
</style>
