<template>
  <div class="test-assembly-task">
    <el-card>
      <div class="search-container">
        <span class="show-text">任务类型:</span>
        <el-select
          v-model="taskType"
          placeholder="请选择任务类型"
          style="width: 150px; margin-right: 10px"
          @change="searchTable"
        >
          <el-option label="全部" value="全部" />
          <el-option label="阀类" value="阀类" />
          <el-option label="系统类" value="系统类" />
        </el-select>
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="productionOrder"
          placeholder="请输入生产订单"
          clearable
          style="width: 150px; margin-right: 10px"
          @keyup.enter.native="searchTable"
        />
        <span class="show-text">销售订单:</span>
        <el-input
          v-model="salesOrder"
          placeholder="请输入销售订单"
          clearable
          style="width: 150px; margin-right: 10px"
          @keyup.enter.native="searchTable"
        />
        <span class="show-text">物料名称:</span>
        <el-input
          v-model="materialName"
          placeholder="请输入物料名称"
          clearable
          style="width: 160px; margin-right: 10px"
          @keyup.enter.native="searchTable"
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="materialCode"
          placeholder="请输入物料编码"
          clearable
          style="width: 180px; margin-right: 10px"
          @keyup.enter.native="searchTable"
        />
        <el-button :disabled="loading" icon="el-icon-search" plain type="primary" @click="searchTable">查询</el-button>
        <el-button :disabled="loading" icon="el-icon-download" plain type="success" @click="exportToExcel">导出</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        :height="'72vh'"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        highlight-current-row
        :row-class-name="tableRowClassName"
        size="mini"
        style="width: 100%; margin-top: 20px"
        tooltip-effect="dark"
      >
        <el-table-column align="center" label="序号" type="index" width="60" fixed />
        <el-table-column align="center" prop="预计送检日期" label="预计送检日期" width="120" fixed show-overflow-tooltip >
          <template slot-scope="scope">
            {{ formatDate(scope.row.预计送检日期) }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="销售订单" label="销售订单" width="120" fixed show-overflow-tooltip />
        <el-table-column align="center" prop="生产订单" label="生产订单" width="100" fixed />
        <el-table-column align="center" prop="物料名称" label="物料名称" width="170" show-overflow-tooltip />
        <el-table-column align="center" prop="物料编码" label="物料编码" width="180" show-overflow-tooltip />
        <el-table-column align="center" prop="计划数量" label="计划数量" width="100" />
        <el-table-column align="center" prop="完成数量" label="完成数量" width="100" />
        <el-table-column align="center" prop="检验数量" label="检验数量" width="100" />
        <el-table-column align="center" prop="检验合格数量" label="检验合格数量" width="120" />
        <el-table-column align="center" prop="检验不合格数量" label="检验不合格数量" width="130" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'TestAssemblyTask',
  data() {
    return {
      taskType: '全部',
      productionOrder: '',
      salesOrder: '',
      materialName: '',
      materialCode: '',
      loading: false,
      tableData: []
    }
  },
  mounted() {
    this.searchTable()
  },
  methods: {
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },
    tableRowClassName({ row }) {
      return this.isInspectionUnfinished(row) ? 'inspection-unfinished-row' : ''
    },
    searchTable() {
      this.loading = true
      const param = []
      param.push(['任务类型', this.taskType])
      param.push(['生产订单', this.productionOrder])
      param.push(['销售订单', this.salesOrder])
      param.push(['物料名称', this.materialName])
      param.push(['物料编码', this.materialCode])
      const data = this.CreateData('11', '质量管理_测试装配任务_查询', param)
      this.ExecDatabase(data).then(response => {
        this.tableData = this.sortTableData(response.data || [])
      }).catch(error => {
        this.$message.error('查询失败：' + error.message)
      }).finally(() => {
        this.loading = false
      })
    },
    exportToExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('没有数据可导出')
        return
      }

      try {
        const exportData = this.tableData.map((item, index) => ({
          序号: index + 1,
          预计送检日期: this.formatDate(item['预计送检日期']),
          销售订单: item['销售订单'] || '',
          生产订单: item['生产订单'] || '',
          物料名称: item['物料名称'] || '',
          物料编码: item['物料编码'] || '',
          计划数量: item['计划数量'] || 0,
          完成数量: item['完成数量'] || 0,
          检验数量: item['检验数量'] || 0,
          检验合格数量: item['检验合格数量'] || 0,
          检验不合格数量: item['检验不合格数量'] || 0
        }))

        const wb = XLSX.utils.book_new()
        const ws = XLSX.utils.json_to_sheet(exportData)
        ws['!cols'] = [
          { wch: 8 },
          { wch: 15 },
          { wch: 15 },
          { wch: 15 },
          { wch: 24 },
          { wch: 20 },
          { wch: 12 },
          { wch: 12 },
          { wch: 12 },
          { wch: 16 },
          { wch: 18 }
        ]
        XLSX.utils.book_append_sheet(wb, ws, '测试装配任务')
        XLSX.writeFile(wb, `测试装配任务_${this.formatDateForFileName(new Date())}.xlsx`)
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    sortTableData(data) {
      return data.slice().sort((a, b) => {
        const unfinishedA = this.isInspectionUnfinished(a)
        const unfinishedB = this.isInspectionUnfinished(b)

        if (unfinishedA !== unfinishedB) {
          return unfinishedA ? -1 : 1
        }

        const timeA = this.getDateTime(a['预计送检日期'])
        const timeB = this.getDateTime(b['预计送检日期'])

        if (timeA === timeB) {
          return 0
        }
        if (timeA === Infinity) {
          return 1
        }
        if (timeB === Infinity) {
          return -1
        }
        return timeA - timeB
      })
    },
    isInspectionUnfinished(row) {
      return this.getNumber(row['完成数量']) > this.getNumber(row['检验数量'])
    },
    getNumber(value) {
      if (value === null || value === undefined || value === '') {
        return 0
      }
      const number = Number(String(value).replace(/,/g, ''))
      return Number.isNaN(number) ? 0 : number
    },
    getDateTime(value) {
      if (!value) {
        return Infinity
      }
      const time = new Date(String(value).replace(/-/g, '/')).getTime()
      return Number.isNaN(time) ? Infinity : time
    },
    formatDateForFileName(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}${month}${day}_${hours}${minutes}${seconds}`
    }
  }
}
</script>

<style scoped>
.test-assembly-task {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.show-text {
  font-size: 14px;
  margin-right: 6px;
}

::v-deep .inspection-unfinished-row > td {
  background-color: #e6a23c !important;
  color: #1f1f1f;
}
</style>
