<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">工位号：</span>
        <el-select v-model="stationValue" placeholder="工位号" clearable filterable size="small" style="width:240px">
          <el-option
            v-for="item in stationList"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
        <span style="margin-left: 10px">产品编号：</span>
        <el-input v-model="productNoValue" placeholder="产品编号" clearable size="small" style="width:150px" />

        <span style="margin-left: 10px">返修状态：</span>
        <el-select v-model="repairStatusValue" placeholder="返修状态" clearable size="small" style="width:120px">
          <el-option label="全部状态" value=""/>
          <el-option label="未下线" value="0"/>
          <el-option label="已下线" value="1"/>
          <el-option label="回流中" value="2"/>
          <el-option label="已完成" value="3"/>
        </el-select>

        <span style="margin-left: 10px">时间：</span>
        <el-date-picker
          :clearable="false"
          v-model="dateTime"
          size="small"
          type="daterange"
          align="center"
          style="width: 240px;"
          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: 5px" @click="pageSize=50;pageCurrent=1;searchTable()">查询</el-button>
        <!-- <el-button type="success" plain size="small" icon="el-icon-refresh" @click="resetFilters()">重置</el-button> -->
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        highlight-current-row
        border
        size="mini"
        height="620px"
        style="width: 100%">
        <el-table-column width="60" label="序号" type="index" align="center"/>
        <el-table-column label="订单号" width="120px" align="center" prop="订单号" show-overflow-tooltip/>
        <el-table-column label="产品编号" width="200px" align="center" prop="产品编号" show-overflow-tooltip/>
        <el-table-column label="产品型号" width="100px" align="center" prop="产品型号" show-overflow-tooltip/>
        <el-table-column label="不合格工位" width="100px" align="center" prop="不合格工位" show-overflow-tooltip/>
        <el-table-column label="不合格时间" width="150px" align="center" prop="不合格时间" show-overflow-tooltip/>
        <el-table-column label="返修上线口" width="100px" align="center" prop="返修上线口" show-overflow-tooltip/>
        <el-table-column label="返修上线时间" width="150px" align="center" prop="返修上线时间" show-overflow-tooltip/>
        <el-table-column label="再起始工位" width="100px" align="center" prop="再起始工位" show-overflow-tooltip/>
        <el-table-column label="再起始工位到达时间" width="150px" align="center" prop="再起始工位到达时间" show-overflow-tooltip/>
        <el-table-column label="返修描述" align="center" prop="返修描述" show-overflow-tooltip/>
        <el-table-column label="返修状态" width="100px" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.返修状态)">
              {{ getStatusText(scope.row.返修状态) }}
            </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]"
          :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: [],
      stationList: [], // 工位列表
      stationValue: '', // 选中的工位号
      productNoValue: '', // 产品编号
      repairStatusValue: '', // 返修状态
      dateTime: '', // 时间范围
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      pageCurrent: 1 // 当前页码
    }
  },
  created() {
    this.initDateTime()
    this.loadStationList()
    this.searchTable()
  },
  methods: {
    // 初始化时间范围（最近一个月）
    initDateTime() {
      const today = new Date()
      const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)

      // 格式化日期为 yyyy-MM-dd
      const formatDate = (date) => {
        const year = date.getFullYear()
        const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        return year + '-' + month + '-' + day
      }

      this.dateTime = [formatDate(thirtyDaysAgo), formatDate(today)]
    },

    // 加载工位列表
    loadStationList() {
      const param = []
      const Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data && response.data.length > 0) {
          this.stationList = response.data.map(item => ({
            label: `【${item.工位号}】${item.工位名称 || ''}`,
            value: item.工位号
          }))
        }
      }).catch(error => {
        console.error('加载工位列表失败:', error)
        this.$message.error('加载工位列表失败')
      })
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        '0': 'danger', // 未下线
        '1': 'warning', // 已下线
        '2': 'info', // 回流中
        '3': 'success' // 已完成
      }
      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '0': '未下线',
        '1': '已下线',
        '2': '回流中',
        '3': '已完成'
      }
      return statusMap[status] || '未知状态'
    },

    // 重置筛选条件
    resetFilters() {
      this.stationValue = ''
      this.productNoValue = ''
      this.repairStatusValue = ''
      this.initDateTime()
      this.pageCurrent = 1
      this.pageSize = 50
      this.searchTable()
    },

    // 查询表格数据
    searchTable() {
      this.loading = true
      this.tableData = []

      // 构建查询参数
      const param = []
      param[0] = ['工位号', this.stationValue || '']
      param[1] = ['产品编号', this.productNoValue || '']
      param[2] = ['返修状态', this.repairStatusValue || '']
      param[3] = ['开始时间', this.dateTime && this.dateTime[0] ? this.dateTime[0] + ' 00:00:00' : '']
      param[4] = ['结束时间', this.dateTime && this.dateTime[1] ? this.dateTime[1] + ' 23:59:59' : '']
      param[5] = ['PageCurrent', this.pageCurrent]
      param[6] = ['PageSize', this.pageSize]
      param[7] = ['PageCount', '1111', 'int', '1']
      param[8] = ['ItemCount', '1111', 'int', '1']

      const Data = this.CreateData('11', 'MES_工位返修记录_分页_查询', param)
      this.ExecDatabase(Data).then(response => {
        console.log('返修记录查询结果:', response)
        if (response.data && response.data.result) {
          this.tableData = response.data.result
        }
        if (response.data && response.data.output && response.data.output[0]) {
          this.total = parseInt(response.data.output[0].ItemCount) || 0
        }
        this.loading = false
      }).catch(error => {
        console.error('查询返修记录失败:', error)
        this.$message.error('查询返修记录失败')
        this.loading = false
      })
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchTable()
    }
  }
}
</script>

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

.topCard {
  margin-bottom: 20px;
}

.block {
  text-align: left;
}
</style>
