<template>
  <div class="app-container">
    <el-card class="topCard">
      <el-tabs v-model="activeName">
        <el-tab-pane label="日产量统计" name="first">
          <div style="height: 780px;overflow: auto;width: 1500px">
            <el-row style="margin-top: 5px">
              <span style="margin-left: 10px">月份:</span>
              <el-date-picker
                v-model="dateMonth"
                type="month"
                value-format="yyyy-MM"
                format="yyyy-MM"
                placeholder="选择月"/>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                plain
                style="margin-left: 10px"
                @click="searchChartData()">查询
              </el-button>
              <span v-show="isExporting" style="color: #16a188">正在导出....</span>
            </el-row>
            <el-row style="margin-top: 5px">
              <div style="font-size: 30px;font-weight: 700">月总产量：{{ workCount }}</div>
              <div id="dashboardOne" style="height: 540px; width: 1200px;margin: 20px 0 0 0"/>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="小时产量统计" name="second">
          <el-row style="margin-top: 5px">
            <span style="margin-left: 10px">日期:</span>
            <el-date-picker
              v-model="dateDay"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              placeholder="选择日期"/>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-search"
              plain
              style="margin-left: 10px"
              @click="searchChartData2()">查询
            </el-button>
            <span v-show="isExporting" style="color: #16a188">正在导出....</span>
          </el-row>
          <el-row style="margin-top: 5px">
            <div style="font-size: 30px;font-weight: 700">日总产量：{{ workDayCount }}</div>
            <div id="dashboardTow" style="height: 540px; width: 1200px;margin: 20px 0 0 0"/>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { date } from '../../../../static/libs/jszip'

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: '',
      dateMonth: '',
      dateDay: '',
      // 表格
      tableData: [],
      loading: false,
      // 分页
      pageCurrent: 1, // 分页当前页
      pageSize: 10, // 分页每页显示条数
      total: 0, // 分页总数
      chartDom1: null,
      chartDom2: null,
      chartOption1: null,
      chartOption2: null,
      myChart1X: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
      myChart1Y1: [2, 3, 1, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0],
      myChart1Y2: [1, 2, 2, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0],
      myChart1Y3: [1, 2, 2, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0],
      myChart2X: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
      myChart2Y1: [2, 3, 1, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0],
      myChart2Y2: [1, 2, 2, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0],
      myChart2Y3: [1, 2, 2, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0],
      workCount: 0,
      workDayCount: 0
    }
  },
  computed: {
    date() {
      return date
    }
  },
  created() {
    this.JPHHeaderF = [...this.JPHHeader, ...this.JPHHeader2]
    this.getStation()
    this.searchTable56()
    this.getTodayDate()
  },
  mounted() {
    this.initChart()
    this.searchChartData()
    this.searchChartData2()
  },
  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
      })
    },
    getTodayDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0') // 月份是从0开始的，所以需要+1
      const day = String(today.getDate()).padStart(2, '0')
      this.dateMonth = `${year}-${month}`
      this.dateDay = `${year}-${month}-${day}`
    },
    initChart() {
      this.chartDom1 = echarts.init(document.getElementById('dashboardOne'))
      this.chartDom2 = echarts.init(document.getElementById('dashboardTow'))
    },
    // 数据库查询图表相关数据
    searchChartData() {
      var param1 = []
      param1[0] = ['month', this.dateMonth]
      var Data1 = this.CreateData('11', '日产量统计', param1)
      this.ExecDatabase(Data1).then((response) => {
        this.workCount = 0
        if (response.data.length !== 0) {
          this.myChart1X = []
          this.myChart1Y1 = []
          this.myChart1Y2 = []
          this.myChart1Y3 = []
          for (const argument of response.data) {
            // 在18点后 只有有数据的小时才进行统计，不然的话就不记了
            this.myChart1X.push(argument['日期'].substring(argument['日期'].length - 2))
            this.myChart1Y1.push(argument['合格数'])
            this.myChart1Y2.push(argument['不合格数'])
            this.myChart1Y3.push(argument['总产量'])
            this.workCount += Number(argument['总产量'])
          }
          this.drawDashboardOne()
        }
      })
    },
    // 数据库查询图表相关数据
    searchChartData2() {
      var param1 = []
      param1[0] = ['TimeDate', this.dateDay]
      var Data1 = this.CreateData('11', '小时产量统计', param1)
      this.ExecDatabase(Data1).then((response) => {
        this.workDayCount = 0
        if (response.data.length !== 0) {
          this.myChart2X = []
          this.myChart2Y1 = []
          this.myChart2Y2 = []
          this.myChart2Y3 = []
          for (const argument of response.data) {
            // 在18点后 只有有数据的小时才进行统计，不然的话就不记了
            this.myChart2X.push(argument['Hour'])
            this.myChart2Y1.push(argument['合格数'])
            this.myChart2Y2.push(argument['不合格数'])
            this.myChart2Y3.push(argument['总产量'])
            this.workDayCount += Number(argument['总产量'])
          }
          this.drawDashboardTow()
        }
      })
    },
    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 ''
        }
      }
    },
    drawDashboardOne() {
      this.chartOption1 = {
        title: {
          text: this.dateMonth + ' 日产量',
          left: '7%', // 标题距离左侧边距
          top: '0%', // 标题距顶部边距
          textStyle: {
            color: '#000000',
            fontSize: 30
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {} // 下载图片
          }
        },
        animation: true, // 控制动画示否开启
        animationDuration: 2000, // 动画的时长，它是以毫秒为单位
        grid: [
          {
            z: 0,
            left: '5%',
            top: '25%',
            right: '0%',
            bottom: '10%'
          }
        ],
        legend: {
          data: ['合格数', '不合格数', '总产量'],
          textStyle: {
            color: '#000000',
            fontSize: 30
          },
          top: '00px'
        },

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.myChart1X,
          axisLine: {
            lineStyle: {
              color: '#000',
              fontSize: 25
            }
          },
          axisLabel: {
            color: 'black',
            fontSize: 25
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: 'black',
            fontSize: 25
          }
        },
        series: [
          {
            name: '合格数',
            data: this.myChart1Y1,
            type: 'bar',
            itemStyle: {
              normal: {
                color: '#00ff00'
                // label: {
                //   show: true,
                //   position: 'top',
                //   textStyle: {
                //     fontSize: 15,
                //     color: 'rgba(0,0,0)'
                //   }
                // }
              }
            }
          },
          {
            name: '不合格数',
            data: this.myChart1Y2,
            type: 'bar',
            itemStyle: {
              normal: {
                color: '#ffbd44'
                // label: {
                //   show: true,
                //   position: 'top',
                //   textStyle: {
                //     fontSize: 15,
                //     color: 'rgba(0,0,0)'
                //   }
                // }
              }
            }
          },
          {
            name: '总产量',
            type: 'line',
            // yAxisIndex: 0,    //这里要设置哪个y轴，默认是最左边的是0，然后1，2顺序来。
            data: this.myChart1Y3,
            symbolSize: 10,
            itemStyle: {
              normal: {
                color: 'rgba(0,255,255,0.6)',
                border: 10,
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    fontSize: 15,
                    color: 'rgba(0,0,0)'
                  }
                }
              }
            },
            lineStyle: {
              normal: {
                width: 5
              }
            }
          }
        ]
      }
      // this.chartDom1.setOption(this.chartOption1)
      this.chartDom1.clear()
      this.chartDom1.setOption(this.chartOption1)
    },
    drawDashboardTow() {
      this.chartOption2 = {
        title: {
          text: this.dateDay + ' 小时产量',
          left: '7%', // 标题距离左侧边距
          top: '0%', // 标题距顶部边距
          textStyle: {
            color: '#000000',
            fontSize: 30
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {} // 下载图片
          }
        },
        animation: true, // 控制动画示否开启
        animationDuration: 2000, // 动画的时长，它是以毫秒为单位
        grid: [
          {
            z: 0,
            left: '5%',
            top: '25%',
            right: '0%',
            bottom: '10%'
          }
        ],
        legend: {
          data: ['合格数', '不合格数', '总产量'],
          textStyle: {
            color: '#000000',
            fontSize: 30
          },
          top: '00px'
        },

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.myChart2X,
          axisLine: {
            lineStyle: {
              color: '#000',
              fontSize: 25
            }
          },
          axisLabel: {
            color: 'black',
            fontSize: 25
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: 'black',
            fontSize: 25
          }
        },
        series: [
          {
            name: '合格数',
            data: this.myChart2Y1,
            type: 'bar',
            itemStyle: {
              normal: {
                color: '#00ff00'
                // label: {
                //   show: true,
                //   position: 'top',
                //   textStyle: {
                //     fontSize: 15,
                //     color: 'rgba(0,0,0)'
                //   }
                // }
              }
            }
          },
          {
            name: '不合格数',
            data: this.myChart2Y2,
            type: 'bar',
            itemStyle: {
              normal: {
                color: '#ffbd44'
                // label: {
                //   show: true,
                //   position: 'top',
                //   textStyle: {
                //     fontSize: 15,
                //     color: 'rgba(0,0,0)'
                //   }
                // }
              }
            }
          },
          {
            name: '总产量',
            type: 'line',
            // yAxisIndex: 0,    //这里要设置哪个y轴，默认是最左边的是0，然后1，2顺序来。
            data: this.myChart2Y3,
            symbolSize: 10,
            itemStyle: {
              normal: {
                color: 'rgba(0,255,255,0.6)',
                border: 10,
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    fontSize: 15,
                    color: 'rgba(0,0,0)'
                  }
                }
              }
            },
            lineStyle: {
              normal: {
                width: 5
              }
            }
          }
        ]
      }
      this.chartDom2.clear()
      this.chartDom2.setOption(this.chartOption2)
    },
    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>
