<template>
  <div>
    <el-card>
      <span class="show-text">工位:</span>
      <el-select
        v-model="OpName"
        clearable
        filterable
        placeholder="请选择工位号"
        size="small"
        style="width: 200px">
        <el-option
          v-for="item in OpNameList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          size="mini"/>
      </el-select>
      <span class="show-text">采集时间:</span>
      <!--      <el-date-picker-->
      <!--        v-model="collectionTime"-->
      <!--        :clearable="false"-->
      <!--        :picker-options="pickerOptions"-->
      <!--        popper-class="virtual-cell-time-picker"-->
      <!--        value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--        format="yyyy-MM-dd HH:mm:ss"-->
      <!--        type="datetimerange"-->
      <!--        range-separator="-"-->
      <!--        style="width: 360px;margin-right: 16px;vertical-align: top"-->
      <!--        start-placeholder="开始时间"-->
      <!--        end-placeholder="结束时间"/>-->
      <el-date-picker
        v-model="date"
        placeholder="选择日期"
        type="date"
        value-format="yyyy-MM-dd"/>
      <el-button icon="el-icon-search" type="primary" @click="searchTable();initEcharts()">查询</el-button>
      <div style="margin-top: 10px;display: flex">
        <div>
          <el-table
            v-loading="loading"
            :data="tableData"
            :header-row-style="{fontSize: '18px',fontFamily:'MiSans Demibold',height: '64px',backgroundColor:'#fff'}"
            :row-style="{fontSize: '16px',fontFamily:'MiSans Regular',height: '64px'}"
            border
            element-loading-background="rgba(0, 0, 0, 0.2)"
            element-loading-spinner="el-icon-loading"
            element-loading-text="数据加载中"
            height="707"
            size="mini"
            style="width: 1001px"
            tooltip-effect="dark">
            <el-table-column align="center" label=" " type="index" width="100"/>
            <el-table-column align="center" label="工位号" width="150">
              <template slot-scope="scope">
                {{ scope.row.工位号2 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="工位名称">
              <template slot-scope="scope">
                {{ scope.row.工位号 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="设备状态">
              <template slot-scope="scope">
                {{ deviceStatus_state[(scope.row.状态 + 1)] }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="开始时间" width="200">
              <template slot-scope="scope">
                {{ scope.row.开始时间 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="结束时间" width="200">
              <template slot-scope="scope">
                {{ scope.row.结束时间 }}
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top: 10px;">
            <el-pagination
              v-if="!loading"
              :current-page="pageList"
              :page-size="pageSize"
              :page-sizes="[50, 100, 200, 300]"
              :total="total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </div>
        </div>
        <div id="Echarts" style="width: 1000px; height: 640px;"/>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      OpName: '',
      OpNameList: '',
      showEchartsType: '1',
      collectionTime: [],
      tableDataExcel: [],
      loading: false,
      tableData: [],
      date: '',
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      pageList: 1, // 后台获取页,
      deviceStatus_state: ['关机', '待机', '运行', '报警', '暂停'],
      deviceStatus_colors: ['grey', 'orange', 'green', 'green', 'blue']
    }
  },
  created() {
    this.getOpName()
    var now = new Date()
    this.date = now
    this.searchTable()
    this.initEcharts()
  },
  methods: {
    // 查询工位号
    getOpName() {
      var param = []
      var Data = this.CreateData('11', '工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.OpNameList = []
        for (const item of response.data) {
          this.OpNameList.push({ label: item.工位号, value: item.工位号 })
        }
      })
    },
    // 查询
    searchTable() {
      if (this.date.length === 0) {
        this.$message.error('请选择需要查询的日期！')
        return
      }
      // if (this.OpName.length === 0) {
      //   this.$message.error('请选择工位号！')
      //   return
      // }
      this.loading = true
      this.tableData = []
      var param = []
      param[0] = ['工位号', this.OpName]
      param[1] = ['开始时间', this.date]
      param[2] = ['结束时间', this.collectionTime[1]]
      param[3] = ['PageCurrent', this.pageList]
      param[4] = ['PageSize', this.pageSize]
      param[5] = ['PageCount', '1111', 'int', '1']
      param[6] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData('11', '设备管理_设备每分钟状态_管理系统_分页_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData = response.data.result
        }
        this.total = parseInt(response.data.output[0].ItemCount)
        this.loading = false
      })
    },
    initEcharts() {
      if (this.date.length === 0) {
        // this.$message.error('请选择需要查询的时间段！')
        return
      }
      // if (this.OpName.length === 0) {
      //   // this.$message.error('请选择工位号！')
      //   return
      // }
      this.deviceStatus_table = []
      var param = []
      param[0] = ['工位号', this.OpName]
      param[1] = ['开始时间', this.date]
      param[2] = ['结束时间', this.collectionTime[1]]
      const data = this.CreateData('11', '设备管理_设备每分钟状态_管理系统_查询', param)
      this.ExecDatabase(data).then((response) => {
        this.deviceStatus_table = response.data
      }).then(() => {
        this.drawDashboard44()
      })
    },
    // 设备运行履历
    drawDashboard44() {
      const scope = this
      const deviceStatus_data = []
      const deviceStatus_yAxisValue = []
      let deviceStatus_index = 0
      if (this.deviceStatus_table.length === 1) {
        deviceStatus_data.push({
          itemStyle: { normal: { color: this.deviceStatus_table[0].颜色 }}, // 条形颜色
          name: this.deviceStatus_table[0].设备状态名称,
          value: [0, this.deviceStatus_table[0].开始时间, this.deviceStatus_table[0].结束时间]
        })
      } else {
        for (let i = 0; i < this.deviceStatus_table.length; i++) {
          if (i < this.deviceStatus_table.length) {
            if (i === 0) {
              deviceStatus_index = 0
              deviceStatus_yAxisValue.push(this.deviceStatus_table[i].工位号)
            } else if (this.deviceStatus_table[i].工位号 !== this.deviceStatus_table[i - 1].工位号) {
              deviceStatus_index++ // y轴索引
              deviceStatus_yAxisValue.push(this.deviceStatus_table[i].工位号)
            }
          }
          deviceStatus_data.push({
            itemStyle: { normal: { color: this.deviceStatus_table[i].颜色 }}, // 条形颜色
            name: this.deviceStatus_table[i].设备状态名称,
            value: [parseInt(deviceStatus_index), this.deviceStatus_table[i].开始时间, this.deviceStatus_table[i].结束时间]
          })
        }
      }

      const myChart = echarts.init(document.getElementById('Echarts'))
      myChart.clear()
      myChart.setOption({
        // title: {
        //   left: 'center',
        //   text: '设备状态分布图(分钟)',
        //   textStyle: {
        //     color: '#ffffff'
        //   }
        // },
        color: this.deviceStatus_colors,
        tooltip: { // 提示框
          formatter(params) {
            return params.value[1].substr(11, 5) + '~' + params.value[2].substr(11, 5)
          } // 数据的值
        },
        grid: { // 绘图网格
          left: '10px',
          right: '4%',
          top: '10%',
          bottom: '2%',
          containLabel: true
        },
        legend: { // 图例
          data: ['关机', '待机', '运行', '暂停', '报警'],
          selectedMode: false,
          textStyle: {
            color: '#272727'
          }
        },
        xAxis: {
          type: 'time',
          axisLine: {
            lineStyle: {
              color: '#272727'
            },
            show: true
          },
          axisTick: {
            show: true
          },
          interval: 1000 * 60 * 60 * 2,
          axisLabel: {
            formatter(value) {
              var date = new Date(value)
              return getzf(date.getHours()) + ':' + getzf(date.getMinutes())

              function getzf(num) {
                if (parseInt(num) < 10) {
                  num = '0' + num
                }
                return num
              }
            }
          }
        },
        yAxis: {
          axisLine: {
            lineStyle: {
              color: '#272727'
            }
          },
          data: deviceStatus_yAxisValue
        },
        series: [
          // 用空bar来显示几个图例
          { name: this.deviceStatus_state[0], type: 'bar', data: [] },
          { name: this.deviceStatus_state[1], type: 'bar', data: [] },
          { name: this.deviceStatus_state[2], type: 'bar', data: [] },
          { name: this.deviceStatus_state[3], type: 'bar', data: [] },
          { name: this.deviceStatus_state[4], type: 'bar', data: [] },
          {
            type: 'custom',
            renderItem(params, api) { // 开发者自定义的图形元素渲染逻辑，是通过书写 renderItem 函数实现的
              var categoryIndex = api.value(0) // 这里使用 api.value(0) 取出当前 dataItem 中第一个维度的数值。
              var start = api.coord([api.value(1), categoryIndex]) // 这里使用 api.coord(...) 将数值在当前坐标系中转换成为屏幕上的点的像素值。
              var end = api.coord([api.value(2), categoryIndex])
              var height = 18 // 柱体宽度
              return {
                type: 'rect', // 表示这个图形元素是矩形。还可以是 'circle', 'sector', 'polygon' 等等。
                shape: echarts.graphic.clipRectByRect({ // 矩形的位置和大小。
                  x: start[0],
                  y: start[1] - height,
                  width: end[0] - start[0],
                  height: height * 1.2
                }, { // 当前坐标系的包围盒。
                  x: params.coordSys.x,
                  y: params.coordSys.y,
                  width: params.coordSys.width,
                  height: params.coordSys.height
                }),
                style: api.style()
              }
            },
            encode: {
              x: [1, 2], // data 中『维度1』和『维度2』对应到 X 轴
              y: 0 // data 中『维度0』对应到 Y 轴
            },
            data: deviceStatus_data
          }
        ]
      })
    },
    // 分页
    handleSizeChange(val) {
      this.pageList = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageList = val
      this.searchTable()
    }
  }
}
</script>
