<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="时间范围:" prop="startAndEndTime">
          <el-date-picker
            v-model="form.startAndEndTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryData">查询</el-button>
        </el-form-item>
      </el-form>
    </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"
        :config="lineConfig"
        format="MM-DD HH:mm:ss"
      />
      <div v-else class="el-table__empty-text" style="text-align: center;margin: 0 auto">暂无数据</div>
    </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" @click="handleDownload">导出</el-button>
      </div>
      <el-table :data="tableDataPaged" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column
          v-for="(property, index) in propertyList"
          :key="index"
          :label="property.propertyName"
          :prop="property.propertyCode"
        />
        <el-table-column
          label="上报时间"
          prop="time"
          :formatter="$moment"
          min-width="155"
        />
      </el-table>
      <el-pagination
        class="margin-top-20 text-align-right"
        :current-page="pageForm.pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="pageForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </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 { getModelHistory } from '@/api/device-management/history-data'
import ELine from '@/components/Charts/ELine'
import moment from 'moment'

export default {
  name: 'HistoryData',
  components: {
    ELine
  },
  data() {
    return {
      form: {
        deviceType: null,
        deviceInstance: null,
        dataMode: null,
        startAndEndTime: []
      },
      activeProperty: null,
      tableData: [],
      pageForm: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      deviceTypeList: [],
      deviceInstanceList: [],
      dataModelList: [],
      propertyList: [],
      lineConfig: {
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 65,
            end: 85
          },
          {
            type: 'inside',
            realtime: true,
            start: 65,
            end: 85
          }
        ]
      },
      property: {
        propertyCode: null,
        propertyName: null,
        propertyUnit: null,
        data: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近半小时',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1800 * 1000)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一小时',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }],
        disabledDate(time) {
          return time.getTime() > new Date(moment().endOf('day').valueOf())
        }
      },
      tableDataPaged: [],
      rules: {
        deviceType: [
          { required: true, message: '', trigger: 'blur' }
        ],
        deviceInstance: [
          { required: true, message: '', trigger: 'blur' }
        ],
        dataMode: [
          { required: true, message: '', trigger: 'blur' }
        ],
        startAndEndTime: [
          { type: 'array', required: true, message: '', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    activeProperty(newVal) {
      if (newVal) {
        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)]
          }
        }
      }
    },
    form: {
      deep: true,
      handler: function() {
        this.$refs.form.clearValidate()
      }
    }
  },
  created() {
    const { deviceTypeId, deviceInstanceId } = this.$route.query
    const now = new Date().getTime()
    const beginTime = new Date(now - 1000 * 3600 * 24 * 7)
    const endTime = new Date(now)
    this.form.startAndEndTime = [beginTime, endTime]
    this.init(deviceTypeId, deviceInstanceId)
  },
  methods: {
    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)
      // 根据设备类型 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 {}
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'time') {
          return this.$moment(v[j], 'YYYY-MM-DD HH:mm:ss')
        } else {
          return v[j]
        }
      }))
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = []
        const filterVal = []
        for (const key in this.tableDataPaged[0]) {
          tHeader.push(key)
          filterVal.push(key)
        }
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    getChartData(propertyCode) {
      return this.tableData.map(v => {
        return {
          time: v.time,
          value: v[propertyCode]
        }
      })
    },
    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
          }
        })
        .then(_ => {
          return {
            beginTime: this.form.startAndEndTime[0].getTime(),
            endTime: this.form.startAndEndTime[1].getTime(),
            dashboardReqList: [
              {
                modelId: this.form.dataMode,
                deviceId: this.form.deviceInstance,
                propertyCodeList: this.propertyList.map(v => v.propertyCode)
              }
            ]
          }
        })
        .then(params => getModelHistory(params))
        .then(res => {
          this.tableData = res.data[0].dataList
          this.pageForm.total = this.tableData.length
          this.pageTableData()
          this.property.data = [...this.getChartData(this.activeProperty)]
        })
        .catch(_ => {})
    },
    onDeviceTypeChange(val) {
      this.form.deviceInstance = null
      this.form.dataMode = null
      this.getAllInstanceByDeviceTypeId(val)
      this.getDataModelByDeviceTypeId(val)
    },
    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(_ => {})
    },
    pageTableData() {
      const { pageNum, pageSize } = this.pageForm
      const x = pageSize.toString().substring(0, 1)
      let start = pageNum - 1
      start = (start === 0) ? start * parseInt(x) : parseInt(`${start}0`) * parseInt(x)
      let end = pageSize - 1
      end = start + end
      this.tableDataPaged = this.tableData.slice(start, end)
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val
      this.pageTableData()
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val
      this.pageTableData()
    }
  }
}
</script>

<style scoped>

</style>
