<template>
  <div class="settlement-workhours">
    <el-card>
      <div class="search-container">
        <span class="show-text">生产订单号:</span>
        <el-input v-model="searchForm.orderNo" placeholder="请输入生产订单号" clearable style="width: 140px; margin-right: 10px" />
        <span class="show-text">物料编码:</span>
        <el-input v-model="searchForm.productCode" placeholder="请输入物料编码" clearable style="width: 160px; margin-right: 10px" />
        <span class="show-text">工位:</span>
        <el-input v-model="searchForm.station" placeholder="请输入工位" clearable style="width: 120px; margin-right: 10px" />
        <span class="show-text">数据条数:</span>
        <el-input v-model="searchForm.datanum" placeholder="数据条数" clearable style="width: 100px; margin-right: 10px" />
        <span class="show-text">开始日期:</span>
        <el-date-picker
          v-model="searchForm.startDate"
          type="date"
          placeholder="选择开始日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 150px; margin-right: 10px"
        />
        <span class="show-text">结束日期:</span>
        <el-date-picker
          v-model="searchForm.endDate"
          type="date"
          placeholder="选择结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 150px; margin-right: 10px"
        />

        <el-button :loading="loading" icon="el-icon-search" plain type="primary" @click="handleSearch">查询</el-button>
        <el-button :disabled="loading || tableData.length === 0" icon="el-icon-download" plain type="success" @click="exportToExcel">导出</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        :height="tableHeight"
        border
        size="mini"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        class="custom-tree-table"
        :row-class-name="tableRowClassName"
        style="width: 100%"
        @expand-change="handleExpandChange"
      >
        <el-table-column prop="taskDescription" label="任务描述" min-width="380" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.level === 1 }">{{ scope.row.taskDescription || '' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="productionOrderNo" label="生产订单号" width="130" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.productionOrderNo || '' }}
          </template>
        </el-table-column>

        <el-table-column prop="station" label="工位" width="110" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.station || '' }}
          </template>
        </el-table-column>

        <el-table-column prop="reportWorkHours" label="报工工时" width="100" align="center">
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.reportWorkHours || '' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="auxiliaryWorkHours" label="辅助工时" width="100" align="center">
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.auxiliaryWorkHours || '' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="reportFinishQty" label="报工完成数" width="110" align="center">
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.reportFinishQty || '' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="auxiliaryFinishQty" label="辅助完成数" width="110" align="center">
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.auxiliaryFinishQty || '' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="totalWorkHours" label="合计工时" width="100" align="center">
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.level <= 2 }">{{ scope.row.totalWorkHours || '' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="clampingTime" label="装夹时间" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.clampingTime || '' }}
          </template>
        </el-table-column>

        <el-table-column prop="programTime" label="程序时间" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.programTime || '' }}
          </template>
        </el-table-column>

        <el-table-column prop="settlementReportPieceHours" label="结算报工单件工时" width="140" align="center">
          <template slot-scope="scope">
            {{ scope.row.settlementReportPieceHours || '' }}
          </template>
        </el-table-column>

        <el-table-column prop="settlementAuxiliaryPieceHours" label="结算辅助单件工时" width="140" align="center">
          <template slot-scope="scope">
            {{ scope.row.settlementAuxiliaryPieceHours || '' }}
          </template>
        </el-table-column>

        <el-table-column prop="operatorNames" label="操作人" width="180" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.operatorNames || '' }}
          </template>
        </el-table-column>
      </el-table>

      <div class="summary-footer">
        <span>报工工时：<strong>{{ totals.reportWorkHours }}</strong> 小时 | 主辅工时：<strong>{{ totals.auxiliaryWorkHours }}</strong> 小时 | 合计工时：<strong>{{ totals.totalWorkHours }}</strong> 小时</span>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'SettlementWorkhours',
  data() {
    return {
      searchForm: {
        contractNo: '',
        productCode: '',
        orderNo: '',
        station: '',
        startDate: '',
        endDate: '',
        datanum: 100
      },
      loading: false,
      tableHeight: '68vh',
      tableData: [],
      collapsedRowIds: []
    }
  },
  computed: {
    totals() {
      const totals = this.tableData.reduce((sum, row) => {
        sum.reportWorkHours += this.parseNumber(row.reportWorkHours)
        sum.auxiliaryWorkHours += this.parseNumber(row.auxiliaryWorkHours)
        sum.totalWorkHours += this.parseNumber(row.totalWorkHours)
        return sum
      }, {
        reportWorkHours: 0,
        auxiliaryWorkHours: 0,
        totalWorkHours: 0
      })

      return {
        reportWorkHours: totals.reportWorkHours.toFixed(2),
        auxiliaryWorkHours: totals.auxiliaryWorkHours.toFixed(2),
        totalWorkHours: totals.totalWorkHours.toFixed(2)
      }
    }
  },
  methods: {
    parseNumber(value) {
      const numberValue = Number(value)
      return Number.isFinite(numberValue) ? numberValue : 0
    },
    handleSearch() {
      this.loadData()
    },
    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),
          [],
          [`报工工时：${this.totals.reportWorkHours} 小时 | 主辅工时：${this.totals.auxiliaryWorkHours} 小时 | 合计工时：${this.totals.totalWorkHours} 小时`]
        ]
        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: 'taskDescription', width: 52 },
        { label: '生产订单号', prop: 'productionOrderNo', width: 14 },
        { label: '工位', prop: 'station', width: 12 },
        { label: '报工工时', prop: 'reportWorkHours', width: 12 },
        { label: '辅助工时', prop: 'auxiliaryWorkHours', width: 12 },
        { label: '报工完成数', prop: 'reportFinishQty', width: 12 },
        { label: '辅助完成数', prop: 'auxiliaryFinishQty', width: 12 },
        { label: '合计工时', prop: 'totalWorkHours', width: 12 },
        { label: '装夹时间', prop: 'clampingTime', width: 12 },
        { label: '程序时间', prop: 'programTime', width: 12 },
        { label: '结算报工单件工时', prop: 'settlementReportPieceHours', width: 18 },
        { label: '结算辅助单件工时', prop: 'settlementAuxiliaryPieceHours', width: 18 },
        { label: '操作人', prop: 'operatorNames', width: 24 }
      ]
    },
    buildExportRows(columns) {
      const rows = []
      this.tableData.forEach(row => {
        rows.push(this.formatExportRow(row, columns))
        if (Array.isArray(row.children) && this.isRowExpanded(row)) {
          row.children.forEach(child => {
            rows.push(this.formatExportRow(child, columns))
          })
        }
      })
      return rows
    },
    formatExportRow(row, columns) {
      return columns.map(column => {
        if (column.prop === 'taskDescription') {
          const indent = row.level === 2 ? '  ' : ''
          return `${indent}${row.taskDescription || ''}`
        }
        return row[column.prop] || ''
      })
    },
    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())}`
    },
    loadData() {
      this.loading = true
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['工位', this.searchForm.station || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || ''],
        ['数据条数', this.searchForm.datanum || '']
      ]
      const Data = this.CreateData('11', '生产管理_结算工时_查询', param)
      this.ExecDatabase(Data).then(res => {
        this.collapsedRowIds = []
        this.tableData = this.buildTree(res.data || [])
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    buildTree(flatData) {
      const materialMap = new Map()

      flatData.forEach((row, index) => {
        if (Number(row.Level) !== 1) return
        materialMap.set(row.materialCode, {
          id: `m-${index}`,
          level: 1,
          materialCode: row.materialCode,
          materialDesc: row.materialDesc,
          taskDescription: row.taskDescription,
          reportWorkHours: row.reportWorkHours,
          auxiliaryWorkHours: row.auxiliaryWorkHours,
          reportFinishQty: row.reportFinishQty,
          auxiliaryFinishQty: row.auxiliaryFinishQty,
          totalWorkHours: row.totalWorkHours,
          clampingTime: row.clampingTime,
          programTime: row.programTime,
          settlementReportPieceHours: row.settlementReportPieceHours,
          settlementAuxiliaryPieceHours: row.settlementAuxiliaryPieceHours,
          recordCount: row.recordCount,
          children: []
        })
      })

      flatData.forEach((row, index) => {
        if (Number(row.Level) !== 2) return
        const parent = materialMap.get(row.materialCode)
        if (!parent) return
        parent.children.push({
          id: `o-${index}`,
          level: 2,
          materialCode: row.materialCode,
          materialDesc: row.materialDesc,
          taskDescription: row.taskDescription,
          productionOrderNo: row.productionOrderNo,
          station: row.station,
          reportWorkHours: row.reportWorkHours,
          auxiliaryWorkHours: row.auxiliaryWorkHours,
          reportFinishQty: row.reportFinishQty,
          auxiliaryFinishQty: row.auxiliaryFinishQty,
          totalWorkHours: row.totalWorkHours,
          clampingTime: row.clampingTime,
          programTime: row.programTime,
          settlementReportPieceHours: row.settlementReportPieceHours,
          settlementAuxiliaryPieceHours: row.settlementAuxiliaryPieceHours,
          operatorNames: row.operatorNames,
          recordCount: row.recordCount
        })
      })

      return Array.from(materialMap.values())
    },
    tableRowClassName({ row }) {
      if (row.level === 1) return 'material-row'
      return ''
    },
    handleExpandChange(row, expanded) {
      if (row.level !== 1) return
      const isExpanded = Array.isArray(expanded)
        ? expanded.some(item => item.id === row.id)
        : expanded
      if (isExpanded) {
        this.collapsedRowIds = this.collapsedRowIds.filter(id => id !== row.id)
        return
      }
      if (!this.collapsedRowIds.includes(row.id)) {
        this.collapsedRowIds.push(row.id)
      }
    },
    isRowExpanded(row) {
      return !this.collapsedRowIds.includes(row.id)
    }
  }
}
</script>

<style scoped>
.settlement-workhours {
  padding: 10px;
}

.search-container {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.show-text {
  margin-right: 5px;
  font-size: 14px;
  color: #606266;
}

.bold-text {
  font-weight: 700;
  color: #303133;
}

::v-deep .el-table .material-row {
  background: #f5f7fa !important;
}

::v-deep .el-table .material-row:hover > td {
  background-color: #f5f7fa !important;
}

.summary-footer {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}
</style>
