<template>
  <div class="app-container container-flex">
    <el-card flex>
      <el-descriptions title="井场数据" :column="column">
        <el-descriptions-item v-if="pictureUrl" label="井场照片" :span="3">
          <el-image
            style="width: 200px; height: 200px"
            :src="pictureUrl"
            fit="contain"
            :preview-src-list="[pictureUrl]"
          ></el-image>
        </el-descriptions-item>
        <!-- <el-descriptions-item label="井场名称">{{ form.name }}</el-descriptions-item> -->
        <el-descriptions-item label="所属集气站">{{ form.departmentStr }}</el-descriptions-item>
        <!-- <el-descriptions-item label="安装位置">{{ form.mountingPosition }}</el-descriptions-item> -->
        <el-descriptions-item
          v-for="item in form.typeExtensionData"
          :label="item.name"
          :key="item.id"
          >{{ typeExtensionDataValue(item) }}
        </el-descriptions-item>
        <el-descriptions-item
          v-for="item in form.extraWindowData"
          :label="item.name"
          :key="item.id"
          >{{ extraWindowDataValue(item) }}</el-descriptions-item
        >
        <!-- <el-descriptions-item v-if="pictureUrl" label="井场照片" :span="3">
          <el-image
            style="width: 20px; height: 20px"
            :src="pictureUrl"
            fit="contain"
            :preview-src-list="[pictureUrl]"
          ></el-image>
        </el-descriptions-item> -->
      </el-descriptions>
      <el-card>
        <el-table :data="childrenTreeData" style="width: 100%">
          <el-table-column label="名称" prop="name" align="center"></el-table-column>
          <el-table-column label="油压   (Mpa)" width="65px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[1]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="套压   (Mpa)" width="65px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[2]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="外输压力(Mpa)" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[3]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="外输温度(℃)" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[4]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="瞬时流量(气)" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[5]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="累计流量(气)" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[6]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="瞬时流量(液)" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[7]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="累计流量(液)" width="80px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[8]) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据时间" width="100px" align="center">
            <template slot-scope="scope">
              <span>{{ extraWindowDataValue(scope.row.extraWindowData[0]) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import Vue from 'vue'
import { initData } from '@/api/data'
import * as mqtt from 'mqtt'
import Dayjs from 'dayjs'
import DownloadAttachment from '@/components/DownloadAttachment'
import { getMQTTCilentId } from '@/utils/mqtt'
import { getElementItemLabel, getElementTreeLabel } from '@/utils'
import { getModuleOptions } from '@/api/options'

export default {
  name: 'WellTimeDataView',
  components: { DownloadAttachment },
  computed: {},
  watch: {},
  data() {
    return {
      column: 3,
      form: {
        id: '',
        code: '',
        name: '',
        typeId: '',
        typeStr: '',
        parentId: '',
        parentCode: '',
        model: '',
        departmentId: '',
        departmentStr: '',
        areaId: '',
        areaStr: '',
        mountingPosition: '',
        status: '',
        statusStr: '',
        remark: '',
        photoPath: '',
        attachment: [],
        typeExtensionData: [],
        calibration: {
          calibrationPeriod: '',
          calibrationLastTime: '',
          calibrationLastManufacturer: '',
        },
        type: {
          calibrationEnable: false,
          extensionConfig: [],
        },
        children: [],
        extraWindowData: [],
      },
      mqttClient: null,
      topicArray: [],
      currData: {},
      childTreData: [],
    }
  },
  computed: {
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    VUE_APP_BASE_WS() {
      return 'ws://' + window.location.host + process.env.VUE_APP_BASE_API
    },
    pictureUrl() {
      return this.form.photoPath ? process.env.VUE_APP_BASE_API + this.form.photoPath : ''
    },
  },
  created() {
    this.initData()
  },
  beforeDestroy() {
    this.mqttClient.end()
  },
  methods: {
    initData() {
      if (this.$route.query.column) this.column = this.$route.query.column
      initData('equipment/ledger/getEntity', { id: this.$route.query.id }).then((resp) => {
        this.form = resp.data
        if (this.form && this.form.typeExtensionData) {
          this.form.typeExtensionData.forEach((a) => {
            if ((a.componentType == 3 || a.componentType == 4) && a.componentConfig && !a.isTag) {
              let config = JSON.parse(a.componentConfig)
              let module = config.options && config.options.module ? config.options.module : ''
              let type = config.options && config.options.type ? config.options.type : ''
              let data = config.options && config.options.data ? config.options.data : {}
              if (module || type) {
                getModuleOptions(module, type, data).then((resp2) => {
                  if (resp2.code === 20000) {
                    if (a.componentType == 3 && resp2.data.content) {
                      const label = getElementItemLabel(resp2.data.content, a.value)
                      console.log(label)
                      if (label) a.value = label
                    } else if (a.componentType == 4 && resp2.data.content) {
                      const label = getElementTreeLabel(resp2.data.content, a.value)
                      if (label) a.value = label
                    }
                  }
                })
              }
            }
          })
        }
        this.startMQTT()
      })
      initData('equipment/ledger/getTree', { id: this.$route.query.id }).then((resp) => {
        this.childrenTreeData = resp.data.content
        // console.log(this.childrenTreeData)
        this.startMQTT()
      })
    },
    //开始MQTT接收
    startMQTT() {
      if (this.mqttClient) this.mqttClient.end()
      // 连接选项
      const options = {
        clean: true, // true: 清除会话, false: 保留会话
        keepalive: 60,
        connectTimeout: 4000, // 超时时间
        // 认证信息
        clientId: getMQTTCilentId('equipmentledgerview'),
        username: 'client',
        password: '19c9547ad2029be96774fce5f1b9f099',
      }
      const connectUrl = this.VUE_APP_BASE_WS + '/MQTTOverWebSocket'
      //console.log(connectUrl)
      this.mqttClient = mqtt.connect(connectUrl, options)

      this.topicArray = []
      if (this.form.typeExtensionData)
        this.topicArray.push.apply(
          this.topicArray,
          this.form.typeExtensionData
            .filter((e) => e.isTag)
            .map((e) => 'DataCommunication/TagData/' + e.value)
        )
      if (this.form.extraWindowData)
        this.topicArray.push.apply(
          this.topicArray,
          this.form.extraWindowData
            .filter((e) => e.isTag)
            .map((e) => 'DataCommunication/TagData/' + e.value)
        )
      if (this.childrenTreeData)
        this.childrenTreeData.forEach((a) => {
          this.topicArray.push.apply(
            this.topicArray,
            a.extraWindowData
              .filter((e) => e.isTag)
              .map((e) => 'DataCommunication/TagData/' + e.value)
          )
        })

      let _this = this
      this.mqttClient.on('connect', function () {
        //订阅主题
        console.log('实时数据MQTT正在连接')
        if (_this.topicArray.length > 0) {
          _this.mqttClient.subscribe(_this.topicArray)
          //console.log('订阅1', _this.topicArray)
        }
      })
      this.mqttClient.on('message', (topic, message) => {
        if (topic == 'Online') {
          console.log('实时数据MQTT收到消息：', topic, message.toString())
        } else if (topic.startsWith('DataCommunication/TagData/')) {
          let data = JSON.parse(message.toString())
          //console.log(JSON.parse(message.toString()))
          Vue.set(this.currData, data.Tag, data)
        }
      })
    },
    typeExtensionDataValue(config) {
      if (config.isTag) {
        if (this.currData[config.value]) {
          if (this.currData[config.value].Type == 1) {
            return this.currData[config.value].Value == 'True' ? '开' : '关'
          } else {
            return (
              this.currData[config.value].Value +
              (this.currData[config.value].Unit ? this.currData[config.value].Unit : '')
            )
          }
        } else return ''
      } else {
        switch (config.componentType) {
          case 1:
          case 2:
            return config.value ? config.value + (config.unit ? config.unit : '') : ''
          case 5:
            return config.value ? (config.value == 'true' ? '是' : '否') : ''
          case 3:
          case 4:
          case 6:
          case 7:
          case 8:
          case 9:
            return config.value ? config.value : ''
          case 10:
          default:
            return ''
        }
      }
    },
    extraWindowDataValue(config) {
      if (config.isTag) {
        if (this.currData[config.value]) {
          if (this.currData[config.value].Type == 1) {
            return this.currData[config.value].Value == 'True' ? '开' : '关'
          } else {
            if (this.currData[config.value].Value == '-9999') {
              return '--'
            } else {
              return (
                this.currData[config.value].Value +
                (this.currData[config.value].Unit ? this.currData[config.value].Unit : '')
              )
            }
          }
        } else return ''
      } else return config.value ? config.value + (config.unit ? config.unit : '') : ''
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.container-flex {
  display: flex;
}
</style>
