<template>
  <div class="app-container">
    <!--<div style="width: 100%;display: flex;justify-content: space-between;padding: 0 20px 0 10px">-->
    <!--<el-button>111</el-button>-->
    <!--<el-button>111</el-button>-->
    <!--<el-button>111</el-button>-->
    <!--<el-button>111</el-button>-->
    <!--</div>-->
    <!--<div style="width: 100%; height: 200px; background-color: #55a532;display: flex;justify-content: center;align-items: center">11</div>-->
    <!--<div style="width: 100%; height: 200px; background-color: gold;display: flex;justify-content: center;align-items: center;flex-direction: column">-->
    <!--<span>1</span>-->
    <!--<span>2</span>-->
    <!--<span>3</span>-->
    <!--</div>-->
    <el-card style="">
      <el-row>
        <span>开始日期:</span>
        <el-date-picker v-model="startTime" size="small" type="date" value-format="yyyy-MM-dd" style="width:135px" placeholder="开始时间"/>
        <span>结束日期:</span>
        <el-date-picker v-model="endTime" size="small" type="date" value-format="yyyy-MM-dd" style="width:135px" placeholder="结束时间"/>
        <el-button type="success" icon="el-icon-search" size="small" style="margin-left: 20px;margin-top: 15px" @click="fetchData();searchChart()">查询</el-button>
        <!--;searchChart();searchChart2()-->
        <el-button type="primary" size="small" icon="el-icon-download" style="margin-left: 10px;margin-top: 15px" @click="handleDownload">导出EXCEL</el-button>
      </el-row>
    </el-card>

    <el-card style="margin-top: 10px">
      <el-table
        :data="tableData"
        :row-class-name="tableRowClassName"
        border
        element-loading-text="数据加载中"
        highlight-current-row
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        fit
        style="max-height: 540px;max-width: 1280px"
        height= "440px"
        size="small"
      >
        <el-table-column label="报警类型" min-width="100" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.测量项目 }}
          </template>
        </el-table-column>
        <el-table-column label="工位名称" min-width="100" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.工位号 }}
          </template>
        </el-table-column>
        <el-table-column label="处理状态" min-width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.信号值 === 1 || scope.row.信号值 === '1'" size="small" type="danger">正在报警</el-tag>
            <el-tag v-else size="small" type="success">处理完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="报警开始时间" min-width="120" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.报警开始时间 }}
          </template>
        </el-table-column>
        <el-table-column label="报警结束时间" min-width="120" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.报警结束时间 }}
          </template>
        </el-table-column>
        <el-table-column label="操作时间" min-width="120" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.操作时间 }}
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          :total="totalNum"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-row style="max-width: 1300px">
        <el-col :span="12">
          <div id="myChart" style="width: 600px;height: 400px;margin: auto;margin-top: 20px;"/>
        </el-col>
        <el-col :span="12">
          <div id="myChart2" style="width: 700px;height: 400px;margin-top: 20px;"/>
        </el-col>
      </el-row>
    </el-card>
    <!--<el-card style="margin-top: 10px">-->
    <!--<el-row>-->
    <!--<el-col :span="12">-->
    <!--<div id="myChart3" style="width: 600px;height: 400px;margin: auto;margin-top: 20px;"/>-->
    <!--</el-col>-->
    <!--<el-col :span="12">-->
    <!--<div id="myChart4" style="width: 600px;height: 400px;margin: auto;margin-top: 20px;"/>-->
    <!--</el-col>-->
    <!--</el-row>-->
    <!--</el-card>-->
  </div>
</template>

<script>
import { ExecDatabase } from '@/main'
import { getNowTime, getNowTime2 } from '@/utils/tool'
import request from '@/utils/request'
export default {
  data() {
    return {
      startTime: getNowTime2(),
      endTime: getNowTime(),
      tableData: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 10,
      pageCurrent: 1,
      totalNum: null,
      downloadLoading: '',
      tableData_excel: [],
      colorchart: []
    }
  },
  watch: {
  },
  created() {
    // this.fetchData()
    // this.measureSelect()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (row.信号值 === 0) {
        return 'warning-row'
      } else if (row.信号值 === 1) {
        return 'background-color: red !important'
      }
    },
    fetchData() {
      this.listLoading = true
      var param = []
      param[0] = ['结束时间', this.endTime]
      param[1] = ['开始时间', this.startTime]
      param[2] = ['PageCurrent', this.pageCurrent]
      param[3] = ['PageSize', this.pageSize]
      param[4] = ['PageCount', 1000, 'int', '1']
      param[5] = ['ItemCount', 1000, 'int', '1']
      var Data = this.CreateData('11', '设备报警_报警历史查询_管理软件分页', param)
      ExecDatabase(Data).then(response => {
        this.tableData = response.data.result
        this.totalNum = parseInt(response.data.output[0].ItemCount)
        this.listLoading = false
      }).catch(er => {
        this.listLoading = false
        this.$message.error('错误')
      }
      )
    },
    // 分页功能改变显示数量
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 分页功能改变当前页
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.fetchData()
    },
    // 导出excel
    handleDownload() {
      this.downloadLoading = true
      // const tHeader = ['呼叫类型名称', '呼叫原因名称', '呼叫原因名称_二级', '工位名称', '处理状态代码', '发动机流水号', '呼叫备注', '呼叫人员呼叫时间']
      // const filterVal = ['呼叫类型名称', '呼叫原因名称', '呼叫原因名称_二级', '工位名称', '处理状态代码', '发动机流水号', '呼叫备注', '呼叫人员呼叫时间']
      // const list = this.tableData_excel
      var s = ``
      if (this.startTime && this.endTime) {
        s = ` where  操作时间>='${this.startTime}' and 操作时间<='${this.endTime}'`
      }
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: `  select * from [报警数据_大柴]` + s
        }
      }).then(response => {
        this.tableData_excel = []
        if (response.data.length !== 0) {
          this.tableData_excel = response.data
          this.downloadLoading = true
            import('@/vendor/Export2Excel').then(excel => {
              const tHeader = ['报警类型', '工位名称', '处理状态', '报警开始时间', '报警结束时间', '操作时间']
              const filterVal = ['测量项目', '工位号', '信号值', '报警开始时间', '报警结束时间', '操作时间']
              const list = this.tableData_excel
              const data = this.formatJson(filterVal, list)
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: '报警统计表',
                autoWidth: this.autoWidth,
                bookType: this.bookType
              })
              this.downloadLoading = false
            })
        } else {
          this.$message.error('无数据无法导出')
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    // 获取图形数据
    drawLine(res) {
      const myChart = this.$echarts.init(document.getElementById('myChart'))
      const myChart2 = this.$echarts.init(document.getElementById('myChart2'))
      const xData = []
      const yData = []
      const series = []
      for (let i = 0; i < res.length; i++) {
        xData.push(res[i].测量项目)
      }
      for (let i = 0; i < res.length; i++) {
        yData.push(res[i].次数)
      }
      for (let i = 0; i < res.length; i++) {
        series.push({
          value: res[i].次数,
          name: res[i].测量项目
        })
      }
      // 随机颜色方式
      var colorList = []
      for (var i = 0; i < res.length; i++) {
        var colorStr = Math.floor(Math.random() * 0xffffff).toString(16)
        // 如果颜色值是五位，则补零
        if (colorStr.length < 6) {
          colorStr += '0'
        }
        if (colorStr === '005094') {
          i--
          continue
        }
        colorList.push('#' + colorStr)
      }
      this.colorchart = colorList
      // colorList = ['#C33531','#EFE42A','#64BD3D','#EE9201','#29AAE3', '#B74AE5','#0AAF9F','#E89589','#16A085','#4A235A','#C39BD3 ','#F9E79F','#BA4A00','#ECF0F1','#616A6B','#EAF2F8','#4A235A','#3498DB' ];
      myChart.clear()
      myChart.setOption({
        // color: ['#3398DB'],
        title: {
          left: 'center',
          text: '报警分类统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '12%',
          bottom: '3%',
          containLabel: true,
          show: true
        },
        xAxis: [
          {
            name: '报警类型',
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          }
        ],
        yAxis: [
          {
            name: '报警次数',
            type: 'value'
          }
        ],
        series: [
          {
            name: '报警次数',
            type: 'bar',
            barWidth: '60%',
            data: yData,
            itemStyle: {
              normal: {
                // 随机显示
                // 定制显示（按顺序）
                color: function(params) {
                  // colorList = colorList
                  return colorList[params.dataIndex]
                },
                label: {
                  show: true,		// 开启显示
                  position: 'top',	// 在上方显示
                  textStyle: { // 数值样式
                    color: 'black',
                    fontSize: 16
                  }
                }
              }
            }
          }
        ]
      })

      myChart2.clear()
      myChart2.setOption({
        title: {
          text: '报警类型比例',
          // subtext: '分类统计',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: xData
        },
        series: [
          {
            name: '报警类型',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: series,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              normal: {
                label: {
                  show: true,
                  formatter: '{b} : {c} ({d}%)'
                },
                labelLine: { show: true },
                // 随机显示
                // 定制显示（按顺序）
                color: function(params) {
                  // colorList = colorList
                  return colorList[params.dataIndex]
                }
              }
            }
          }
        ]
      })
    },
    searchChart() {
      var s = ``
      if (this.startTime && this.endTime) {
        s = ` where  操作时间>='${this.startTime}' and 操作时间<='${this.endTime}'`
      }
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: `  select 测量项目 ,COUNT(测量项目) as 次数 from 报警数据_大柴 ` + s + `group by  测量项目  order by 次数 desc`
        }
      }).then(response => {
        this.drawLine(response.data)
      }).catch(er => {
      }
      )
    },
    searchChart2() {
      request({
        url: '',
        method: 'post',
        data: {
          type: '3',
          name: ` SELECT 呼叫类型代码,[呼叫类型名称],SUM(停台时间 ) as 停台时间
FROM dbo.安东_安东呼叫详情_主记录_视图
where  三级人员呼叫时间>='${this.startTime}' and 三级人员呼叫时间<='${this.endTime}'
GROUP BY
呼叫类型代码
,[呼叫类型名称] order by 停台时间 desc  `
        }
      }).then(response => {
        this.drawLine2(response.data)
      }).catch(er => {
      }
      )
    },
    drawLine2(res) {
      const myChart3 = this.$echarts.init(document.getElementById('myChart3'))
      const myChart4 = this.$echarts.init(document.getElementById('myChart4'))
      const xData = []
      const yData = []
      const series = []
      for (let i = 0; i < res.length; i++) {
        xData.push(res[i].呼叫类型名称)
      }
      for (let i = 0; i < res.length; i++) {
        yData.push(res[i].停台时间)
      }
      for (let i = 0; i < res.length; i++) {
        series.push({
          value: res[i].停台时间,
          name: res[i].呼叫类型名称
        })
      }
      // 随机颜色方式
      var colorList = []
      for (var i = 0; i < res.length; i++) {
        var colorStr = Math.floor(Math.random() * 0xffffff).toString(16)
        // 如果颜色值是五位，则补零
        if (colorStr.length < 6) {
          colorStr += '0'
        }
        if (colorStr === '005094') {
          i--
          continue
        }
        colorList.push('#' + colorStr)
      }
      // colorList = ['#C33531','#EFE42A','#64BD3D','#EE9201','#29AAE3', '#B74AE5','#0AAF9F','#E89589','#16A085','#4A235A','#C39BD3 ','#F9E79F','#BA4A00','#ECF0F1','#616A6B','#EAF2F8','#4A235A','#3498DB' ];
      myChart3.clear()
      myChart3.setOption({
        // color: ['#3398DB'],
        title: {
          left: 'center',
          text: '条形统计图'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '12%',
          bottom: '3%',
          containLabel: true,
          show: true
        },
        xAxis: [
          {
            name: '呼叫类型',
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            name: '停台时间',
            type: 'value'
          }
        ],
        series: [
          {
            name: '停台时间',
            type: 'bar',
            barWidth: '60%',
            data: yData,
            itemStyle: {
              normal: {
                // 随机显示
                // 定制显示（按顺序）
                color: function(params) {
                  // colorList = colorList
                  return colorList[params.dataIndex]
                },
                label: {
                  show: true,		// 开启显示
                  position: 'top',	// 在上方显示
                  textStyle: { // 数值样式
                    color: 'black',
                    fontSize: 16
                  }
                }
              }
            }
          }
        ]
      })

      myChart4.clear()
      myChart4.setOption({
        title: {
          text: '分类统计',
          // subtext: '分类统计',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: xData
        },
        series: [
          {
            name: '呼叫类型',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: series,
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              },
              normal: {
                // 随机显示
                // 定制显示（按顺序）
                color: function(params) {
                  // colorList = colorList
                  return colorList[params.dataIndex]
                }
              }
            }
          }
        ]
      })
    }
  }
}
</script>

<style scoped>
  span{
    /*margin: 10px 0px 10px 10px;*/
  }
  .el-table .warning-row{

  }
  .el-table .warning-row {
       background: #a94442;
     }
  .el-table .sucess-row {
    background: #f0f9eb;
  }
  .el-table td, .is-leaf{
    background-color: rgb(255, 91, 103);
    color: black;
    font-weight:400
  }
</style>

