<template>
  <el-card class="topCard">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane :label="$t('stationJph.realtimeTab')" name="realtime">
        <div class="chartCard">
          <div id="stationJphRealtimeChart" class="chartDom" />
        </div>
      </el-tab-pane>

      <el-tab-pane :label="$t('stationJph.historyTab')" name="history">
        <el-row class="toolbarRow">
          <span class="promptText">{{ $t('stationJph.productionTimeLabel') }}</span>
          <el-date-picker
            v-model="dateTime"
            :clearable="false"
            align="center"
            :end-placeholder="$t('stationJph.endDate')"
            format="yyyy-MM-dd"
            :range-separator="$t('stationJph.dateRangeSeparator')"
            size="small"
            :start-placeholder="$t('stationJph.startDate')"
            style="width: 240px"
            type="daterange"
            value-format="yyyy-MM-dd"
          />
          <span class="promptText">{{ $t('stationJph.stationLabel') }}</span>
          <el-select
            v-model="stationValues"
            :placeholder="$t('stationJph.selectStation')"
            clearable
            filterable
            collapse-tags
            multiple
            size="small"
            style="width: 320px"
          >
            <el-option
              v-for="item in stationOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span style="margin-left: 10px">{{ $t('stationJph.orderNumberLabel') }}</span>
          <el-input
            v-model="orderNumberValue"
            :placeholder="$t('stationJph.orderNumberPlaceholder')"
            clearable
            size="small"
            style="width: 150px"
          />
          <span class="promptText">{{ $t('stationJph.productModelLabel') }}</span>
          <el-select
            v-model="engineTypeValue"
            :placeholder="$t('stationJph.selectProductModel')"
            filterable
            clearable
            size="small"
            style="width: 150px"
          >
            <el-option
              v-for="item in engineType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            class="functionButton"
            type="primary"
            size="small"
            icon="el-icon-search"
            plain
            @click="handleSearch()"
          >{{ $t('stationJph.search') }}</el-button>
          <el-button
            type="info"
            size="small"
            icon="el-icon-download"
            plain
            @click="exportExcel()"
          >{{ $t('stationJph.export') }}</el-button>
        </el-row>

        <div class="chartCard">
          <div id="stationJphHistoryChart" class="chartDom" />
        </div>
        <el-table
          v-loading="historyLoading"
          :data="historyTableData"
          border
          stripe
          height="560px"
          style="width: 100%"
        >
          <el-table-column type="index" align="center" :label="$t('stationJph.sequence')" width="80" />
          <el-table-column prop="日期" :label="$t('stationJph.date')" align="center" min-width="120" />
          <el-table-column prop="小时段" :label="$t('stationJph.hourSlot')" align="center" min-width="120" />
          <el-table-column prop="产量" :label="$t('stationJph.outputQty')" align="center" min-width="100" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import { getNowShotTime } from '../../../utils/tool'

export default {
  data() {
    return {
      activeTab: 'realtime',
      dateTime: [],
      stationValues: [],
      stationOptions: [],
      orderNumberValue: '',
      engineTypeValue: '',
      engineType: [],
      historyTableData: [],
      realtimeLoading: false,
      historyLoading: false,
      realtimeChart: null,
      historyChart: null,
      realtimeSource: [],
      historySource: [],
      realtimeTimer: null
    }
  },
  created() {
    this.dateTime = [getNowShotTime(), getNowShotTime()]
    this.getStationOptions()
    this.getEngineType()
    this.getRealtimeData()
    this.getHistoryData()
  },
  mounted() {
    this.$nextTick(() => {
      this.initRealtimeChart()
      this.initHistoryChart()
      if (this.activeTab === 'realtime') {
        this.startRealtimePolling()
      }
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    this.stopRealtimePolling()
    window.removeEventListener('resize', this.handleResize)
    if (this.realtimeChart) {
      this.realtimeChart.dispose()
      this.realtimeChart = null
    }
    if (this.historyChart) {
      this.historyChart.dispose()
      this.historyChart = null
    }
  },
  watch: {
    '$i18n.locale'() {
      this.renderRealtimeChart()
      this.renderHistoryChart()
    }
  },
  methods: {
    getStationOptions() {
      const param = []
      const Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        const source = response.data || []
        this.stationOptions = source.map(item => ({
          label: item.工位名称 ? `【${item.工位号}】${item.工位名称}` : item.工位号,
          value: item.工位号
        }))
      })
    },
    getEngineType() {
      const param = []
      const Data = this.CreateData('11', 'MES_基本变量_机型代码_查询', param)
      this.ExecDatabase(Data).then(response => {
        const source = response.data || []
        this.engineType = source.map(item => ({
          label: item.发动机型号 + '-' + item.标识字符,
          value: item.发动机机型标志
        }))
      })
    },
    buildParams(type) {
      let stationCheck, orderCheck, engineTypeCheck
      this.stationValues.length > 0 ? stationCheck = 1 : stationCheck = 0
      this.orderNumberValue ? orderCheck = 1 : orderCheck = 0
      this.engineTypeValue ? engineTypeCheck = 1 : engineTypeCheck = 0

      const param = []
      param[0] = ['开始时间', this.dateTime[0]]
      param[1] = ['结束时间', this.dateTime[1]]
      param[2] = ['工位_check', stationCheck]
      param[3] = ['工位列表', this.stationValues.join(',')]
      param[4] = ['订单号_check', orderCheck]
      param[5] = ['订单号', this.orderNumberValue]
      param[6] = ['产品型号代码_check', engineTypeCheck]
      param[7] = ['产品型号代码', this.engineTypeValue]
      return this.CreateData(type, '', param)
    },
    handleSearch() {
      this.getHistoryData()
    },
    handleTabChange() {
      if (this.activeTab === 'realtime') {
        this.getRealtimeData()
        this.startRealtimePolling()
      } else {
        this.stopRealtimePolling()
      }
      this.$nextTick(() => {
        this.handleResize()
      })
    },
    getRealtimeData() {
      let stationCheck, orderCheck, engineTypeCheck
      this.stationValues.length > 0 ? stationCheck = 1 : stationCheck = 0
      this.orderNumberValue ? orderCheck = 1 : orderCheck = 0
      this.engineTypeValue ? engineTypeCheck = 1 : engineTypeCheck = 0
      this.realtimeLoading = true
      const param = []
      param[0] = ['开始时间', getNowShotTime()]
      param[1] = ['结束时间', getNowShotTime()]
      param[2] = ['工位_check', stationCheck]
      param[3] = ['工位列表', this.stationValues.join(',')]
      param[4] = ['订单号_check', orderCheck]
      param[5] = ['订单号', this.orderNumberValue]
      param[6] = ['产品型号代码_check', engineTypeCheck]
      param[7] = ['产品型号代码', this.engineTypeValue]
      const Data = this.CreateData('11', '质量数据查询_测量数据发动机在线状态_工位JPH_实时', param)
      this.ExecDatabase(Data).then(response => {
        this.realtimeSource = response.data || []
        this.renderRealtimeChart()
        this.realtimeLoading = false
      }).catch(() => {
        this.realtimeSource = []
        this.renderRealtimeChart()
        this.realtimeLoading = false
      })
    },
    startRealtimePolling() {
      this.stopRealtimePolling()
      this.realtimeTimer = setInterval(() => {
        if (this.activeTab === 'realtime') {
          this.getRealtimeData()
        }
      }, 30000)
    },
    stopRealtimePolling() {
      if (this.realtimeTimer) {
        clearInterval(this.realtimeTimer)
        this.realtimeTimer = null
      }
    },
    getHistoryData() {
      let stationCheck, orderCheck, engineTypeCheck
      this.stationValues.length > 0 ? stationCheck = 1 : stationCheck = 0
      this.orderNumberValue ? orderCheck = 1 : orderCheck = 0
      this.engineTypeValue ? engineTypeCheck = 1 : engineTypeCheck = 0
      this.historyLoading = true
      const param = []
      param[0] = ['开始时间', this.dateTime[0]]
      param[1] = ['结束时间', this.dateTime[1]]
      param[2] = ['工位_check', stationCheck]
      param[3] = ['工位列表', this.stationValues.join(',')]
      param[4] = ['订单号_check', orderCheck]
      param[5] = ['订单号', this.orderNumberValue]
      param[6] = ['产品型号代码_check', engineTypeCheck]
      param[7] = ['产品型号代码', this.engineTypeValue]
      const Data = this.CreateData('11', '质量数据查询_测量数据发动机在线状态_工位JPH_历史', param)
      this.ExecDatabase(Data).then(response => {
        this.historySource = response.data || []
        this.historyTableData = this.historySource
        this.renderHistoryChart()
        this.historyLoading = false
      }).catch(() => {
        this.historySource = []
        this.historyTableData = []
        this.renderHistoryChart()
        this.historyLoading = false
      })
    },
    initRealtimeChart() {
      const dom = document.getElementById('stationJphRealtimeChart')
      if (!dom) {
        return
      }
      this.realtimeChart = this.$echarts.getInstanceByDom(dom)
      if (!this.realtimeChart) {
        this.realtimeChart = this.$echarts.init(dom)
      }
      this.renderRealtimeChart()
    },
    initHistoryChart() {
      const dom = document.getElementById('stationJphHistoryChart')
      if (!dom) {
        return
      }
      this.historyChart = this.$echarts.getInstanceByDom(dom)
      if (!this.historyChart) {
        this.historyChart = this.$echarts.init(dom)
      }
      this.renderHistoryChart()
    },
    renderRealtimeChart() {
      if (!this.realtimeChart) {
        this.initRealtimeChart()
      }
      if (!this.realtimeChart) {
        return
      }
      const xAxis = this.realtimeSource.map(item => item.小时段)
      const series = this.realtimeSource.map(item => Number(item.产量 || 0))
      this.realtimeChart.setOption({
        title: {
          text: this.$t('stationJph.realtimeChartTitle'),
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '12%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              title: this.$t('stationJph.saveAsImage'),
              type: 'png'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: xAxis,
          axisLabel: {
            interval: 0,
            rotate: 35
          }
        },
        yAxis: {
          type: 'value',
          name: this.$t('stationJph.outputQty')
        },
        series: [{
          name: this.$t('stationJph.outputQty'),
          type: 'bar',
          barMaxWidth: 28,
          data: series,
          itemStyle: {
            color: '#409EFF'
          },
          label: {
            show: true,
            position: 'top',
            color: '#333'
          }
        }]
      }, true)
    },
    renderHistoryChart() {
      if (!this.historyChart) {
        this.initHistoryChart()
      }
      if (!this.historyChart) {
        return
      }
      const xAxis = this.historySource.map(item => `${item.日期} ${item.小时段}`)
      const series = this.historySource.map(item => Number(item.产量 || 0))
      this.historyChart.setOption({
        title: {
          text: this.$t('stationJph.historyChartTitle'),
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '14%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              title: this.$t('stationJph.saveAsImage'),
              type: 'png'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: xAxis,
          axisLabel: {
            interval: 0,
            rotate: 40
          }
        },
        yAxis: {
          type: 'value',
          name: this.$t('stationJph.outputQty')
        },
        series: [{
          name: this.$t('stationJph.outputQty'),
          type: 'bar',
          barMaxWidth: 28,
          data: series,
          itemStyle: {
            color: '#67C23A'
          }
        }]
      }, true)
    },
    handleResize() {
      if (this.realtimeChart) {
        this.realtimeChart.resize()
      }
      if (this.historyChart) {
        this.historyChart.resize()
      }
    },
    exportExcel() {
      if (this.historyTableData.length === 0) {
        this.$message.warning(this.$t('stationJph.noData'))
        return
      }
      let stationCheck, orderCheck, engineTypeCheck
      this.stationValues.length > 0 ? stationCheck = 1 : stationCheck = 0
      this.orderNumberValue ? orderCheck = 1 : orderCheck = 0
      this.engineTypeValue ? engineTypeCheck = 1 : engineTypeCheck = 0

      const param = []
      param[0] = ['开始时间', this.dateTime[0]]
      param[1] = ['结束时间', this.dateTime[1]]
      param[2] = ['工位_check', stationCheck]
      param[3] = ['工位列表', this.stationValues.join(',')]
      param[4] = ['订单号_check', orderCheck]
      param[5] = ['订单号', this.orderNumberValue]
      param[6] = ['产品型号代码_check', engineTypeCheck]
      param[7] = ['产品型号代码', this.engineTypeValue]
      const Data = this.CreateData('2001', '质量数据查询_测量数据发动机在线状态_工位JPH_历史_导出', param)
      this.exportExcel_NPOI(Data)
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

.toolbarRow {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px 0;
  margin-bottom: 12px;
}

.chartCard {
  width: 100%;
  margin: 0 0 12px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fff;
}

.chartDom {
  width: 100%;
  height: 360px;
}
</style>
