<template>
  <el-card class="container">
    <el-row :gutter="20" class="content">
      <el-col :xs="8" :sm="8" :md="6" :lg="4">
        <div class="left">
          <div class="search">
            <el-select
              v-model="deviceType"
              style="width: 100%"
              @change="onDeviceTypeChange"
            >
              <el-option
                v-for="item in deviceTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="custom-menu">
            <el-menu
              ref="customMenu"
              @select="onInstanceSelect"
            >
              <el-menu-item
                v-for="(instance, index) in deviceInstanceList"
                :id="'instance' + instance.id"
                :key="'instance' + index"
                :index="instance.id.toString()"
              >{{ instance.name }}</el-menu-item>
            </el-menu>
          </div>
        </div>
      </el-col>
      <el-col :xs="16" :sm="16" :md="18" :lg="20">
        <el-form
          ref="form"
          :model="chartField"
          inline
          label-position="top"
          label-width="100px"
          style="margin-top: 20px"
        >
          <el-form-item
            label="属性:"
            prop="yFields"
          >
            <div class="data-model-container">
              <div
                v-for="(dataModel, index) in dataModelList"
                :key="index + 400"
                class="data-model-item"
              >
                <div class="data-model-name">
                  {{ dataModel.name }}:
                </div>
                <el-checkbox-group v-model="chartField.yFields[index]">
                  <el-checkbox
                    v-for="(prop, i) in dataModel.propertyList"
                    :key="200+i"
                    :label="prop.propertyCode"
                  >{{ prop.propertyName }}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </el-form-item>
          <el-form-item
            label="查询范围:"
            prop="startAndEndTime"
            :rules="[{ type: 'array', required: true, message: '请选择时间范围', trigger: 'blur' }]"
          >
            <el-date-picker
              v-model="chartField.startAndEndTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="createCharts"
            >查看图表</el-button>
          </el-form-item>
        </el-form>
        <el-row
          v-for="(chartGroup, index) in chartList"
          :key="index + 1000"
          :gutter="20"
        >
          <el-col
            v-for="(chart) in chartGroup"
            :key="chart.id"
            :span="12"
            style="height: 400px"
          >
            <e-line
              :id="'line-' + chart.propertyCode"
              :title="chart.propertyName"
              :line-data="setChartData(chart.propertyCode, index)"
              :description="chart.propertyUnit"
              :config="lineConfig"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import ELine from '@/components/Charts/ELine'
import { getAllInstanceByDeviceTypeId } from '@/api/data-visible/dashboard'
import { getAllDeviceModel } from '@/api/equipment-management/equipment-instance'
import { getDataModelByDeviceTypeId } from '@/api/equipment-management/equipment-model'
import { getModelHistory } from '@/api/data-visible/query-history'

export default {
  name: 'QueryHistory',
  components: {
    ELine
  },
  data() {
    return {
      chartField: {
        yFields: [],
        refresh: 1,
        startAndEndTime: []
      },
      dataModelList: [],
      deviceInstance: null,
      modelList: [],
      objectId: '1',
      defaultActive: null,
      timer: 0,
      count: 0,
      instanceList: [],
      propertyList: [],
      deviceType: null,
      deviceTypeList: [],
      deviceInstanceList: [],
      chartData: [],
      chartList: [],
      rules: {
        instanceId: [
          { required: true, message: '请选择实例', trigger: 'change' }
        ],
        yFields: [
          { type: 'array', required: true, message: '请至少选择一个属性', trigger: 'change' }
        ]
      },
      lineConfig: {
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 65,
            end: 85
          },
          {
            type: 'inside',
            realtime: true,
            start: 65,
            end: 85
          }
        ]
      }
    }
  },
  created() {
    // 初始化设备类型
    getAllDeviceModel()
      .then(res => {
        this.deviceTypeList = res.data.map(v => {
          return {
            value: v.id,
            label: v.name
          }
        })
        if (this.deviceTypeList.length) {
          this.deviceType = this.deviceTypeList[0].value
          // 获取该设备类型下的设备实例
          this.getAllInstanceByDeviceTypeId(this.deviceType)
          // 根据设备类型 ID 获取关联数据模型
          this.getDataModelByDeviceTypeId(this.deviceType)
        }
      })
      .catch(_ => {})
  },
  methods: {
    onDeviceTypeChange(val) {
      this.dataModelList = []
      this.chartField = {
        yFields: [],
        refresh: 1
      }
      this.chartList = []
      this.chartData = []
      clearInterval(this.timer)
      this.getDataModelByDeviceTypeId(val)
      this.getAllInstanceByDeviceTypeId(val)
    },
    onInstanceSelect(index) {
      const id = parseInt(index)
      const instance = this.deviceInstanceList.find(v => v.id === id)
      if (instance.id !== this.deviceInstance) {
        this.deviceInstance = instance.id
        this.chartField.refresh = 1
        const length = this.chartField.yFields.length
        this.chartField.yFields = [...new Array(length).fill([])]
        this.chartList = []
        this.chartData = []
        clearInterval(this.timer)
      }
    },
    getDataModelByDeviceTypeId(id) {
      getDataModelByDeviceTypeId({ id })
        .then(res => {
          this.dataModelList = []
          this.chartField.yFields = []
          this.dataModelList = res.data
          this.dataModelList.forEach(v => {
            this.chartField.yFields.push([])
          })
        })
        .catch(_ => {})
    },
    getAllInstanceByDeviceTypeId(val) {
      getAllInstanceByDeviceTypeId({ deviceTypeId: val })
        .then(res => {
          this.deviceInstanceList = res.data
        })
        .then(_ => {
          if (this.deviceInstanceList.length) {
            this.deviceInstance = this.deviceInstanceList[0].id
            this.$nextTick()
              .then(_ => {
                document.getElementById(`instance${this.deviceInstanceList[0].id}`).click()
              })
              .catch(_ => {})
          }
        })
        .catch(_ => {})
    },
    setChartData(yField, index) {
      return this.chartData[index].map(v => {
        return {
          time: v.time,
          value: parseInt(v[yField])
        }
      })
    },
    createCharts() {
      // eslint-disable-next-line no-unused-vars
      let count = 0
      this.chartField.yFields.forEach(v => {
        if (v.length) {
          count += v.length
        }
      })
      if (count > 0) {
        this.$refs.form.validate()
          .then(_ => {
            this.chartData = []
            this.chartList = []
            const dashboardReqList = this.dataModelList.map((v, i) => {
              return {
                modelId: v.id,
                deviceId: this.deviceInstance,
                propertyCodeList: [...this.chartField.yFields[i]]
              }
            })
            return {
              beginTime: this.chartField.startAndEndTime[0].getTime(),
              endTime: this.chartField.startAndEndTime[1].getTime(),
              dashboardReqList
            }
          })
          .then(params => getModelHistory(params))
          .then(res => {
            this.dataModelList.forEach((dataModel, i) => {
              const arr = []
              dataModel.propertyList.forEach(v => {
                const index = this.chartField.yFields[i].findIndex(item => item === v.propertyCode)
                index !== -1 && arr.push({ ...v })
              })
              this.chartList.push(arr)
            })
            this.chartData = res.data.map(v => {
              return [...v.dataList]
            })
          })
          .then(_ => this.$nextTick())
          .then(_ => {
            this.chartData = [...this.chartData]
          })
          .catch(_ => {})
      } else {
        this.$message.warning('请至少选择 1 个属性')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  min-height: calc(100vh - 95px);
  .content{
    display: flex;
    min-height: calc(100vh - 135px);
    .left{
      width: 100%;
      height: 100%;
      .search{
        height: 40px;
      }
      .custom-menu{
        background-color: #efeff1;
        height: calc(100% - 40px);
        .el-menu{
          background-color: initial;
          border-right: none;
          border-top: solid 1px #e6e6e6;
          border-left: solid 1px #e6e6e6;
          .el-menu-item.el-menu-item{
            min-width: initial;
            background-color: #efeff1;
          }
          .el-menu-item.is-active{
            background-color: #fff;
            color: #303133;
          }
        }
      }
    }
    .top{
      display: flex;
      justify-content: space-between;
    }
    .data-model-container{
      display: flex;
      .data-model-item{
        display: flex;
        .data-model-name{
          margin-right: 20px;
          margin-left: 20px;
        }
      }
      .data-model-item:first-of-type{
        .data-model-name{
          margin-left: 0;
        }
      }
      .data-model-item:last-of-type{
        margin-right: 20px;
      }
    }
  }
}
</style>
