<template>
  <div>
    <el-card class="no-bottom">
      <el-form ref="form" :model="form" inline :rules="rules">
        <el-form-item label="设备类型:" prop="deviceType">
          <el-select v-model="form.deviceType" @change="onDeviceTypeChange">
            <el-option
              v-for="(deviceType, index) in deviceTypeList"
              :key="index"
              :label="deviceType.name"
              :value="deviceType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备实例:" prop="deviceInstance">
          <el-select v-model="form.deviceInstance" placeholder="请选择">
            <el-option
              v-for="(deviceInstance, index) in deviceInstanceList"
              :key="index"
              :label="deviceInstance.name"
              :value="deviceInstance.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据模型:" prop="dataMode">
          <el-select v-model="form.dataMode" placeholder="请选择">
            <el-option
              v-for="(dataMode, index) in dataModelList"
              :key="index"
              :label="dataMode.name"
              :value="dataMode.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间轴:">
          <div style="margin-right: 20px">
            Timestamp
          </div>
        </el-form-item>
        <el-form-item label="刷新时间">
          <el-input-number
            v-model.number="form.refresh"
            :min="1"
            :max="10"
            label="单位秒"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryData">查询</el-button>
          <el-button v-if="false" @click="clearIntervalT">clear</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="margin-top-20">
      <div slot="header" class="clearfix">
        <span>设备信息</span>
      </div>
      <descriptions
        label-position="right"
        label-width="140px"
      >
        <descriptions-item label="设备名称" :value="deviceInstance.name" />
        <descriptions-item label="运行状态" :value="$_dictionaryFormat(deviceInstance.onlineState, 'onlineState')" />
        <descriptions-item label="设备型号" :value="deviceInstance.deviceModel" />
        <descriptions-item label="业务ID" :value="deviceInstance.businessId" />
        <descriptions-item label="描述" :value="deviceInstance.description" />
      </descriptions>
    </el-card>
    <el-card class="margin-top-20">
      <div slot="header" class="clearfix">
        <span>模型数据</span>
        <el-button style="float: right; padding: 3px 0" type="text">{{ $moment(dataModelReportTime, 'YYYY-MM-DD HH:mm:ss') }}</el-button>
      </div>
      <descriptions-item
        v-for="(property, index) in dataModelDetail"
        :key="index"
        :label="property.propertyName"
        :value="formatProperty(property)"
      />
    </el-card>
    <el-card class="margin-top-20">
      <div v-if="!propertyList.length" slot="header" class="clearfix">
        <span>图表</span>
      </div>
      <el-tabs v-model="activeProperty">
        <el-tab-pane
          v-for="(property, index) in propertyList"
          :key="index"
          :label="property.propertyName"
          :name="property.propertyCode"
        />
      </el-tabs>
      <e-line
        v-if="propertyList.length"
        :id="'line-' + property.propertyCode"
        :title="property.propertyName"
        :line-data="property.data"
        :description="property.propertyUnit"
        format="MM-DD HH:mm:ss"
      />
      <div v-else class="el-table__empty-text" style="text-align: center;margin: 0 auto">暂无数据</div>
    </el-card>
  </div>
</template>

<script>
import { getAllDeviceModel } from '@/api/equipment-management/equipment-instance'
import { getAllInstanceByDeviceTypeId } from '@/api/equipment-management/equipment-model'
import { getDataModelByDeviceTypeId } from '@/api/equipment-management/equipment-model'
import { getModelInstanceChart } from '@/api/device-management/device-monitoring'
import ELine from '@/components/Charts/ELine'
import { getDeviceInstanceDetail, getPropertyDetail } from '@/api/equipment-management/device-instance'
import dictionary from '@/utils/dictionary'

export default {
  name: 'DeviceMonitoring',
  components: {
    ELine
  },
  mixins: [
    dictionary
  ],
  data() {
    return {
      form: {
        deviceType: null,
        deviceInstance: null,
        dataMode: null,
        refresh: 1
      },
      property: {
        propertyCode: null,
        propertyName: null,
        propertyUnit: null,
        data: []
      },
      rules: {
        deviceType: [
          { required: true, message: '', trigger: 'blur' }
        ],
        deviceInstance: [
          { required: true, message: '', trigger: 'blur' }
        ],
        dataMode: [
          { required: true, message: '', trigger: 'blur' }
        ]
      },
      deviceInstanceList: [],
      dataModelList: [],
      propertyList: [],
      activeProperty: null,
      deviceTypeList: [],
      tableData: [],
      timer: 0,
      deviceInstance: {
        businessId: null,
        description: null,
        name: null,
        onlineState: null,
        deviceModel: null
      },
      dataModelDetail: [],
      dataModelReportTime: null
    }
  },
  watch: {
    activeProperty(newVal) {
      if (newVal !== null) {
        const property = this.propertyList.find(v => v.propertyCode === newVal)
        if (property) {
          const { propertyCode, propertyName, propertyUnit } = property
          this.property = {
            propertyCode,
            propertyName,
            propertyUnit,
            data: [...this.getChartData(this.activeProperty)]
          }
        }
      } else {
        this.propertyList = []
      }
    },
    form: {
      deep: true,
      handler: function() {
        this.$refs.form.clearValidate()
      }
    }
  },
  created() {
    const { deviceTypeId, deviceInstanceId } = this.$route.query
    this.timer && clearInterval(this.timer)
    this.init(deviceTypeId, deviceInstanceId)
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer)
  },
  methods: {
    clearIntervalT() {
      this.timer && clearInterval(this.timer)
    },
    async init(deviceTypeId, deviceInstanceId) {
      // 获取所有设备类型
      const deviceTypeList = await getAllDeviceModel()
      this.deviceTypeList = deviceTypeList.data
      this.form.deviceType = deviceTypeId || (this.deviceTypeList.length ? this.deviceTypeList[0].id : null)
      // 获取该设备类型下的设备实例
      const deviceInstanceList = await getAllInstanceByDeviceTypeId({ deviceTypeId: this.form.deviceType })
      this.deviceInstanceList = deviceInstanceList.data
      this.form.deviceInstance = deviceInstanceId || (this.deviceInstanceList.length ? this.deviceInstanceList[0].id : null)
      await this.getDeviceInstanceDetail(this.form.deviceType)
      // 根据设备类型 ID 获取关联数据模型
      const dataModelList = await getDataModelByDeviceTypeId({ id: this.form.deviceType })
      this.dataModelList = dataModelList.data
      if (this.dataModelList.length) {
        this.form.dataMode = this.dataModelList[0].id
        this.propertyList = this.dataModelList[0].propertyList
        this.activeProperty = this.propertyList.length ? this.propertyList[0].propertyCode : null
      }
      // // 查询图表数据
      await this.queryData()
      return {}
    },
    queryData() {
      this.$refs.form.validate()
        .then(_ => {
          const index = this.dataModelList.findIndex(i => i.id === this.form.dataMode)
          this.propertyList = [...this.dataModelList[index].propertyList]
          if (this.propertyList.length) {
            this.activeProperty = this.propertyList[0].propertyCode
          }
          this.getDeviceInstanceDetail(this.form.deviceInstance)
          return [{
            modelId: this.form.dataMode,
            deviceId: this.form.deviceInstance,
            propertyCodeList: this.propertyList.map(v => v.propertyCode)
          }]
        })
        .then(params => getModelInstanceChart(params))
        .then(res => {
          this.tableData = res.data[0].dataList
          this.property.data = [...this.getChartData(this.activeProperty)]
          return [{
            modelId: this.form.dataMode,
            deviceId: this.form.deviceInstance,
            propertyCodeList: this.propertyList.map(v => v.propertyCode)
          }]
        })
        .then(params => {
          const { dataMode, deviceInstance } = this.form
          this.timer && clearInterval(this.timer)
          this.timer = setInterval(async() => {
            await this.getPropertyDetail(dataMode, deviceInstance)
            const chartData = await getModelInstanceChart(params)
            this.tableData = chartData.data[0].dataList
            this.property.data = [...this.getChartData(this.activeProperty)]
          }, this.form.refresh * 1000)
        })
        .catch(e => console.error(e))
    },
    formatProperty(property) {
      return property.propertyValue ? `${property.propertyValue} ${property.propertyUnit}` : ''
    },
    getDeviceInstanceDetail(id) {
      getDeviceInstanceDetail({ id })
        .then(res => {
          const { businessId, description, name, onlineState, deviceModel } = res.data.deviceInstance
          this.deviceInstance = {
            businessId,
            description,
            name,
            onlineState,
            deviceModel
          }
        })
        .catch(_ => {})
    },
    getPropertyDetail(dataModelId, deviceId) {
      getPropertyDetail({ dataModelId, deviceId })
        .then(res => {
          this.dataModelDetail = res.data.propertyList.length ? res.data.propertyList : []
          this.dataModelReportTime = res.data.reportTime ? res.data.reportTime : null
        })
        .catch(_ => {})
    },
    onDeviceTypeChange(val) {
      this.form.deviceInstance = null
      this.form.dataMode = null
      this.getAllInstanceByDeviceTypeId(val)
      this.getDataModelByDeviceTypeId(val)
    },
    getChartData(propertyCode) {
      return this.tableData.map(v => {
        return {
          time: v.time,
          value: v[propertyCode]
        }
      })
    },
    getAllInstanceByDeviceTypeId(val) {
      getAllInstanceByDeviceTypeId({ deviceTypeId: val })
        .then(res => {
          this.deviceInstanceList = res.data
          if (this.deviceInstanceList.length) {
            this.form.deviceInstance = this.deviceInstanceList[0].id
          }
        })
        .catch(_ => {})
    },
    getDataModelByDeviceTypeId(id) {
      getDataModelByDeviceTypeId({ id })
        .then(res => {
          this.dataModelList = res.data
          if (this.dataModelList.length) {
            this.form.dataMode = this.dataModelList[0].id
          }
        })
        .catch(_ => {})
    }
  }
}
</script>

<style scoped>

</style>
