<template>
  <div class="app-container product-pass-rate-page">
    <el-card>
      <div class="search-container" @keyup.enter="searchTable">
        <span class="show-text">关闭日期:</span>
        <el-date-picker
          v-model="searchForm.closeDateStart"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          clearable
          size="small"
          style="width: 140px; margin-right: 6px"
        />
        <span class="date-separator">至</span>
        <el-date-picker
          v-model="searchForm.closeDateEnd"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          clearable
          size="small"
          style="width: 140px; margin-right: 10px"
        />
        <span class="show-text">生产订单:</span>
        <el-input
          v-model="searchForm.orderNo"
          clearable
          placeholder="生产订单"
          size="small"
          style="width: 120px; margin-right: 10px"
        />
        <span class="show-text">物料编码:</span>
        <el-input
          v-model="searchForm.itemCode"
          clearable
          placeholder="物料编码"
          size="small"
          style="width: 170px; margin-right: 10px"
        />
        <span class="show-text">物料名称:</span>
        <el-input
          v-model="searchForm.itemName"
          clearable
          placeholder="物料名称"
          size="small"
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">工序:</span>
        <el-input
          v-model="searchForm.process"
          clearable
          placeholder="工序"
          size="small"
          style="width: 110px; margin-right: 10px"
        />
        <span class="show-text">工位:</span>
        <el-input
          v-model="searchForm.station"
          clearable
          placeholder="工位"
          size="small"
          style="width: 110px; margin-right: 10px"
        />
        <span class="show-text">合格状态:</span>
        <el-select
          v-model="searchForm.passStatus"
          clearable
          placeholder="合格状态"
          size="small"
          style="width: 110px; margin-right: 10px"
        >
          <el-option label="不合格" value="不合格" />
          <el-option label="合格" value="合格" />
          <el-option label="全部" value="全部" />
        </el-select>
        <el-button
          :disabled="loading"
          icon="el-icon-search"
          plain
          size="small"
          type="primary"
          @click="searchTable"
        >查询</el-button>
        <el-button
          :disabled="loading || tableData.length === 0"
          icon="el-icon-download"
          plain
          size="small"
          type="success"
          @click="exportToExcel"
        >导出</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        element-loading-background="rgba(0, 0, 0, 0.2)"
        element-loading-spinner="el-icon-loading"
        height="76vh"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 12px"
        tooltip-effect="dark"
      >
        <el-table-column type="expand" width="44">
          <template slot-scope="scope">
            <div class="detail-wrapper">
              <el-table
                :data="scope.row.children"
                border
                class="detail-table"
                empty-text="无二级数据"
                size="mini"
              >
                <el-table-column align="center" label="工序" prop="工序" min-width="110" show-overflow-tooltip />
                <el-table-column align="center" label="工序号" prop="工序号" width="80" />
                <el-table-column align="center" label="工位（指派对象）" prop="工位" min-width="130" show-overflow-tooltip />
                <el-table-column align="right" label="完工数量" prop="完成数量" width="100" />
                <el-table-column align="right" label="不良数量" prop="不良数量" width="100" />
                <el-table-column align="center" label="合格率" width="100">
                  <template slot-scope="childScope">
                    <span :class="getRateClass(childScope.row.合格率)">
                      {{ formatRate(childScope.row.合格率) }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column align="left" label="检验说明" prop="检测说明" min-width="220" show-overflow-tooltip />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed label="序号" type="index" width="50" />
        <el-table-column align="center" label="关闭日期" width="120">
          <template slot-scope="scope">{{ formatDate(scope.row.关闭日期) }}</template>
        </el-table-column>
        <el-table-column align="center" label="生产订单号" prop="生产订单号" width="100" />
        <el-table-column align="left" label="物料名称" prop="物料名称" min-width="220" show-overflow-tooltip />
        <el-table-column align="left" label="物料编码" prop="物料编码" min-width="190" show-overflow-tooltip />
        <el-table-column align="right" label="计划数量" prop="计划数量" width="100" />
        <el-table-column align="right" label="完成数量" prop="完成数量" width="100" />
        <el-table-column align="right" label="不良数量" prop="不良数量" width="100" />
        <el-table-column align="center" label="合格率" width="100">
          <template slot-scope="scope">
            <span :class="getRateClass(scope.row.合格率)">
              {{ formatRate(scope.row.合格率) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'ProductPassRateWorkstation',
  data() {
    return {
      loading: false,
      searchForm: {
        closeDateStart: this.getDefaultDateStart(),
        closeDateEnd: this.getDefaultDateEnd(),
        orderNo: '',
        itemCode: '',
        itemName: '',
        process: '',
        station: '',
        passStatus: '不合格'
      },
      tableData: []
    }
  },
  methods: {
    async searchTable() {
      this.loading = true
      this.tableData = []

      const param = []
      param.push(['生产订单号', this.searchForm.orderNo || ''])
      param.push(['物料编码', this.searchForm.itemCode || ''])
      param.push(['物料名称', this.searchForm.itemName || ''])
      param.push(['关闭日期_Start', this.searchForm.closeDateStart || ''])
      param.push(['关闭日期_End', this.searchForm.closeDateEnd || ''])
      param.push(['工序', this.searchForm.process || ''])
      param.push(['工位', this.searchForm.station || ''])
      param.push(['合格状态', this.searchForm.passStatus || ''])

      const data = this.CreateData('11', '生产管理_产品合格率工位_查询', param)
      try {
        const response = await this.ExecDatabase(data)
        const list = response.data || []
        this.tableData = list.map(row => ({
          ...row,
          children: this.parseDetails(row.明细JSON)
        }))
      } catch (error) {
        console.error('产品合格率查询失败:', error)
        this.$message.error('查询失败')
      } finally {
        this.loading = false
      }
    },
    exportToExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('没有数据可导出')
        return
      }

      try {
        const columns = this.getExportColumns()
        const exportRows = [
          columns.map(column => column.label),
          ...this.buildExportRows(columns)
        ]
        const wb = XLSX.utils.book_new()
        const ws = XLSX.utils.aoa_to_sheet(exportRows)
        ws['!cols'] = columns.map(column => ({ wch: column.width }))
        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('导出失败')
      }
    },
    getExportColumns() {
      return [
        { label: '层级', prop: '层级', width: 10 },
        { label: '关闭日期', prop: '关闭日期', width: 12 },
        { label: '生产订单号', prop: '生产订单号', width: 14 },
        { label: '物料名称', prop: '物料名称', width: 32 },
        { label: '物料编码', prop: '物料编码', width: 24 },
        { label: '计划数量', prop: '计划数量', width: 12 },
        { label: '完成数量', prop: '完成数量', width: 12 },
        { label: '不良数量', prop: '不良数量', width: 12 },
        { label: '合格率', prop: '合格率', width: 12 },
        { label: '工序', prop: '工序', width: 16 },
        { label: '工序号', prop: '工序号', width: 10 },
        { label: '工位（指派对象）', prop: '工位', width: 18 },
        { label: '明细完工数量', prop: '明细完成数量', width: 14 },
        { label: '明细不良数量', prop: '明细不良数量', width: 14 },
        { label: '明细合格率', prop: '明细合格率', width: 12 },
        { label: '检验说明', prop: '检测说明', width: 32 }
      ]
    },
    buildExportRows(columns) {
      const rows = []
      this.tableData.forEach(row => {
        rows.push(this.formatExportRow(this.buildMainExportRow(row), columns))
        if (Array.isArray(row.children)) {
          row.children.forEach(child => {
            rows.push(this.formatExportRow(this.buildDetailExportRow(row, child), columns))
          })
        }
      })
      return rows
    },
    buildMainExportRow(row) {
      return {
        层级: '主表',
        关闭日期: this.formatDate(row.关闭日期),
        生产订单号: row.生产订单号,
        物料名称: row.物料名称,
        物料编码: row.物料编码,
        计划数量: row.计划数量,
        完成数量: row.完成数量,
        不良数量: row.不良数量,
        合格率: this.formatRate(row.合格率)
      }
    },
    buildDetailExportRow(row, child) {
      return {
        层级: '明细',
        关闭日期: this.formatDate(row.关闭日期),
        生产订单号: row.生产订单号,
        物料名称: row.物料名称,
        物料编码: row.物料编码,
        工序: child.工序,
        工序号: child.工序号,
        工位: child.工位,
        明细完成数量: child.完成数量,
        明细不良数量: child.不良数量,
        明细合格率: this.formatRate(child.合格率),
        检测说明: child.检测说明
      }
    },
    formatExportRow(row, columns) {
      return columns.map(column => this.normalizeExportValue(row[column.prop]))
    },
    normalizeExportValue(value) {
      if (value === null || value === undefined) return ''
      return value
    },
    parseDetails(value) {
      if (!value) return []
      try {
        const details = JSON.parse(value)
        return Array.isArray(details) ? details : []
      } catch (error) {
        console.error('产品合格率明细解析失败:', error)
        return []
      }
    },
    getDefaultDateStart() {
      const start = new Date()
      start.setDate(start.getDate() - 30)
      return this.formatPickerDate(start)
    },
    getDefaultDateEnd() {
      return this.formatPickerDate(new Date())
    },
    formatPickerDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    formatDateForFileName(date) {
      const pad = value => String(value).padStart(2, '0')
      return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
    },
    formatDate(value) {
      if (!value) return ''
      return String(value).split('T')[0].split(' ')[0]
    },
    formatRate(value) {
      if (value === null || value === undefined || value === '') return ''
      const numberValue = Number(value)
      if (Number.isNaN(numberValue)) return ''
      return `${numberValue.toFixed(2)}%`
    },
    getRateClass(value) {
      const numberValue = Number(value)
      if (Number.isNaN(numberValue)) return ''
      if (numberValue >= 100) return 'rate-good'
      if (numberValue >= 90) return 'rate-warning'
      return 'rate-danger'
    }
  }
}
</script>

<style scoped>
.product-pass-rate-page {
  padding: 12px;
}

.search-container {
  line-height: 32px;
}

.show-text {
  margin-right: 5px;
}

.date-separator {
  margin-right: 6px;
  color: #606266;
}

.detail-wrapper {
  padding: 8px 28px 10px 58px;
  background: #f7fbff;
}

.detail-table {
  width: 100%;
}

.rate-good {
  color: #67c23a;
  font-weight: 600;
}

.rate-warning {
  color: #409eff;
  font-weight: 600;
}

.rate-danger {
  color: #f56c6c;
  font-weight: 600;
}
</style>
