<template>
  <div class="work-hours-statistics">
    <el-card>
      <div class="search-container">
        <span class="show-text">合同号:</span>
        <el-input v-model="searchForm.contractNo" placeholder="请输入合同号" clearable style="width: 130px; margin-right: 10px" />
        <span class="show-text">产品编码:</span>
        <el-input v-model="searchForm.productCode" placeholder="请输入产品编码" clearable style="width: 150px; margin-right: 10px" />
        <span class="show-text">订单号:</span>
        <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable style="width: 100px; 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>
      </div>

      <el-tabs v-model="activeTab" type="card" class="statistics-tabs" @tab-click="handleTabChange">
        <el-tab-pane label="工序工时" name="process">
           <el-table 
            v-loading="loading"
            :data="processTableData" 
            :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%">
            
            <el-table-column prop="taskDescription" label="任务描述" width="360" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">
                  {{ scope.row.level === 1 ? scope.row.taskDescription : '' }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="dateLabel" label="日期" width="130" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 2}">
                  {{ scope.row.level === 2 ? `日期${scope.row.dateLabel || ''}` : scope.row.dateLabel || '' }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="shift" label="班次" width="100" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.shift || '' }}
              </template>
            </el-table-column>

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

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

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

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

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

            <el-table-column prop="workHours" label="工时" width="90" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level <= 2}">{{ scope.row.workHours || '' }}</span>
              </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="pieceWorkHours" label="单件工时" width="110" align="center">
              <template slot-scope="scope">
                {{ scope.row.pieceWorkHours || '' }}
              </template>
            </el-table-column>

            <el-table-column prop="processWorkHours" label="工艺工时" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.processWorkHours || '' }}
              </template>
            </el-table-column>
            
            <!-- <el-table-column prop="contractNo" label="合同号" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.contractNo : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="orderNo" label="订单号" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.orderNo : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="productCode" label="产品编码" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.productCode : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="productName" label="产品名称" width="150" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.productName : '' }}
              </template>
            </el-table-column> -->
            
            <!-- <el-table-column prop="processName" label="工序名称" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.processName : '' }}
              </template>
            </el-table-column> -->
            
          </el-table>
        </el-tab-pane>
      </el-tabs>
      
      <!-- 底部汇总 -->
      <div class="summary-footer">
        <span>总工时：<strong>{{ currentTotalWorkHours }}</strong> 小时</span>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'WorkHoursStatistics',
  data() {
    return {
      // 查询条件
      searchForm: {
        contractNo: '',
        productCode: '',
        orderNo: '',
        startDate: '',
        endDate: '',
        datanum:100
      },
      dateRange: [],
      activeTab: 'process',
      loading: false,
      tableHeight: '68vh',
      processTableData: []
    }
  },
  created() {
    // 设置默认日期为今天
    // const today = new Date()
    // const year = today.getFullYear()
    // const month = String(today.getMonth() + 1).padStart(2, '0')
    // const day = String(today.getDate()).padStart(2, '0')
    // const todayStr = `${year}-${month}-${day}`
    // this.dateRange = [todayStr, todayStr]
    // this.searchForm.startDate = todayStr
    // this.searchForm.endDate = todayStr
  },
  computed: {
    // 计算当前Tab的总工时
    currentTotalWorkHours() {
      const total = this.processTableData.reduce((sum, item) => {
        return sum + (parseFloat(item.workHours) || 0)
      }, 0)
      return total.toFixed(1)
    }
  },
  
  watch: {
    dateRange(val) {
      if (val && val.length === 2) {
        this.searchForm.startDate = val[0]
        this.searchForm.endDate = val[1]
      } else {
        this.searchForm.startDate = ''
        this.searchForm.endDate = ''
      }
    }
  },
  
  methods: {
    handleSearch() {
      // 校验日期是否已选择
      // if (!this.searchForm.startDate || !this.searchForm.endDate) {
      //   this.$message.warning('请选择开始日期和结束日期')
      //   return
      // }
      // // 校验开始日期不能大于结束日期
      // if (this.searchForm.startDate > this.searchForm.endDate) {
      //   this.$message.warning('开始日期不能大于结束日期')
      //   return
      // }
      this.loadProcessData()
    },
    handleTabChange() {
      this.loadProcessData()
    },
    formatReportType(value) {
      const reportType = String(value || '')
      if (reportType.includes('辅助')) return '调机'
      if (reportType.includes('报工')) return '正常'
      return reportType
    },
    
    loadProcessData() {
      this.loading = true
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || ''],
        ['数据条数', this.searchForm.datanum || ''],
      ]
      const Data = this.CreateData('11', '生产管理_工时查询_工序工时_查询', param)
      this.ExecDatabase(Data).then(res => {
        this.processTableData = this.buildProcessTree(res.data || [])
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    
    buildProcessTree(flatData) {
      const level1Map = new Map() // TaskAID
      const level2Map = new Map() // TaskAID_dateLabel
      
      flatData.forEach((row, index) => {
        if (row.Level === 1) {
          // 第一层：TaskAID汇总
          level1Map.set(row.TaskAID, {
            id: `p1-${index}`,
            level: 1,
            TaskAID: row.TaskAID,
            taskDescription: row.taskDescription,
            reportCount: row.reportCount,
            reportQty: row.reportQty,
            workHours: row.workHours || row.actualWorkHours,
            pieceWorkHours: row.pieceWorkHours,
            processWorkHours: row.processWorkHours,
            children: []
          })
        } else if (row.Level === 2) {
          // 第二层：按TaskAID和日期汇总
          const key = `${row.TaskAID}_${row.dateLabel}`
          level2Map.set(key, {
            id: `p2-${index}`,
            level: 2,
            TaskAID: row.TaskAID,
            taskDescription: row.taskDescription,
            dateLabel: row.dateLabel,
            shift: '',
            operatorNames: '',
            productionOrderNo: '',
            reportType: '',
            reportCount: row.reportCount,
            reportQty: row.reportQty,
            station: '',
            workHours: row.workHours || row.actualWorkHours,
            programTime: '',
            pieceWorkHours: row.pieceWorkHours,
            processWorkHours: row.processWorkHours,
            startTime: '',
            children: []
          })
        } else if (row.Level === 3) {
          // 第三层：明细
          const parentKey = `${row.TaskAID}_${row.dateLabel}`
          const parent = level2Map.get(parentKey)
          if (parent) {
            parent.children.push({
              id: `p3-${index}`,
              level: 3,
              TaskAID: row.TaskAID,
              taskDescription: row.taskDescription,
              dateLabel: row.dateLabel,
              shift: row.shift,
              operatorNames: row.operatorNames,
              productionOrderNo: row.productionOrderNo,
              reportType: this.formatReportType(row.reportType),
              reportQty: row.reportQty,
              station: row.station || row.工位名称,
              workHours: row.workHours || row.actualWorkHours,
              programTime: row.programTime,
              pieceWorkHours: row.pieceWorkHours,
              processWorkHours: row.processWorkHours,
              startTime: row.startTime
            })
          }
        }
      })
      
      // 构建树形结构
      level2Map.forEach(l2Item => {
        const parent = level1Map.get(l2Item.TaskAID)
        if (parent) {
          parent.children.push(l2Item)
        }
      })
      
      return Array.from(level1Map.values())
    },
    
    tableRowClassName({ row }) {
      if (row.level === 1) {
        return 'level1-row'
      }
      if (row.level === 2) {
        return 'level2-row'
      }
      if (row.level === 3) {
        return 'level3-row'
      }
      return ''
    }
  }
}
</script>

<style scoped>
.work-hours-statistics {
  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 .level1-row {
  background: #e8eaed !important;
}
::v-deep .el-table .level1-row:hover > td {
  background-color: #e8eaed !important;
}

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

::v-deep .el-table .level3-row {
  background: #ffffff !important;
}
::v-deep .el-table .level3-row:hover > td {
  background-color: #fafafa !important;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  font-size: 13px;
  padding: 8px 0;
}

::v-deep .el-table td {
  padding: 6px 0;
}

.summary-footer {
  margin-top: 5px;
  padding: 10px 20px;
  background-color: #fdfdfd;
  border-top: 1px solid #ebeef5;
  font-size: 14px;
  color: #606266;
  height: 40px;
  line-height: 20px;
}

/* 调整展开图标 */
::v-deep .el-table__expand-icon {
  color: #606266;
}
</style>
