<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">工位号：</span>
        <el-select v-model="stationNumberValue" placeholder="请选择工位号" filterable clearable size="small"
          style="width:240px">
          <el-option v-for="item in stationNumber" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <span style="margin-left: 10px">是否结束：</span>
        <el-select v-model="isEndedValue" placeholder="请选择" clearable size="small" style="width:120px">
          <el-option v-for="item in isEndedOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <span style="margin-left: 10px">时间：</span>
        <el-date-picker :clearable="false" v-model="dateTime" size="small" type="daterange" align="center"
          style="width: 280px;" value-format="yyyy-MM-dd" format="yyyy-MM-dd" range-separator="～"
          start-placeholder="开始日期" end-placeholder="结束日期" />
        <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 10px"
          @click="pageSize = 100; pageCurrent = 1; searchTable()">查询</el-button>
        <el-button :loading="exportLoading" :disabled="exportLoading" type="info" size="small" icon="el-icon-download"
          style="margin-left: 10px" @click="exportExcel">Excel</el-button>
        <el-button type="danger" plain size="small" icon="el-icon-delete" style="margin-left: 10px"
          :loading="deleteLoading" @click="handleBatchDelete">删除</el-button>
      </div>
      <el-table ref="alarmTable" v-loading="loading" :data="tableData"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }" highlight-current-row border size="mini"
        height="620px" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column width="60" label="序号" type="index" align="center" />
        <el-table-column label="工位号" width="280" align="center">
          <template slot-scope="scope">
            {{ getStationLabel(scope.row.工位号) }}
          </template>
        </el-table-column>
        <el-table-column label="开始时间" width="180" align="center">
          <template slot-scope="scope">
            {{ scope.row.开始时间 }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180" align="center">
          <template slot-scope="scope">
            {{ scope.row.结束时间 || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="持续时间(s)" width="120" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.结束时间">{{ scope.row.持续时间 }}</span>
            <el-tag v-else type="warning" size="mini">进行中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.结束时间" type="success" size="mini">已结束</el-tag>
            <el-tag v-else type="danger" size="mini">未结束</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination v-if="!loading" :current-page="pageCurrent" :page-sizes="[50, 100, 200, 500, 1000]"
          :page-size="pageSize" :total="total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      tableData: [],
      stationNumber: [],
      stationNumberValue: '',
      isEndedValue: '',
      isEndedOptions: [
        { label: '全部', value: '' },
        { label: '未结束', value: '1' }
      ],
      dateTime: [],
      total: 0,
      pageSize: 100,
      pageCurrent: 1,
      selectedRows: [],
      deleteLoading: false,
      exportLoading: false
    }
  },
  created() {
    // 默认查询今天
    const today = this.formatDate(new Date())
    this.dateTime = [today, today]
    this.getStationNumber()
    this.searchTable()
  },
  methods: {
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    getStationNumber() {
      this.stationNumber = []
      const param = []
      const Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (const item of response.data) {
          this.stationNumber.push({
            label: `【${item.工位号}】${item.工位名称 || ''}`,
            value: item.工位号
          })
        }
      })
    },
    getStationLabel(stationCode) {
      const found = this.stationNumber.find(item => item.value === stationCode)
      return found ? found.label : stationCode
    },
    getQueryParam(pageCurrent, pageSize) {
      if (!this.dateTime || this.dateTime.length !== 2) {
        this.$message.warning('请选择查询时间范围！')
        return null
      }
      const param = []
      param.push(['工位号', this.stationNumberValue || ''])
      param.push(['是否结束', this.isEndedValue || ''])
      param.push(['开始时间', this.dateTime[0] + ' 00:00:00'])
      param.push(['结束时间', this.dateTime[1] + ' 23:59:59'])
      param.push(['PageCurrent', pageCurrent])
      param.push(['PageSize', pageSize])
      param.push(['PageCount', '0', 'int', '1'])
      param.push(['ItemCount', '0', 'int', '1'])
      return param
    },
    searchTable() {
      const param = this.getQueryParam(this.pageCurrent, this.pageSize)
      if (!param) {
        return
      }
      this.loading = true
      this.tableData = []
      const Data = this.CreateData('11', '报警工位记录表_分页_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result && response.data.result.length > 0) {
          this.tableData = response.data.result
        }
        this.total = parseInt(response.data.output[0].ItemCount) || 0
        this.selectedRows = []
        this.$nextTick(() => {
          if (this.$refs.alarmTable) {
            this.$refs.alarmTable.clearSelection()
          }
        })
        this.loading = false
      }).catch(err => {
        this.loading = false
        this.$message.error('查询失败，请稍后重试！')
        console.error('searchTable error:', err)
      })
    },
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('暂无数据')
        return
      }
      const param = this.getQueryParam(1, 99999999)
      if (!param) {
        return
      }
      const exportData = JSON.parse(this.CreateData('2005', '报警工位记录表_分页_查询', param))
      exportData.exportFileName = '工位报警记录'
      exportData.exportColumns = '工位号,开始时间,结束时间,持续时间'
      const Data = JSON.stringify(exportData)
      this.runExcelExport(Data, 'exportLoading')
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows || []
    },
    getRowId(row) {
      return row.ID || row.Id || row.id || null
    },
    handleBatchDelete() {
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message.warning('请先勾选要删除的数据')
        return
      }
      const idList = this.selectedRows.map(item => this.getRowId(item)).filter(item => item !== null && item !== undefined)
      if (idList.length === 0) {
        this.$message.error('未找到可删除数据的ID')
        return
      }
      this.$confirm(`确定删除已勾选的 ${idList.length} 条数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteLoading = true
        const tasks = idList.map(id => {
          const param = []
          param.push(['ID', id])
          const Data = this.CreateData('12', 'MES_设备停机时间_删除', param)
          return this.ExecDatabase(Data).then(() => ({ success: true })).catch(() => ({ success: false }))
        })
        Promise.all(tasks).then(results => {
          const failCount = results.filter(item => !item.success).length
          if (failCount === 0) {
            this.$message.success(`删除成功，共 ${idList.length} 条`)
          } else if (failCount === idList.length) {
            this.$message.error('删除失败，请重试')
          } else {
            this.$message.warning(`部分删除成功，成功 ${idList.length - failCount} 条，失败 ${failCount} 条`)
          }
          this.searchTable()
        }).finally(() => {
          this.deleteLoading = false
        })
      }).catch(() => { })
    },
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>

<style scoped>
.topDiv {
  margin-bottom: 10px;
}
</style>
