<template>
  <div class="container"
       :style="'background-image: url('+((controlList&& controlList.length === 0) ? bgImg1 : bgImg)+')'">
    <div class="title1">监控设备</div>
    <div class="centerImg"></div>
    <div class="title">监控单元</div>
    <div class="tree">

      <el-tree
        :data="treeData"
        accordion
        node-key="id"
        @node-click="treeClick">
    <span slot-scope="{ node, data }" class="custom-tree-node">
      <span>{{ node.label }}</span>
    </span>
      </el-tree>
    </div>
    <div v-if="show" :class="((controlList&& controlList.length === 0) ? 'equipmentInfo1' : 'equipmentInfo')">
      <p>
        <span>名称：</span>
        <span style="color: #d9dee3">{{ MonitorInfo.monitorUnitName }}</span>
      </p>
      <p>
        <span>ID：</span>
        <span style="color: #d9dee3">{{ MonitorInfo.monitorUnitId }}</span>
      </p>
      <p>
        <span>状态：</span>
        <span style="color: #d9dee3">{{ MonitorInfo.monitorUnitStatus === '1' ? '正常' : '异常' }}</span>
      </p>
      <p>
        <span>类型：</span>
        <span style="color: #d9dee3">{{ MonitorInfo.monitorUnitTypeName }}</span>
      </p>
    </div>
    <div v-if="show"
         :style="'background-image: url('+(MonitorInfo.monitorPic ? MonitorInfo.monitorPic :defaultImg)+');'"
         :class="((controlList&& controlList.length === 0) ? 'img1' : 'img')"></div>
    <div class="terminal">
      <div class="terminalList">
        <div v-for="(i,k) in controlList" class="item">
          <div :style="'background-image: url('+(i.devicePic ? i.devicePic :defaultImg1)+');'" class="icon"></div>
          <div class="title">{{ i.deviceName + ' - ' + i.deviceModeFunction.functionName }}</div>
          <div class="switch">
            <el-button
              size="mini"
              type="primary"
              @click="switchChange(i.deviceModeFunction.functionIdentifier,i.deviceId,i.deviceCode,i.deviceModeFunction.modeFunctionId)">
              执行
            </el-button>
            <!--            <el-switch-->
            <!--              v-model="i.deviceType==='1'"-->
            <!--              active-color="#1165a1"-->
            <!--              inactive-color="#1facf4"-->
            <!--              @change="switchChange(i.deviceModeFunction.functionIdentifier,i.deviceId,i.deviceCode,i.deviceModeFunction.modeFunctionId)">-->
            <!--            </el-switch>-->
          </div>
        </div>
      </div>
    </div>
    <div class="right">
      <div v-for="(i,k) in acquisitionList" class="item">
        <!--        <div class="iconBg"></div>-->
        <!--        <div-->
        <!--          class="icon">-->
        <!--          <el-image-->
        <!--            v-if="i.deviceDataMap[Object.keys(i.deviceDataMap).find(e=> i.deviceDataMap[e].toString().includes('http'))]"-->
        <!--            :preview-src-list="[i.deviceDataMap[Object.keys(i.deviceDataMap).find(e=> i.deviceDataMap[e].toString().includes('http'))]]"-->
        <!--            :src="i.deviceDataMap[Object.keys(i.deviceDataMap).find(e=> i.deviceDataMap[e].toString().includes('http'))]"-->
        <!--            style="width: 100%; height: 100%">-->
        <!--          </el-image>-->
        <!--          <el-image-->
        <!--            v-else-if="i.devicePic"-->
        <!--            :src="i.devicePic"-->
        <!--            style="width: 100%; height: 100%">-->
        <!--          </el-image>-->
        <!--          <el-image-->
        <!--            v-else-->
        <!--            :src="defaultImg1"-->
        <!--            style="width: 100%; height: 100%">-->
        <!--          </el-image>-->
        <!--        </div>-->
        <div class="rightBg">
          <div class="index">{{ k + 1 }}</div>
          <div class="title">{{ i.deviceName }}</div>
          <div style="position: absolute;left: 27%;top: 0px;width: 45%;height: 100%;">
            <div
              v-for="val in Object.keys(i.deviceDataMap).slice(0,6).filter(e=> !(i.deviceDataMap[e].toString().includes('http')))"
              :style="'width:'+(Object.keys(i.deviceDataMap).length<=2 ? '100%':'50%')" class="infoItem">
              <div class="span">{{ val }}:</div>
              <div class="spanBg"></div>
              <div class="num">{{ i.deviceDataMap[val] }}</div>
            </div>
            <div class="infoItem">
              <div class="span"> 时间 :</div>
              <div class="spanBg"></div>
              <div class="num">{{ i.updateTime }}</div>
            </div>

          </div>
          <div class="btn">
            <div class="btnC" style="top: 50%">
              <el-button type="primary" @click="toHistory(i.deviceId,i.deviceModeId)" size="mini">历史记录</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="历史记录" :visible.sync="historyDialog">
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="查询时间">
          <el-date-picker
            v-model="form.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="查询类型">
          <el-select v-model="form.type" placeholder="">
            <el-option label="趋势分析" value="1"></el-option>
            <el-option label="历史数据" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getHistoryData">查询</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 12px">
        <el-button type="primary" @click="exportF">导出</el-button>
        <el-button type="success" @click="comparison">对比</el-button>
      </div>
      <el-table
        :data="historyData"
        v-loading="loading1"
        v-if="isHistoryTable"
        style="width: 100%">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          v-for="i in Object.keys(historyTh)"
          v-if="historyTh[i]"
          :prop="i"
          :label="historyTh[i]"
          width="180">
          <template slot-scope="scope">
            <div v-if="historyTh[i] === '时间'">{{ parseTime(scope.row['ts']) }}</div>
            <div v-else>{{ scope.row[historyTh[i]] }}</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="isHistoryTable"
        v-show="total>0"
        :total="total"
        :page.sync="form.pageNum"
        :limit.sync="form.pageSize"
        @pagination="getHistoryData"
      />
      <Chart v-if="!isHistoryTable" ref="historyChart" class="historyChart"></Chart>
    </el-dialog>

    <el-dialog title="对比" :visible.sync="comparisonDialog">
      <el-form ref="form1" :rules="rules" :inline="true" :model="form1" class="demo-form-inline">
        <el-form-item label="查询时间" prop="time">
          <el-date-picker
            v-model="form1.time"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="传感器" prop="sensor">
          <el-cascader
            v-model="sensorData"
            :options="sensorOptions"
            :props="props"
            collapse-tags
            @change="sensorChange"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="对比属性" prop="prop">
          <el-select v-model="form1.prop" placeholder="">
            <el-option v-for="i in comparisonOptions" :label="i" :value="i"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getComparisonData">查询</el-button>
        </el-form-item>
      </el-form>
      <div v-loading="loading2">
        <Chart ref="chart" class="chart"></Chart>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  treeList,
  selectDevicesByMonitorUnitId,
  getMonitorById,
  publishControlCommand,
  selectHistoryAndTrendAnalysis,
  selectComparison,
  exportData
} from '@/api/board/equipment'
import defaultImg from '@/assets/board/equipment/icon.png'
import defaultImg1 from '@/assets/board/equipment/icon2.png'
import defaultImg2 from '@/assets/board/equipment/defaultImg.png'
import bgImg from '@/assets/board/equipment/bg.jpg'
import bgImg1 from '@/assets/board/equipment/bg2.jpg'
import Chart from '@/components/Charts/Chart'


let getDeviceInterval = null
export default {
  components: {Chart},
  data() {
    const validatePass = (rule, value, callback) => {
      if (this.sensorData.length > 5) {
        return callback(new Error('最多选择五个传感器'));
      } else {
        callback()
      }
    }
    return {
      defaultImg,
      defaultImg1,
      defaultImg2,
      bgImg,
      bgImg1,
      rules: {
        sensor: [
          {validator: validatePass, trigger: 'change'}
        ],
        prop: [
          {required: true, message: '请选择对比属性', trigger: 'change'}
        ]
      },
      loading1: false,
      loading2: false,
      show: false,
      monitorUnitId: '',
      data1: true,
      treeData: [],
      controlList: [],
      acquisitionList: [],
      MonitorInfo: {},
      sceneId: 0,
      deviceId: '',
      historyDialog: false,
      form: {},
      form1: {
        time: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24), new Date()],
      },
      historyData: [],
      historyTh: {},
      isHistoryTable: true,
      total: 100,
      comparisonDialog: false,
      sensorOptions: [],
      sensorData: '',
      comparisonOptions: [],
      props: {
        multiple: true,
        value: 'voId',
        label: 'voName',
        children: 'voList'
      },
      propArr: [],
    }
  },
  async mounted() {
    await this.getData()
    this.sceneId = this.$store.getters.sceneId
    if (this.$route.query.monitorUnitId) {
      this.deviceId = this.$route.query.monitorUnitId
      await this.treeClick({id: this.$route.query.monitorUnitId})
    }
  },
  beforeDestroy() {
    clearInterval(getDeviceInterval)
  },
  methods: {
    async getData() {
      await this.getTree()
    },
    switchChange(functionIdentifier, deviceId, deviceCode, modeFunctionId) {
      this.$confirm('确定执行么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        publishControlCommand({
          deviceId: deviceId,
          modeFunctionId: modeFunctionId,
          deviceCode: deviceCode,
          type: functionIdentifier,
        }).then(e => {
          if (e.code === 200) {
            this.$message({
              type: 'success',
              message: '成功!'
            });
            const device = this.controlList.find(e => e.deviceId === deviceId);
            device.deviceType = device.deviceType === '1' ? '0' : '1';
            // this.controlList.find(e => e.deviceId === deviceId).deviceType === '1' ? this.controlList.find(e => e.deviceId === deviceId).deviceType = '0' : this.controlList.find(e => e.deviceId === deviceId).deviceType = '1'
          } else {
            this.$message({
              type: 'info',
              message: '网络错误'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },
    async getTree() {
      if (this.$store.getters.sceneId) {
        const {data} = await treeList(this.$store.getters.sceneId)
        this.treeData = data
      }
    },
    async treeClick(e) {
      if (!e.children?.length > 0) {
        this.monitorUnitId = e.id
        await this.getDevice(e.id)
        await this.setMonitorById(e)
        this.show = true
        if (typeof getDeviceInterval === 'number') {
          clearInterval(getDeviceInterval)
        }
        getDeviceInterval = setInterval(() => {
          this.getDevice(e.id)
        }, 30 * 1000)
      }
    },
    async getDevice(e) {
      if (this.$store.getters.sceneId) {
        const {data} = await selectDevicesByMonitorUnitId(e, this.$store.getters.sceneId)
        this.deviceId = e
        this.controlList = data.control
        this.acquisitionList = data.acquisition
      }
    },
    async setMonitorById(e) {
      const {data} = await getMonitorById(e.id)
      this.MonitorInfo = data
    },
    toHistory(e, i) {
      // this.$router.push({path: "/board/senso", query: {id: e, deviceModeId: i}});
      this.historyDialog = true
      this.form = {
        pageNum: 1,
        pageSize: 10,
        deviceIds: e,
        time: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24), new Date()],
        type: "2",
      }
      this.getHistoryData()
    },
    async getHistoryData() {
      this.loading1 = true
      let query = JSON.parse(JSON.stringify(this.form))
      query.startTime = this.parseTime(this.form.time?.[0]?.getTime())
      query.endTime = this.parseTime(this.form.time?.[1]?.getTime())
      delete query.time
      const data = await selectHistoryAndTrendAnalysis(query)
      this.loading1 = false
      if (query.type === '1') {

        this.isHistoryTable = false
        this.$nextTick(() => {
          let series = Object.keys(data.mapName).map(e => {
            if (data.mapName[e]) {
              return {
                name: data.mapName[e],
                type: 'line',
                stack: 'Total',
                data: data.tableDataInfo.rows.map(v => [new Date(v.ts), v[e]])
              }
            }
          })
          this.$refs.historyChart.setData({
            tooltip: {
              trigger: 'axis'
            },
            legend: {},
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'time',
              boundaryGap: false,
            },
            yAxis: {
              type: 'value'
            },
            series: series
          })
        })
      }
      if (query.type === '2') {
        this.isHistoryTable = true
        this.$nextTick(() => {
          this.historyData = data.tableDataInfo.rows
          this.historyTh = data.mapName
          if (Object.keys(data.mapName).includes('ts')) {
            this.historyTh.ts = '时间'
          }
          console.log(this.historyTh)
          this.total = data.tableDataInfo.total
        })
      }
    },
    async comparison() {
      this.comparisonDialog = true
      const data = await selectComparison()
      let propArr = []
      const f = (arr) => {
        arr.forEach(v => {
          if (v.voList) {
            f(v.voList)
          } else {
            propArr.push({
              id: v.voId,
              name: v.voName,
              props: (v.prop || '').split(',')
            })
          }
        })
      }
      f(data.data)
      this.propArr = propArr
      this.sensorOptions = data.data
    },
    sensorChange(e) {
      let comparisonData = []
      let sensorArr = []
      e.forEach(v => {
        sensorArr.push(v.at(-1))
        comparisonData = [...new Set([...comparisonData, ...(this.propArr.find(item => item.id === v.at(-1))?.props || [])])].filter(v => v)
      })
      this.comparisonOptions = comparisonData
      this.form1.sensor = sensorArr
    },
    getComparisonData() {
      this.$refs['form1'].validate(async (valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify({
            ...this.form1,
            deviceIds: this.form1.sensor.join(','),
            startTime: this.parseTime(this.form1.time?.[0]?.getTime()),
            endTime: this.parseTime(this.form1.time?.[1]?.getTime())
          }))
          delete query.time
          delete query.sensor
          this.loading2 = true
          const data = await selectHistoryAndTrendAnalysis(query)
          this.loading2 = false
          let chartData = {}
          data.tableDataInfo.rows.forEach(e => {
            if (chartData[e.deviceId]) {
              chartData[e.deviceId].push({
                value: [new Date(e.ts), e.functionIdentifier]
              })
            } else {
              chartData[e.deviceId] = [{
                value: [new Date(e.ts), e.functionIdentifier]
              }]
            }
          })
          let series = Object.keys(chartData).map(e => {
            return {
              name: (this.propArr.find(item => item.id === parseFloat(e)) || {}).name,
              type: 'line',
              stack: 'Total',
              data: chartData[e]
            }
          })
          this.$refs.chart.setData({
            tooltip: {
              trigger: 'axis'
            },
            legend: {},
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'time',
              boundaryGap: false,
            },
            yAxis: {
              type: 'value'
            },
            series: series
          })
        } else {
          return false;
        }
      });
    },
    async exportF() {
      let query = JSON.parse(JSON.stringify(this.form))
      query.startTime = this.parseTime(this.form.time?.[0]?.getTime())
      query.endTime = this.parseTime(this.form.time?.[1]?.getTime())
      delete query.time
      const data = exportData(query, '历史数据')
    }
  },
};
</script>
<style lang="less" scoped>
.title1 {
  position: absolute;
  top: 12%;
  left: 73%;
  font-size: 1vw;
  color: #00f8ff;
  transform: translateX(-50%);
}

.container {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  width: 100%;
  height: calc(100vh);
  position: relative;
}

.title {
  position: absolute;
  top: 12.9%;
  left: 6%;
  font-size: 0.9vw;
  color: #d9dee3;
}

.tree {
  position: absolute;
  top: 18.9%;
  left: 2%;
  width: 13%;
  height: 78%;

  /deep/ .el-tree {
    background-color: #0000;
    color: #d9dee3;
  }

  /deep/ .el-tree-node__content:hover {
    background-color: #0d5e93;
  }

  /deep/ .el-tree-node__content {
    height: 40px;
    border-bottom: 1px solid #fff2;
  }

  /deep/ .is-current {
    background-color: #0d5e93;
  }

  /deep/ .custom-tree-node {
    padding-left: 8px;
  }
}

.equipmentInfo {
  position: absolute;
  top: 11.6%;
  left: 17.2%;
  width: 16%;
  height: 20%;
  color: #1684c2;
  padding: 2vh 0 0 1vw;

  p {
    margin: 0;
    line-height: 4vh;
    font-size: 0.9vw;
  }
}

.equipmentInfo1 {
  position: absolute;
  top: 52.6%;
  left: 17.2%;
  width: 28.4%;
  height: 44%;
  color: #1684c2;
  padding: 2vh 0 0 1vw;
  display: flex;
  flex-direction: column;
  justify-content: space-around;

  p {
    width: 100%;
    margin: 0;
    flex: 1;
    font-size: 0.9vw;
  }
}

.img {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: absolute;
  top: 11.5%;
  left: 33.7%;
  width: 12%;
  height: 20.4%;
}

.img1 {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: absolute;
  top: 11.5%;
  left: 16.9%;
  width: 28.8%;
  height: 40.4%;
}

.terminal {
  position: absolute;
  top: 35.6%;
  left: 17.2%;
  width: 28%;
  height: 61%;
  padding-top: 14px;

  /deep/ .el-form-item__label {
    color: #25bffc !important;
    font-weight: normal;
  }

  /deep/ .el-input__inner {
    background-color: #0000;
    border-color: #25bffc;
  }

  .terminalList::-webkit-scrollbar {
    width: 0;
  }

  .terminalList {
    position: absolute;
    top: 1%;
    left: 0%;
    width: 100%;
    height: 95%;
    overflow: auto;

    ::-webkit-scrollbar {
      width: 0;
    }

    .item {
      background-image: url("~@/assets/board/equipment/item.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      position: relative;
      width: 50%;
      height: 3.5vw;
      margin-top: 12px;
      display: inline-block;

      .icon {
        background-image: url("~@/assets/board/equipment/icon.png");
        background-repeat: no-repeat;
        background-size: 100% 100%;
        position: absolute;
        top: 21%;
        left: 5.8%;
        width: 14.5%;
        height: 57%;
      }

      .title {
        position: absolute;
        top: 50%;
        left: 30%;
        transform: translateY(-50%);
        font-size: 0.6vw;
        color: #1facf4;
      }

      .switch {
        position: absolute;
        top: 50%;
        right: 5%;
        transform: translateY(-50%);
      }
    }
  }
}

.right::-webkit-scrollbar {
  width: 0;
}

.right {
  position: absolute;
  top: 16%;
  left: 48%;
  width: 50%;
  height: 80%;
  overflow: auto;
  padding-top: 0.5vw;

  .item {
    position: relative;
    width: 50%;
    margin-bottom: 12px;
    height: 11vh;
    padding: 0.5vh 0;
    display: inline-block;

    .iconBg {
      background-image: url("~@/assets/board/equipment/iconBg.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      position: absolute;
      top: 16%;
      left: 5%;
      width: 8vh;
      height: 8vh;
    }

    .icon {

      background-repeat: no-repeat;
      background-size: 100% 100%;
      position: absolute;
      top: calc(16% + 0.5vh);
      left: calc(5% + 0.25vw);
      width: 7vh;
      height: 7vh;
    }

    .rightBg {
      background-image: url("~@/assets/board/equipment/right.png");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      position: absolute;
      top: 16%;
      left: 1vw;
      width: calc(100% - 1vw);
      height: 10vh;

      .index {
        position: absolute;
        top: 0;
        left: 0;
        transform: translate(-50%, -50%);
        color: #fff;
        font-size: 0.6vw;
        width: 1.5vw;
        height: 1.5vw;
        border-radius: 50%;
        background-color: #1ca0e5;
        line-height: 1.5vw;
        text-align: center;
      }

      .title {
        position: absolute;
        top: 50%;
        left: 12.5%;
        color: #1facf4;
        transform: translate(-50%, -50%);
        font-size: 0.6vw;
      }

      .infoItem {
        white-space: nowrap;
        display: inline-block;
        position: relative;
        //width: 3vw;
        width: 50%;
        height: 33%;

        .spanBg {
          //background-image: url("~@/assets/board/equipment/icon.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
          position: absolute;
          bottom: 55%;
          left: 12%;
          width: 2vw;
          height: 0.8vw;

        }

        .span {
          //position: absolute;
          bottom: 55%;
          left: 12%;
          color: #f4f4f4;
          font-size: 0.7vw;
          display: inline-block;
          line-height: calc(11vh / 3);
        }

        .num {
          //position: absolute;
          display: inline-block;
          line-height: calc(11vh / 3);
          top: 55%;
          left: 12%;
          color: #f4f4f4;
          font-size: 0.7vw;
        }
      }

      .btn {
        position: absolute;
        top: 0%;
        right: 5%;
        width: 6vw;
        height: 100%;
      }

      .btnC {
        position: absolute;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}

.chart {
  width: 100%;
  height: 50vh;
}

.historyChart {
  width: 100%;
  height: 50vh;
}
</style>
