<template>
  <el-card class="topCard">
    <el-row class="toolbarRow">
      <span class="promptText">{{ $t('offLinePartCount.productionTimeLabel') }}</span>
      <el-date-picker
        v-model="dateTime"
        :clearable="false"
        align="center"
        :end-placeholder="$t('offLinePartCount.endDate')"
        format="yyyy-MM-dd"
        :range-separator="$t('offLinePartCount.dateRangeSeparator')"
        size="small"
        :start-placeholder="$t('offLinePartCount.startDate')"
        style="width: 240px"
        type="daterange"
        value-format="yyyy-MM-dd"
      />
      <span style="margin-left: 10px">{{ $t('offLinePartCount.orderNumberLabel') }}</span>
      <el-input
        v-model="orderNumberValue"
        :placeholder="$t('offLinePartCount.orderNumberPlaceholder')"
        clearable
        size="small"
        style="width: 150px"
      />
      <span class="promptText">{{ $t('offLinePartCount.productModelLabel') }}</span>
      <el-select
        v-model="engineTypeValue"
        :placeholder="$t('offLinePartCount.selectProductModel')"
        filterable
        clearable
        size="small"
        style="width: 150px"
      >
        <el-option
          v-for="item in engineType"
          :key="item.value"
          :label="item.label"
          :value="item.value"
          size="mini"
        />
      </el-select>
      <span class="promptText">{{ $t('offLinePartCount.trendGranularityLabel') }}</span>
      <el-radio-group v-model="trendMode" size="small">
        <el-radio-button label="day">{{ $t('offLinePartCount.byDay') }}</el-radio-button>
        <el-radio-button label="hour">{{ $t('offLinePartCount.byHour') }}</el-radio-button>
      </el-radio-group>
      <el-button
        class="functionButton"
        type="primary"
        size="small"
        icon="el-icon-search"
        plain
        @click="searchTable(true)"
      >{{ $t('offLinePartCount.search') }}</el-button>
      <el-button
        type="info"
        style="margin-left: 0"
        icon="el-icon-document"
        size="small"
        plain
        @click="exportExcel()"
      >{{ $t('offLinePartCount.export') }}</el-button>
      <span v-show="isExporting" style="color: #16a188">{{ $t('offLinePartCount.exporting') }}</span>
    </el-row>

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

    <el-row>
      <div>
        <el-table
          v-loading="loading"
          :data="tableData"
          highlight-current-row
          border
          stripe
          class="tableCustomization"
          height="600px"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            align="center"
            :label="$t('offLinePartCount.sequence')"
            width="90px"
          />
          <el-table-column width="200px" :label="$t('offLinePartCount.orderNumber')" align="center">
            <template slot-scope="scope">
              {{ scope.row.订单号 }}
            </template>
          </el-table-column>
          <el-table-column min-width="240px" :label="$t('offLinePartCount.productNumber')" align="center">
            <template slot-scope="scope">
              {{ scope.row.发动机号 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('offLinePartCount.productModel')" width="200px" align="center">
            <template slot-scope="scope">
              {{ scope.row.机型 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('offLinePartCount.offlineTime')" width="250px" align="center">
            <template slot-scope="scope">
              {{ scope.row.离开时间 }}
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-top: 10px">
          <el-pagination
            :current-page="pageCurrent"
            :page-sizes="[15, 30, 40]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChanges"
            @current-change="handleCurrentChanges"
          />
        </div>
      </div>
    </el-row>
  </el-card>
</template>

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

export default {
  data() {
    return {
      isExporting: false,
      dateTime: [],
      orderNumberValue: '',
      stationOptions: [],
      station: [],
      engineType: [],
      stationString: '',
      engineTypeValue: '',
      engineNumber: '',
      enginePartNumber: '',
      tableData: [],
      loading: false,
      pageCurrent: 1,
      pageSize: 15,
      total: 0,
      trendMode: 'day',
      trendChart: null,
      trendLoading: false,
      trendXAxis: [],
      trendSeries: []
    }
  },
  created() {
    this.dateTime = [getNowShotTime(), getNowShotTime()]
    this.getEngineType()
  },
  mounted() {
    this.$nextTick(() => {
      this.initTrendChart()
      this.searchTable(true)
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.trendChart) {
      this.trendChart.dispose()
      this.trendChart = null
    }
  },
  methods: {
    getStationNumber() {
      this.stationNumber = []
      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.stationNumber.push({
            label: `【${response.data[i].工位号}】${response.data[i].工位名称}`,
            value: response.data[i].工位号
          })
        }
      })
    },
    getEngineType() {
      this.engineType = []
      var param = []
      var Data = this.CreateData('11', 'MES_基本变量_机型代码_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.engineType.push({
            label: response.data[i].发动机型号 + '-' + response.data[i].标识字符,
            value: response.data[i].发动机机型标志
          })
        }
      })
    },
    buildSearchParams() {
      let engineTypeValueCheck, orderNumberValueCheck
      this.engineTypeValue ? engineTypeValueCheck = 1 : engineTypeValueCheck = 0
      this.orderNumberValue ? orderNumberValueCheck = 1 : orderNumberValueCheck = 0
      return {
        engineTypeValueCheck,
        orderNumberValueCheck
      }
    },
    searchTable(needRefreshChart) {
      const checks = this.buildSearchParams()
      if (needRefreshChart) {
        this.pageCurrent = 1
      }
      this.loading = true
      const param = []
      param[0] = ['开始时间', this.dateTime[0]]
      param[1] = ['结束时间', this.dateTime[1]]
      param[2] = ['订单号_check', checks.orderNumberValueCheck]
      param[3] = ['订单号', this.orderNumberValue]
      param[4] = ['产品型号代码_check', checks.engineTypeValueCheck]
      param[5] = ['产品型号代码', this.engineTypeValue]
      param[6] = ['PageCurrent', this.pageCurrent]
      param[7] = ['PageSize', this.pageSize]
      param[8] = ['PageCount', '1111', 'int', '1']
      param[9] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', '质量数据查询_测量数据发动机在线状态_下线统计', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data.result || []
        this.total = parseInt(response.data.output[0].ItemCount)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })

      if (needRefreshChart) {
        this.getTrendData()
      }
    },
    getTrendData() {
      const checks = this.buildSearchParams()
      this.trendLoading = true
      const param = []
      param[0] = ['开始时间', this.dateTime[0]]
      param[1] = ['结束时间', this.dateTime[1]]
      param[2] = ['订单号_check', checks.orderNumberValueCheck]
      param[3] = ['订单号', this.orderNumberValue]
      param[4] = ['产品型号代码_check', checks.engineTypeValueCheck]
      param[5] = ['产品型号代码', this.engineTypeValue]
      param[6] = ['聚合类型', this.trendMode]
      const Data = this.CreateData('11', '质量数据查询_测量数据发动机在线状态_下线统计_趋势分析', param)
      this.ExecDatabase(Data).then(response => {
        const source = response.data || []
        this.trendXAxis = source.map(item => item.时间段)
        this.trendSeries = source.map(item => Number(item.下线数量 || 0))
        this.renderTrendChart()
        this.trendLoading = false
      }).catch(() => {
        this.trendXAxis = []
        this.trendSeries = []
        this.renderTrendChart()
        this.trendLoading = false
      })
    },
    initTrendChart() {
      const chartDom = document.getElementById('offlineTrendChart')
      if (!chartDom) {
        return
      }
      this.trendChart = this.$echarts.getInstanceByDom(chartDom)
      if (!this.trendChart) {
        this.trendChart = this.$echarts.init(chartDom)
      }
      this.renderTrendChart()
    },
    renderTrendChart() {
      if (!this.trendChart) {
        this.initTrendChart()
      }
      if (!this.trendChart) {
        return
      }
      this.trendChart.setOption({
        title: {
          text: this.$t('offLinePartCount.trendTitle'),
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '4%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {
              title: this.$t('offLinePartCount.saveAsImage'),
              type: 'png'
            }
          }
        },
        xAxis: {
          type: 'category',
          name: this.trendMode === 'day' ? this.$t('offLinePartCount.dateAxis') : this.$t('offLinePartCount.hourAxis'),
          data: this.trendXAxis,
          axisLabel: {
            interval: 0,
            rotate: this.trendMode === 'hour' ? 45 : 25
          }
        },
        yAxis: {
          type: 'value',
          name: this.$t('offLinePartCount.offlineQuantityAxis'),
          minInterval: 1
        },
        series: [{
          name: this.$t('offLinePartCount.offlineQuantitySeries'),
          type: 'bar',
          barMaxWidth: 40,
          data: this.trendSeries,
          itemStyle: {
            color: '#409EFF'
          },
          label: {
            show: true,
            position: 'top',
            color: '#333'
          }
        }]
      }, true)
    },
    handleResize() {
      if (this.trendChart) {
        this.trendChart.resize()
      }
    },
    exportExcel() {
      if (this.tableData.length !== 0) {
        let dateTimeCheck, enginePartNumberCheck, engineNumberCheck
        this.dateTime && this.dateTime.length === 2 ? dateTimeCheck = 1 : dateTimeCheck = 0
        if (dateTimeCheck === 0) {
          this.$message({
            message: this.$t('offLinePartCount.selectDateRange'),
            type: 'error'
          })
          return
        }
        this.enginePartNumber ? enginePartNumberCheck = 1 : enginePartNumberCheck = 0
        this.engineNumber ? engineNumberCheck = 1 : engineNumberCheck = 0
        this.isExporting = true
        const param = []
        param[0] = ['timeFrame_check', dateTimeCheck]
        param[1] = ['QueryStartTime', this.dateTime[0]]
        param[2] = ['QueryEndTime', this.dateTime[1]]
        param[3] = ['engineNumber_check', engineNumberCheck]
        param[4] = ['engineNumber', this.engineNumber]
        param[5] = ['enginePartNumber_check', enginePartNumberCheck]
        param[6] = ['enginePartNumber', this.enginePartNumber]
        const Data = this.CreateData('2003', 'SP_His_OffLinePartCount_ExportExcel', param)
        const blob = 'data:image/gif;base64,R0lGODlhCQACAIAAAMzMzP///yH5BAEAAAEALAAAAAAJAAIAAAIEjI9pUAA7'
        this.exportExcel_NPOI(Data, blob).then(() => {
          this.isExporting = false
        }).catch(() => {
          this.isExporting = false
        })
      } else {
        this.$message.warning(this.$t('offLinePartCount.noData'))
      }
    },
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable(false)
    },
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable(false)
    }
  },
  watch: {
    '$i18n.locale'() {
      this.renderTrendChart()
    },
    trendMode() {
      this.getTrendData()
    }
  }
}
</script>

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

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

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

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