<template>
  <el-card class="container">
    <el-tabs
      v-model="activeModel"
      tab-position="left"
      @tab-click="onTabClick"
    >
      <el-tab-pane
        v-for="(model, index) in modelList"
        :key="index"
        :label="model.name"
        :name="model.id.toString()"
      >
        <div v-if="activeModel === model.id.toString()">
          <el-form
            :ref="'form'+activeModel"
            :model="chartField"
            inline
            label-width="100px"
            style="margin-top: 20px"
            :rules="rules"
          >
            <div>
              <el-form-item label="选择实例：" prop="instanceId">
                <el-radio-group v-model="chartField.instanceId">
                  <el-radio
                    v-for="(ins, index) in instanceList"
                    :key="300 + index"
                    :label="ins.id"
                  >{{ ins.instanceName }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="Y轴:" prop="yFields">
                <el-checkbox-group v-model="chartField.yFields">
                  <el-checkbox
                    v-for="(prop, i) in propertyList"
                    :key="200+i"
                    :label="prop.propertyCode"
                  >{{ prop.propertyName }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="时间轴:">
                Timestamp
              </el-form-item>
              <el-form-item
                label="刷新时间(秒):"
              >
                <el-input-number
                  v-model.number="chartField.refresh"
                  :min="1"
                  :max="10"
                  label="单位秒"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="createCharts"
                >生成图表</el-button>
              </el-form-item>
            </div>
          </el-form>
          <el-row :gutter="20">
            <el-col
              v-for="(chart) in chartList"
              :key="chart.id"
              :span="12"
              style="height: 400px"
            >
              <e-line
                :id="'line-' + chart.propertyCode"
                :title="chart.propertyName"
                :line-data="setChartData(chart.propertyCode)"
                :description="chart.propertyUnit"
              ></e-line>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import ELine from '@/components/Charts/ELine'
import { getAllModel, getModelDetail, getModelInstanceList, getModelInstanceChart } from '@/api/data-visible/dashboard'

export default {
  name: 'Dashboard',
  components: {
    ELine
  },
  data() {
    return {
      chartField: {
        instanceId: null,
        yFields: [],
        refresh: 1
      },
      activeModel: null,
      modelList: [],
      objectId: '1',
      timer: 0,
      count: 0,
      instanceList: [],
      propertyList: [],
      chartData: [],
      chartList: [],
      rules: {
        instanceId: [
          { required: true, message: '请选择实例', trigger: 'change' }
        ],
        yFields: [
          { type: 'array', required: true, message: '请至少选择一个属性', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    getAllModel()
      .then(res => {
        this.modelList = res.data
        if (this.modelList.length > 0) {
          this.activeModel = this.modelList[0].id.toString()
          this.getDetail(parseInt(this.activeModel))
        }
      })
      .catch(err => console.error(err))
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    onTabClick() {
      this.chartField = {
        instanceId: null,
        yFields: [],
        refresh: 1
      }
      this.getDetail(parseInt(this.activeModel))
      this.chartList = []
      clearInterval(this.timer)
    },
    getDetail(id) {
      Promise.all([getModelInstanceList({ id }), getModelDetail({ id })])
        .then(res => {
          const [res1, res2] = res
          this.instanceList = res1.data
          this.propertyList = res2.data.propertyList
        })
        .catch(err => console.error(err))
    },
    random(m, n) {
      return Math.round(Math.random() * (m - n) + n)
    },
    setChartData(yField) {
      return this.chartData.map(v => {
        return {
          time: v.time,
          value: parseInt(v[yField])
        }
      })
    },
    createCharts() {
      const form = `form${this.activeModel}`
      this.$refs[form][0].validate()
        .then(_ => {
          this.chartData = []
          this.chartList = []
          const params = {
            modelId: parseInt(this.activeModel),
            instanceId: this.chartField.instanceId,
            propertyCodeList: [...this.chartField.yFields]
          }
          getModelInstanceChart(params)
            .then(res => {
              this.chartData = res.data.sort((a, b) => {
                return (a > b) ? 1 : -1
              })
              const arr = []
              this.propertyList.forEach(v => {
                const index = this.chartField.yFields.findIndex(item => item === v.propertyCode)
                index !== -1 && arr.push({ ...v })
              })
              this.chartList = [...arr]
            })
            .then(_ => {
              this.timer && clearInterval(this.timer)
              this.timer = setInterval(async() => {
                const chartData = await getModelInstanceChart(params)
                this.chartData = chartData.data.sort((a, b) => {
                  return (a > b) ? 1 : -1
                })
                this.count++
              }, this.chartField.refresh * 1000)
            })
            .catch(_ => {})
        })
        .catch(err => console.error(err))
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  min-height: calc(100vh - 90px);
}
</style>
