<template>
  <div class="app-container">
    <el-card class="topCard">
      <el-tabs v-model="activeName">
        <el-tab-pane label="各区JPH完成统计" name="first">
          <div style="height: 780px;overflow: auto;width: 1500px">
            <el-row v-for="item in JPHDataList" :key="item" style="margin: 5px">
              <div style="height: 500px;border: 1px solid #868686">
                <!--<div style="position: absolute;right: 5%;top: 2%;font-size: 1.5rem">
                  <div style="padding: 12px 20px;line-height: 1;border: 2px solid #00893d;">
                    <span>当班产量：</span>
                    <span style="font-weight: bolder">{{ currentBeatCount.get(item) }}</span>
                  </div>
                </div>-->
                <!--<el-button type="text" icon="el-icon-refresh" style="position: absolute;right: 2%;top: 2%;font-size: 1.5rem" @click="searchChartData4_opPlanCount"/>-->
                <div :id="item + '_big'" style="width: 1400px;height: 500px;margin: 5px"/>
              </div>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="工位JPH查询" name="second">
          <el-row style="margin-top: 5px">
            <span style="margin-left: 10px">日期:</span>
            <el-date-picker
              v-model="timeFrame"
              :picker-options="pickerOptions"
              size="small"
              type="daterange"
              class="functionButton"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"/>
            <span style="margin-left: 10px">工位号:</span>
            <el-select v-model="station" class="functionButton" size="small" placeholder="请选择">
              <el-option
                v-for="item in stationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" size="small" icon="el-icon-search" plain style="margin-left: 10px" @click="searchTable()">查询</el-button>
            <el-button style="margin-left: 0" type="info" icon="el-icon-download" size="small" plain @click="exportExcel()">Excel</el-button>
            <span v-show="isExporting" style="color: #16a188">正在导出....</span>
            <div style="height: 50px;line-height: 20px">
              <span>
                小时范围:
              </span>
              <div style="display: inline-block;width: 1000px;margin-left: 10px">
                <el-slider
                  v-model="timeRange"
                  :max="23"
                  :marks="marks"
                  range
                  @change="changeHourRange" />
              </div>
            </div>
          </el-row>
          <el-row>
            <el-table
              v-loading="loading"
              :data="tableData"
              :cell-style="set_cell_style"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
              element-loading-text="数据加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.2)"
              highlight-current-row
              border
              stripe
              tooltip-effect="dark"
              height="730px">
              <el-table-column width="50px" label="ID" align="center">
                <template slot-scope="scope">
                  {{ scope.row.ID }}
                </template>
              </el-table-column>
              <el-table-column width="105px" label="日期" align="center">
                <template slot-scope="scope">
                  {{ scope.row.日期 }}
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in JPHHeaderF"
                :key="index"
                :label="item"
                :width="calculateCellWidth(item)"
                align="center">
                <template slot-scope="scope">
                  {{ scope.row[item] }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import echarts from 'echarts'
export default {
  data() {
    return {
      timer: null,
      currentBeatCount: new Map(),
      JPHData: new Map(),
      JPHData_PlanCount: new Map(),
      JPHDataList: [],
      activeName: 'first',
      isExporting: false,
      timeRange: [0, 23],
      marks: {
        '0': '00',
        '1': '01',
        '2': '02',
        '3': '03',
        '4': '04',
        '5': '05',
        '6': '06',
        '7': '07',
        '8': '08',
        '9': '09',
        '10': '10',
        '11': '11',
        '12': '12',
        '13': '13',
        '14': '14',
        '15': '15',
        '16': '16',
        '17': '17',
        '18': '18',
        '19': '19',
        '20': '20',
        '21': '21',
        '22': '22',
        '23': '23'
      },
      JPHHeader: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
      JPHHeader2: ['结果'],
      JPHHeaderF: [],
      // 时间范围
      timeFrame: '',
      tableHeader: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 两个复选框
      alarmNameOptions: [],
      stationOptions: [],
      station: '',
      alarmCode: [],
      alarmCodeString: '',
      // 表格
      tableData: [],
      loading: false,
      // 分页
      pageCurrent: 1, // 分页当前页
      pageSize: 10, // 分页每页显示条数
      total: 0 // 分页总数
    }
  },
  computed: {
  },
  created() {
    this.JPHHeaderF = [...this.JPHHeader, ...this.JPHHeader2]
    this.getStation()
    this.searchChartData4_opPlanCount()
    this.searchTable56()
  },
  mounted() {
    this.timer = setInterval(() => {
      this.searchChartData4_opPlanCount()
    }, 1000 * 60)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    getStation() {
      this.stationOptions = []
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationOptions.push({
            label: response.data[i].工位号,
            value: response.data[i].工位号
          })
        }
        this.station = this.stationOptions[0].value
      })
    },
    changeHourRange(value) {
      const newArray = this.JPHHeader.slice(value[0], value[1] + 1)
      this.JPHHeaderF = [...newArray, ...this.JPHHeader2]
      console.log(newArray)
      for (let i = 1; i < this.tableData.length; i++) {
        const tempData = this.tableData[i]
        let tempDataResultOkCount = 0
        let tempDataResultAll = 0
        for (const responseKey in tempData) {
          if (newArray.indexOf(responseKey) !== -1) {
            tempDataResultAll += 1
            if (tempData[responseKey + '_result']) {
              tempDataResultOkCount += 1
            }
            tempData['结果'] = `${tempDataResultOkCount} / ${tempDataResultAll}`
          }
        }
      }
    },
    // 设置单元格颜色
    set_cell_style({ row, column, rowIndex, columnIndex }) {
      if (row.日期 !== '目标产量') {
        if (this.JPHHeader.indexOf(column.label) !== -1) {
          if (row[column.label + '_result']) {
            return {
              'background': '#00893d',
              'color': 'white'
            }
          } else {
            return {
              'background': '#fcb3bb',
              'color': 'white'
            }
          }
        } else {
          return ''
        }
      }
    },
    searchTable() {
      if (this.timeFrame === null || this.timeFrame === '' || this.timeFrame[0] === '') {
        this.$message.error('请选择日期范围')
        this.loading = false
        return
      }
      // 查询表的信息
      this.loading = true
      this.tableData = []
      const param = []
      let tableDataTemp = []
      const Data = this.CreateData('11', 'SP_His_StationJPH_TableHeaderQuery', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          tableDataTemp = response.data
          const param1 = []
          param1[0] = ['QueryStartDate', this.timeFrame[0]]
          param1[1] = ['QueryEndDate', this.timeFrame[1]]
          param1[2] = ['Station', this.station]
          const Data1 = this.CreateData('11', 'SP_His_StationJPH_Query', param1)
          this.ExecDatabase(Data1).then(response => {
            if (response.data.length > 0) {
              for (let i = 0; i < response.data.length; i++) {
                const tempData = response.data[i]
                let tempDataResult = false
                let tempDataResultOkCount = 0
                let tempDataResultAll = 0
                for (const responseKey in tempData) {
                  if (this.JPHHeader.indexOf(responseKey) !== -1) {
                    tempDataResultAll += 1
                    if (tempData[responseKey] > tableDataTemp[0][responseKey]) {
                      tempDataResult = true
                      tempDataResultOkCount += 1
                    } else {
                      tempDataResult = false
                    }
                    tempData[responseKey + '_result'] = tempDataResult
                    tempData['结果'] = `${tempDataResultOkCount} / ${tempDataResultAll}`
                  }
                }
                tableDataTemp.push(tempData)
              }
            }
            this.tableData = tableDataTemp
            this.loading = false
          })
        } else {
          this.$message({
            message: '选择的该时间段没有数据！',
            type: 'error'
          })
          this.loading = false
        }
      })
    },
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('请查询要导出的内容')
        return
      }
      if (this.tableData.length) {
        this.isExporting = false
        const newTable = []
        for (let i = 0; i < this.tableData.length; i++) {
          newTable.push({
            'ID': this.tableData[i]['ID'],
            '日期': this.tableData[i]['日期'],
            '00': this.tableData[i]['00'] ? this.tableData[i]['00'] : 0,
            '01': this.tableData[i]['01'] ? this.tableData[i]['01'] : 0,
            '02': this.tableData[i]['02'] ? this.tableData[i]['02'] : 0,
            '03': this.tableData[i]['03'] ? this.tableData[i]['03'] : 0,
            '04': this.tableData[i]['04'] ? this.tableData[i]['04'] : 0,
            '05': this.tableData[i]['05'] ? this.tableData[i]['05'] : 0,
            '06': this.tableData[i]['06'] ? this.tableData[i]['06'] : 0,
            '07': this.tableData[i]['07'] ? this.tableData[i]['07'] : 0,
            '08': this.tableData[i]['08'] ? this.tableData[i]['08'] : 0,
            '09': this.tableData[i]['09'] ? this.tableData[i]['09'] : 0,
            '10': this.tableData[i]['10'] ? this.tableData[i]['10'] : 0,
            '11': this.tableData[i]['11'] ? this.tableData[i]['11'] : 0,
            '12': this.tableData[i]['12'] ? this.tableData[i]['12'] : 0,
            '13': this.tableData[i]['13'] ? this.tableData[i]['13'] : 0,
            '14': this.tableData[i]['14'] ? this.tableData[i]['14'] : 0,
            '15': this.tableData[i]['15'] ? this.tableData[i]['15'] : 0,
            '16': this.tableData[i]['16'] ? this.tableData[i]['16'] : 0,
            '17': this.tableData[i]['17'] ? this.tableData[i]['17'] : 0,
            '18': this.tableData[i]['18'] ? this.tableData[i]['18'] : 0,
            '19': this.tableData[i]['19'] ? this.tableData[i]['19'] : 0,
            '20': this.tableData[i]['20'] ? this.tableData[i]['20'] : 0,
            '21': this.tableData[i]['21'] ? this.tableData[i]['21'] : 0,
            '22': this.tableData[i]['22'] ? this.tableData[i]['22'] : 0,
            '23': this.tableData[i]['23'] ? this.tableData[i]['23'] : 0,
            '结果': this.tableData[i]['结果'] ? this.tableData[i]['结果'] : ''
          })
        }
          import('@/vendor/Export2Excel').then(excel => {
            const dataGroup = []
            const filterVal = ['ID', '日期', '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '结果']
            const data = newTable.map(v => filterVal.map(j => v[j]))
            dataGroup.push(data)
            // 这个导出可以指定多个sheet表即使你只导出一个，你也要把 headerGroup定义为二维数组！！！！！！
            const headerGroup = [['ID', '日期', '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '结果']]
            const sheetGroup = ['工位JPH']
            excel.export_json_to_excel({
              headerGroup: headerGroup,
              dataGroup: dataGroup,
              sheetGroup: sheetGroup,
              filename: '工位JPH',
              autoWidth: true,
              bookType: 'xlsx'
            })
            this.isExporting = false
          })
      } else {
        this.$message.warning('请查询要导出的内容')
      }
    },
    calculateCellWidth(rowName) {
      if (rowName === '结果') {
        return '80px'
      } else {
        return '40px'
      }
    },
    // JPH查询
    searchChartData4() {
      const scope = this
      this.JPHData = new Map()
      var param4 = []
      var Data4 = this.CreateData('11', 'Visualization_HoursOutput_Query', param4)
      this.ExecDatabase(Data4).then(response => {
        if (response.data.length !== 0) {
          const list = []
          for (const argument of response.data) {
            const temp = this.JPHData.get(argument.StationName)
            if (temp) {
              temp['HH'].push(argument['HH'])
              temp['DataCount'].push(argument['DataCount'])
            } else {
              list.push(argument.StationName)
              this.JPHData.set(argument.StationName, {
                HH: [argument['HH']],
                DataCount: [argument['DataCount']],
                StationName: argument.StationName,
                PlanCount: this.JPHData_PlanCount.get(argument.StationName)
              })
            }
          }
          scope.JPHDataList = list
          this.$nextTick(() => {
            this.drawDashboardTwo(this.JPHData)
          })
        }
      })
    },
    drawDashboardTwo(JPHData) {
      console.log(JPHData, 222)
      JPHData.forEach(function(value, key) {
        let chartsDom1 = echarts.getInstanceByDom(document.getElementById(key.toString() + '_big'))
        if (chartsDom1 == null) {
          chartsDom1 = echarts.init(document.getElementById(key.toString() + '_big'))
        }
        chartsDom1.setOption({
          title: {
            show: true,
            text: key,
            left: 'center',
            textStyle: {
              color: '#ffaa13'
            }
          },
          grid: [
            {
              top: '15%',
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            }
          ],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            name: 'H',
            type: 'category',
            data: value['HH'],
            axisLine: {
              lineStyle: {
                color: '#6c6c6c'
              }
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              color: '#6c6c6c'
            }
          },
          yAxis: {
            name: '台',
            type: 'value',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#6c6c6c'
              }
            },
            splitLine: {
              show: false
            }
          },
          series: [
            {
              name: '下线台数',
              data: value['DataCount'],
              type: 'bar',
              itemStyle: {
                color: '#209de2'
              },
              label: {
                show: true,
                color: '#050505',
                position: 'top'
              }
            }
          ]
        })
      })
    },
    searchChartData4_opPlanCount() {
      var param4 = []
      var Data4 = this.CreateData('11', 'SP_Config_BeatCountOpName_Query', param4)
      this.ExecDatabase(Data4).then(response => {
        if (response.data.length !== 0) {
          for (let i = 0; i < response.data.length; i++) {
            this.JPHData_PlanCount.set(response.data[i].StationName, response.data[i].PlanCount)
          }
        }
        this.searchChartData4()
      })
    },
    searchTable56() {
      const param = []
      const Data = this.CreateData('11', 'Visualization_JPH_FiveOp_Query', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.currentBeatCount.set(response.data[i].StationName, response.data[i].NumCount)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
