<template>
  <div>
    <el-card>
      <!-- <span class="show-text">设备:</span>
      <el-select v-model="OpName" clearable @change="getPostList()" filterable placeholder="请选择设备"
        style="width: 200px;margin-right: 10px">
        <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-input v-model="posName" placeholder="数据名称" clearable style="width: 200px;margin-right: 10px" /> -->
      <span class="show-text">采集日期:</span>
      <el-date-picker v-model="collectionTime" :clearable="false" :picker-options="pickerOptions" end-placeholder="结束时间"
        format="yyyy-MM-dd" popper-class="virtual-cell-time-picker" range-separator="-" start-placeholder="开始时间"
        style="width: 280px;vertical-align: top" type="datetimerange" value-format="yyyy-MM-dd" />
      <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="searchTable()">查询</el-button>
      <!-- <el-button :disabled="loading" icon="el-icon-download" plain type="success" @click="searchTableExport()">导出
      </el-button> -->
      <div style="margin-top: 10px;display: flex;">
        <div>
          <div style="width: 100%; display: flex; ">
            <div id="chartDom2" style="width: 40%; height: 250px"></div>
            <div id="chartDom3" style="width: 60%; height: 250px"></div>
          </div>
          <el-table v-loading="loading" :data="tableData" border element-loading-background="rgba(0, 0, 0, 0.2)"
            :height="'50vh'" element-loading-spinner="el-icon-loading" size="mini" style="width: 1101px;"
            tooltip-effect="dark">
            <el-table-column align="center" label=" " type="index" width="50" />
            <el-table-column align="center" label="设备" width="150">
              <template slot-scope="scope">
                {{ scope.row.工位号 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="设备名称" width="120">
              <template slot-scope="scope">
                {{ scope.row.工位名称 || scope.row.工位号 }}
              </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="持续时间" width="100">
              <template slot-scope="scope">
                {{ scope.row.持续时间 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="开始时间" width="160">
              <template slot-scope="scope">
                {{ scope.row.开始时间 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="结束时间" width="160">
              <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>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      OpName: '',
      OpNameList: [],
      posName: '',
      posNameList: [],
      chartDom2: null,
      chartDom3: null,
      chart2Data: [],
      chart3X1: [],
      chart3X2: [],
      chart2DataColor: ['#49a9ee', '#98d87d', '#ffd86e', '#f3857b', '#8996e6'],
      showEchartsType: '1',
      collectionTime: [],
      tableDataExcel: [],
      loading: false,
      tableData: [],
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      pageList: 1 // 后台获取页,
    }
  },
  created() {
    this.getOpName()
    var now = new Date()
    var start = new Date(Date.UTC(now.getFullYear(), now.getMonth() - 1, now.getDate(), 0, 0, 0)).toISOString().replace('T', ' ').replace('.000Z', '')
    var end = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)).toISOString().replace('T', ' ').replace('.000Z', '')
    this.collectionTime = [start, end]
    this.searchTable()
  },
  methods: {
    getChart2Data() {
      var param = []
      param.push(['开始时间', this.collectionTime[0]])
      param.push(['结束时间', this.collectionTime[1]])
      const data = this.CreateData('11', 'WEB_报警看板饼图_查询', param)
      this.ExecDatabase(data).then((res) => {
        this.chart2Data = []
        if (res.data.length <= 0) {
          this.chart2Data.push({
            value: '0',
            name: '无报警',
            itemStyle: {
              color: this.chart2DataColor[0]
            }
          })
          return
        }
        for (let i = 0; i < res.data.length; i++) {
          let ele = res.data[i]
          this.chart2Data.push({
            value: ele.出现次数,
            name: ele.报警内容,
            itemStyle: {
              color: this.chart2DataColor[i]
            }
          })
        }
      }).then(() => {
        this.chart2OptionSet()
      })
    },
    chart2OptionSet() {
      let chartDom2Option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: -5,
          top: '15%',
          itemGap: 5,
          icon: 'circle',
          formatter: function (name) {
            var total = 0
            var targetValue
            // 直接使用rightBottomPieOption，而不是this
            chartDom2Option.series[0].data.forEach(function (item) {
              total += item.value
              if (item.name === name) {
                targetValue = item.value
              }
            })
            var percentage = ((targetValue / total) * 100).toFixed(2) + '%'
            return name + ' ' + targetValue + '个 ' + percentage
          }.bind(this), // 使用bind(this)确保this指向正确的上下文
          textStyle: {
            fontSize: 10,
            color: '#000'
          }
        },
        series: [
          {
            name: '问题分类',
            type: 'pie',
            radius: '80%',
            center: ['55%', '40%'],
            right: '47%',
            labelLine: {
              show: false
            },
            label: {
              show: false
            },
            data: this.chart2Data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      let chartDom = echarts.init(document.getElementById('chartDom2'))
      chartDom.setOption(chartDom2Option)
    },
    getChart3Data() {
      var param = []
      param.push(['开始时间', this.collectionTime[0]])
      param.push(['结束时间', this.collectionTime[1]])
      const data = this.CreateData('11', 'WEB_报警看板柱状_查询', param)
      this.ExecDatabase(data).then((res) => {
        if (res.data.length <= 0) {
          return
        }
        this.chart3X1 = []
        this.chart3Y1 = []
        for (let i = 0; i < res.data.length; i++) {
          const ele = res.data[i]
          this.chart3X1.push(ele.工位名称简称 || ele.工位号)
          this.chart3Y1.push(Number(ele.报警次数))
        }
      }).then(() => {
        this.chart3OptionSet()
      })
    },
    chart3OptionSet() {
      let chartDom = echarts.init(document.getElementById('chartDom3'))
      chartDom.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          top: '6%',
          left: '3%',
          right: '4%',
          bottom: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chart3X1,
          axisLabel: {
            interval: 0, // 显示所有标签
            fontSize: 13, // 设置x轴文字的大小
            color: '#000'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: true
          },
          splitLine: {
            show: false
          }
        },
        series: [
          {
            name: '出现次数',
            type: 'bar',
            stack: '总量',
            itemStyle: {
              color: '#f3857b'
            },
            data: this.chart3Y1,
            barMaxWidth: 15
          },
        ]
      })
    },
    // 查询工位号
    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.工位号 + '-' + item.工位名称简称, value: item.工位号 })
        }
      })
    },
    // 查询
    searchTable() {
      if (this.collectionTime.length === 0) {
        this.$message.error('请选择需要查询的时间段！')
        return
      }
      this.loading = true
      this.tableData = []
      var param = []
      param.push(['工位号', this.OpName])
      param.push(['数据名称', this.posName])
      param.push(['开始时间', this.collectionTime[0]])
      param.push(['结束时间', this.collectionTime[1]])
      param.push(['PageCurrent', this.pageList])
      param.push(['PageSize', this.pageSize])
      param.push(['PageCount', '1111', 'int', '1'])
      param.push(['ItemCount', '1111', 'int', '1'])
      var Data = this.CreateData('11', 'WEB_报警_记录_历史_分页查询', 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
      })
      this.getChart2Data()
      this.getChart3Data()
    },
    // 导出数据
    searchTableExport() {
      if (this.tableData.length !== 0) {
        var param = []
        param.push(['工位号', this.OpName])
        param.push(['数据名称', this.posName])
        param.push(['开始时间', this.collectionTime[0]])
        param.push(['结束时间', this.collectionTime[1]])
        param.push(['PageCurrent', this.pageList])
        param.push(['PageSize', this.pageSize])
        param.push(['PageCount', '1111', 'int', '1'])
        param.push(['ItemCount', '1111', 'int', '1'])
        var Data = this.CreateData('2001', 'WEB_报警_记录_历史_分页查询', param)
        this.exportExcel_NPOI(Data)
      } else {
        this.$message.warning('暂无数据')
      }
    },
    // 分页
    handleSizeChange(val) {
      this.pageList = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageList = val
      this.searchTable()
    }
  }
}
</script>
