<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-row :gutter="20">
      <el-col :span="16">
        <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"
            :step="property.propertyType === 4"
            :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-col>
      <el-col :span="8">
        <el-card class="margin-top-20">
          <div slot="header">
            <span>FFT</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col
        v-for="(chart, index) in functionList"
        :key="index"
        :span="8"
      >
        <el-card class="margin-top-20">
          <f-line
            :id="'func-' + index"
            :line-data="chart.data"
          />
        </el-card>
      </el-col>
    </el-row>
  </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 FLine from '@/components/Charts/FLine'
import moment from 'moment'

export default {
  name: 'FrequencyAnalysis',
  components: {
    ELine,
    FLine
  },
  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,
        propertyType: 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' }
        ]
      },
      functionList: []
    }
  },
  watch: {
    activeProperty(newVal) {
      if (newVal) {
        const property = this.propertyList.find(v => v.propertyCode === newVal)
        if (property) {
          const { propertyCode, propertyName, propertyType, propertyUnit } = property
          this.property = {
            propertyCode,
            propertyName,
            propertyUnit,
            propertyType,
            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.getFunctionChartList()
      // 查询图表数据
      await this.queryData()
      return {}
    },
    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(_ => {})
    },
    getFunctionChartList() {
      this.functionList.push({
        name: 'func1',
        data: this.generateData()
      })
    },
    generateData() {
      const data = []
      for (let i = 0; i < 50; i += 0.1) {
        data.push([i, this.func(i)])
      }
      return data
    },
    func(x) {
      return Math.sin(x)
    }
  }
}
</script>

<style scoped>

</style>
