<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="eModel" style="width: 100%">
              <el-option
                v-for="item in eModelList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="custom-menu">
            <el-menu
              ref="customMenu"
              default-active="1"
            >
              <el-menu-item
                v-for="(model, index) in eInstanceList"
                :key="'model' + index"
                :index="model.id.toString()"
              >{{ model.name }}</el-menu-item>
            </el-menu>
          </div>
        </div>
      </el-col>
      <el-col :xs="16" :sm="16" :md="18" :lg="20">
        <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>
      </el-col>
    </el-row>
  </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: [],
      eModel: 1,
      eModelList: [
        {
          value: 1,
          label: '设备模型一'
        },
        {
          value: 2,
          label: '设备模型二'
        }
      ],
      eInstanceList: [
        {
          id: 1,
          name: '设备实例一'
        },
        {
          id: 2,
          name: '设备实例二'
        },
        {
          id: 3,
          name: '设备实例三'
        },
        {
          id: 4,
          name: '设备实例四'
        }
      ],
      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].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 - 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;
    }
  }
}
</style>
