<template>
  <div class="app-container mes-admin-page">
    <el-card class="topCard">
      <el-row class="toolbarRow">
        <span class="promptText">{{ $t('stationBeat.productionTimeLabel') }}</span>
        <el-date-picker
          v-model="dateTime"
          :clearable="false"
          align="center"
          :end-placeholder="$t('stationBeat.endDate')"
          format="yyyy-MM-dd"
          :range-separator="$t('stationBeat.dateRangeSeparator')"
          size="small"
          :start-placeholder="$t('stationBeat.startDate')"
          style="width: 240px"
          type="daterange"
          value-format="yyyy-MM-dd"
        />
        <span class="promptText" style="margin-left: 10px">{{ $t('stationBeat.stationLabel') }}</span>
        <el-select
          v-model="stationValues"
          :placeholder="$t('stationBeat.selectStation')"
          clearable
          filterable
          collapse-tags
          multiple
          size="small"
          style="width: 270px"
        >
          <el-option
            v-for="item in stationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span style="margin-left: 10px">{{ $t('stationBeat.orderNumberLabel') }}</span>
        <el-input
          v-model="orderNumberValue"
          :placeholder="$t('stationBeat.orderNumberPlaceholder')"
          clearable
          size="small"
          style="width: 150px"
        />
        <span class="promptText" style="margin-left: 10px">{{ $t('stationBeat.productModelLabel') }}</span>
        <el-select
          v-model="engineTypeValue"
          :placeholder="$t('stationBeat.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="searchTable()"
          style="margin-left: 10px"
        >{{ $t('stationBeat.search') }}</el-button>
        <el-button
          type="info"
          size="small"
          icon="el-icon-download"
          plain
          @click="exportExcel()"
        >{{ $t('stationBeat.excel') }}</el-button>
      </el-row>

      <el-row>
        <div class="chartCard">
          <div id="stationBeatChart" class="chartDom" />
        </div>
      </el-row>

      <el-row>
        <div class="tablePanel">

          <el-table
            v-loading="loading"
            :data="tableData"
            border
            stripe
            class="tableCustomization"
            height="650px"
            style="width: 100%"
          >
            <el-table-column type="index" align="center" :label="$t('stationBeat.sequence')" width="80" />
            <el-table-column prop="工位" :label="$t('stationBeat.station')" align="center" min-width="140" />
            <el-table-column prop="总平均节拍" :label="$t('stationBeat.totalAverageBeat')" align="center" min-width="140" />
            <el-table-column
              v-for="item in dynamicDateColumns"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
              align="center"
              min-width="130"
            />
          </el-table>
        </div>
      </el-row>
    </el-card>
  </div>
</template>

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

export default {
  data() {
    return {
      dateTime: [],
      stationValues: [],
      stationOptions: [],
      orderNumberValue: '',
      engineTypeValue: '',
      engineType: [],
      tableData: [],
      loading: false,
      dynamicDateColumns: [],
      isExporting: false,
      chartDom: null
    }
  },
  created() {
    this.dateTime = [getNowShotTime(), getNowShotTime()]
    this.getStationOptions()
    this.getEngineType()
    this.searchTable()
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chartDom) {
      this.chartDom.dispose()
      this.chartDom = null
    }
  },
  watch: {
    '$i18n.locale'() {
      this.renderChart()
    }
  },
  methods: {
    getStationOptions() {
      this.stationOptions = []
      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() {
      this.engineType = []
      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.发动机机型标志
        }))
      })
    },
    searchTable() {
      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.loading = 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', '质量数据查询_测量数据发动机在线状态_工位节拍统计', param)
      this.ExecDatabase(Data).then(response => {
        const source = response.data || []
        this.buildDynamicTable(source)
        this.renderChart()
        this.loading = false
      }).catch(() => {
        this.tableData = []
        this.dynamicDateColumns = []
        this.renderChart()
        this.loading = false
      })
    },
    buildDynamicTable(source) {
      const dateMap = {}
      const rowMap = {}

      source.forEach(item => {
        if (!dateMap[item.日期]) {
          dateMap[item.日期] = true
        }
        if (!rowMap[item.工位]) {
          rowMap[item.工位] = {
            工位: item.工位,
            总平均节拍: item.总平均节拍
          }
        }
        rowMap[item.工位][item.日期] = item.当日平均节拍
        rowMap[item.工位].总平均节拍 = item.总平均节拍
      })

      const dates = Object.keys(dateMap).sort()
      this.dynamicDateColumns = dates.map(date => ({
        label: date,
        prop: date
      }))

      this.tableData = Object.keys(rowMap).map(key => {
        const row = rowMap[key]
        dates.forEach(date => {
          if (typeof row[date] === 'undefined') {
            row[date] = ''
          }
        })
        return row
      })
    },
    initChart() {
      const dom = document.getElementById('stationBeatChart')
      if (!dom) {
        return
      }
      this.chartDom = this.$echarts.getInstanceByDom(dom)
      if (!this.chartDom) {
        this.chartDom = this.$echarts.init(dom)
      }
      this.renderChart()
    },
    renderChart() {
      if (!this.chartDom) {
        this.initChart()
      }
      if (!this.chartDom) {
        return
      }
      const chartData = [...this.tableData]
        .map(item => ({
          station: item.工位,
          beat: Number(item.总平均节拍 || 0)
        }))
        .sort((a, b) => b.beat - a.beat)

      this.chartDom.setOption({
        title: {
          text: this.$t('stationBeat.totalAverageBeatChartTitle'),
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '6%',
          right: '6%',
          bottom: '8%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              title: this.$t('stationBeat.saveAsImage'),
              type: 'png'
            }
          }
        },
        xAxis: {
          type: 'value',
          name: this.$t('stationBeat.totalAverageBeatAxis')
        },
        yAxis: {
          type: 'category',
          data: chartData.map(item => item.station),
          name: this.$t('stationBeat.station')
        },
        series: [{
          name: this.$t('stationBeat.totalAverageBeatSeries'),
          type: 'bar',
          data: chartData.map(item => item.beat),
          barMaxWidth: 28,
          itemStyle: {
            color: '#67C23A'
          },
          label: {
            show: true,
            position: 'right',
            color: '#333'
          }
        }]
      }, true)
    },
    handleResize() {
      if (this.chartDom) {
        this.chartDom.resize()
      }
    },
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning(this.$t('stationBeat.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

      this.isExporting = 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('2001', '质量数据查询_测量数据发动机在线状态_工位节拍统计_导出', param)
      this.exportExcel_NPOI(Data).then(() => {
        this.isExporting = false
      }).catch(() => {
        this.isExporting = false
      })
    }
  }
}
</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;
}

.panelHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.panelTitle {
  color: #203247;
  font-size: 15px;
  font-weight: 700;
}

.panelSubtitle {
  color: #6b7f93;
  font-size: 12px;
  margin-top: 3px;
}

.compactHeader {
  padding: 0 2px;
}

.tablePanel {
  width: 100%;
  padding-top: 4px;
  border-radius: 14px;
  background: linear-gradient(180deg, rgba(255,255,255,0.54) 0%, rgba(243,247,251,0.94) 100%);
}

::v-deep .toolbarRow .el-button {
  margin-bottom: 2px;
}
</style>
