<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.operator" placeholder="请输入作业者" clearable style="width: 100px; 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.processName" placeholder="请输入工序" clearable style="width: 100px; 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-select v-model="searchForm.workHoursType" placeholder="请选择" clearable style="width: 100px; margin-right: 10px">
          <el-option label="装配" value="装配" />
          <el-option label="电气" value="电气" />
          <el-option label="机加" value="机加" />
          <el-option label="质检" value="质检" />
          <el-option label="技术" value="技术" />
          <el-option label="计划" value="计划" />
          <el-option label="库房" value="库房" />
          <el-option label="采购" value="采购" />
          <el-option label="销售" value="销售" />
          <el-option label="售后" value="售后" />
          <el-option label="工艺" value="工艺" />
          <el-option label="其他" value="其他" />
        </el-select>
        <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 style="width: 100px;" icon="el-icon-download" type="primary"  @click="exportExcel">Excel导出</el-button>
      </div>

      <el-tabs v-model="activeTab" type="card" class="statistics-tabs" @tab-click="handleTabChange">
        <el-tab-pane label="项目工时" name="project">
          <el-table 
            v-loading="loading"
            :data="projectTableData" 
            :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="contractNo" label="合同号" width="160" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.level === 1 ? scope.row.contractNo : '' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="materialDesc" label="产品名称" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 1 ? scope.row.materialDesc : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="materialCode" label="产品编码" width="250" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 1 ? scope.row.materialCode : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="计划数量" label="计划数量" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.计划数量 : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="工序说明" label="工序说明" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.工序说明 : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="工时类型" label="工时类型" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? getWorkHoursType(scope.row) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="workHours" label="工时(h)" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.workHours }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.operator : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="planStart" label="开始时间" width="110" align="center" />
            
            <el-table-column prop="planEnd" label="结束时间" width="110" align="center" />
            <el-table-column prop="订单号" label="订单编号" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.订单号 : '' }}
              </template>
            </el-table-column>
            
            
            <el-table-column prop="processName" label="工序名称" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.processName : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="指派对象" label="指派对象" width="120" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.指派对象 : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="qty" label="计划/完成" width="100" align="center" />
            
            <el-table-column prop="reportQty" label="报工数量" width="90" align="center" />
            
            
            
            
            
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="作业者工时" name="operator">
           <el-table 
            v-loading="loading"
            :data="operatorTableData" 
            :height="tableHeight"
            border
            size="mini"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            default-expand-all
            class="custom-tree-table"
            :row-class-name="operatorTableRowClassName"
            style="width: 100%">
            
            <el-table-column prop="operator" label="操作人/日期" width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level <= 2}">
                  {{ scope.row.level === 1 ? scope.row.operator : (scope.row.level === 2 ? scope.row.dateLabel : '') }}
                </span>
              </template>
            </el-table-column>
            
            
            
            <el-table-column prop="contractNo" label="合同号" width="130" 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="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.orderNo : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="productCode" label="产品编码" width="280" 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="160" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.productName : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="计划数量" label="计划数量" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.计划数量 : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="工序说明" label="工序说明" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 3}">{{ scope.row.工序说明 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.startTime : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="endTime" label="结束时间" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.endTime : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="workHours" label="工时(h)" width="100" 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="processName" label="工序名称" width="90" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.processName : '' }}
              </template>
            </el-table-column>

            <el-table-column prop="工时类型" label="工时类型" width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? getWorkHoursType(scope.row) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="指派对象" label="指派对象" width="120" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.指派对象 : '' }}
              </template>
            </el-table-column>
            
            
            <el-table-column prop="操作类别" label="类型" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 3}">{{ scope.row.操作类别 }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="异常说明" label="异常说明" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 3}">{{ scope.row.异常说明 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reportCount" label="报工次数" width="90" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level <= 2}">{{ scope.row.level <= 2 ? scope.row.reportCount : '' }}</span>
              </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>
        </el-tab-pane>

        <el-tab-pane label="任务工时" name="task">
          <el-table 
            v-loading="loading"
            :data="taskTableData" 
            :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="contractNo" label="合同号" width="130" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.level === 1 ? scope.row.contractNo : '' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="orderNo" label="订单号" width="80" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.level === 1 ? scope.row.orderNo : '' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="productCode" label="产品编码" width="280" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 1 ? scope.row.productCode : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="productName" label="产品名称" width="200" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 1 ? scope.row.productName : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="计划数量" label="计划数量" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.level <= 2 ? scope.row.计划数量 : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="工序说明" label="工序说明" width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level <= 2 ? scope.row.工序说明 : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="工时类型" label="工时类型" width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level <= 2 ? getWorkHoursType(scope.row) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="workHours" label="工时(h)" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.workHours }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.operator : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="startTime" label="开始时间" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.startTime : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="endTime" label="结束时间" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.endTime : '' }}
              </template>
            </el-table-column>
            
            
            <el-table-column prop="processName" label="工序名称" width="90" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 1 ? scope.row.processName : '' }}
              </template>
            </el-table-column>

            

            <el-table-column prop="指派对象" label="指派对象" width="120" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 2 ? scope.row.指派对象 : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="qty" label="计划/完成" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.level === 1 ? scope.row.qty : '' }}</span>
              </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 === 1}">{{ scope.row.reportQty }}</span>
              </template>
            </el-table-column>
            
            
            <el-table-column prop="workHours" label="类型" width="100" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level === 1}">{{ scope.row.操作类别 }}</span>
              </template>
            </el-table-column>
            
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="设备工时" name="device">
           <el-table 
            v-loading="loading"
            :data="DeviceTableData" 
            :height="tableHeight"
            border
            size="mini"
            row-key="id"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            default-expand-all
            class="custom-tree-table"
            :row-class-name="operatorTableRowClassName"
            style="width: 100%">
            
            <el-table-column prop="operator" label="操作人/日期" width="140" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level <= 2}">
                  {{ scope.row.level === 1 ? scope.row.operator : (scope.row.level === 2 ? scope.row.dateLabel : '') }}
                </span>
              </template>
            </el-table-column>
            
           
            
            <el-table-column prop="contractNo" label="合同号" width="130" 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="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.orderNo : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="productCode" label="产品编码" width="280" 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="160" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.productName : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="计划数量" label="计划数量" width="100" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.计划数量 : '' }}
              </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="startTime" label="开始时间" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.startTime : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="endTime" label="结束时间" width="150" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.endTime : '' }}
              </template>
            </el-table-column>
            
            <el-table-column prop="workHours" label="工时(h)" width="100" 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="processName" label="工序名称" width="90" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.processName : '' }}
              </template>
            </el-table-column>

            <el-table-column prop="班次" label="班次" width="80" align="center">
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.班次 : '' }}
              </template>
            </el-table-column>

            <el-table-column prop="报工类型" label="报工类型" width="100" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.报工类型 : '' }}
              </template>
            </el-table-column>

            <el-table-column prop="指派对象" label="指派对象" width="120" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.level === 3 ? scope.row.指派对象 : '' }}
              </template>
            </el-table-column>
            
            
             <el-table-column prop="reportCount" label="报工次数" width="90" align="center">
              <template slot-scope="scope">
                <span :class="{'bold-text': scope.row.level <= 2}">{{ scope.row.level <= 2 ? scope.row.reportCount : '' }}</span>
              </template>
            </el-table-column>
            
            
            
          </el-table>
        </el-tab-pane>
      </el-tabs>
      
      <!-- 底部汇总 -->
      <div class="summary-footer">
        <span>总工时：<strong>{{ currentTotalWorkHours }}</strong> 小时</span>
        <span
          v-for="item in currentWorkHoursTypeSummary"
          :key="item.type"
          class="type-summary-item"
        >
          {{ item.type }}：<strong>{{ item.workHours }}</strong> 小时
        </span>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'WorkHoursStatistics',
  data() {
    return {
      // 查询条件
      searchForm: {
        contractNo: '',
        operator: '',
        productCode: '',
        processName: '',
        orderNo: '',
        workHoursType: '',
        startDate: '',
        endDate: ''
      },
      activeTab: 'project',
      loading: false,
      exporting: false,
      tableHeight: '68vh',
      totalCount: 0,
      totalWorkHours: '0',
      projectTableData: [],
      operatorTableData: [],
      DeviceTableData: [],
      taskTableData: []
    }
  },
  
  computed: {
    // 计算当前Tab的总工时
    currentTotalWorkHours() {
      let data = []
      if (this.activeTab === 'project') {
        data = this.projectTableData
      } else if (this.activeTab === 'operator') {
        data = this.operatorTableData
      } else if (this.activeTab === 'task') {
        data = this.taskTableData
      } else if (this.activeTab === 'device'){
        data = this.DeviceTableData
      }
      // 只算第一层的工时
      const total = data.reduce((sum, item) => {
        return sum + (parseFloat(item.workHours) || 0)
      }, 0)
      return total.toFixed(1)
    },
    currentWorkHoursTypeSummary() {
      const summaryMap = new Map()
      this.getCurrentSummaryItems().forEach(item => {
        const type = this.getWorkHoursType(item)
        const workHours = parseFloat(item.workHours) || 0
        summaryMap.set(type, (summaryMap.get(type) || 0) + workHours)
      })

      return Array.from(summaryMap, ([type, workHours]) => ({
        type,
        workHours: workHours.toFixed(1)
      }))
    }
  },
  
  mounted() {
    // 日期默认为空，不自动加载数据
  },
  
  methods: {
    getWorkHoursType(row) {
      return row.工时类型 || row.workType || row.WorkType || row.workHoursType || row.WorkHoursType || '未分类'
    },
    getStartTimeValue(row) {
      if (!row) return Number.MAX_SAFE_INTEGER
      const value = row.startTime || row.planStart || row.开始时间 || row.dateLabel || ''
      const text = String(value).trim()
      if (!text) return Number.MAX_SAFE_INTEGER
      const normalizedText = text.includes('T') ? text : text.replace(/-/g, '/')
      const time = new Date(normalizedText).getTime()
      return Number.isNaN(time) ? Number.MAX_SAFE_INTEGER : time
    },
    getEarliestStartTime(row) {
      if (row && Array.isArray(row.children) && row.children.length > 0) {
        return Math.min(...row.children.map(child => this.getEarliestStartTime(child)))
      }
      return this.getStartTimeValue(row)
    },
    sortRowsByStartTime(rows) {
      return (rows || []).map(row => {
        if (Array.isArray(row.children) && row.children.length > 0) {
          row.children = this.sortRowsByStartTime(row.children)
        }
        return row
      }).sort((a, b) => {
        const diff = this.getEarliestStartTime(a) - this.getEarliestStartTime(b)
        if (diff !== 0) return diff
        return String(a.id || '').localeCompare(String(b.id || ''), 'zh-CN')
      })
    },
    parseReportQty(value) {
      const sourceValue = value === null || value === undefined ? 0 : value
      const qty = Number(String(sourceValue).replace(/,/g, ''))
      return Number.isFinite(qty) ? qty : 0
    },
    formatReportQty(value) {
      if (!Number.isFinite(value)) return '0'
      return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(6)))
    },
    getTaskAID(row) {
      if (!row) return ''
      return row.TaskAID || row.taskAID || row.TaskId || row.taskId || row.任务ID || row.AID || ''
    },
    getReportQtyGroupKey(row) {
      const taskAID = this.getTaskAID(row)
      const startTime = row && (row.startTime || row.开始时间 || '')
      if (!taskAID || !startTime) return ''
      return `${taskAID}_${startTime}`
    },
    isAssemblyAssignee(row) {
      const assignee = row && (row.指派对象 || row.工位名称 || row.assignee || '')
      return String(assignee).includes('装配')
    },
    buildTaskStartReportQtyMap(rows) {
      const qtyMap = new Map()
      ;(rows || []).forEach(row => {
        if (Number(row.Level) !== 3) return
        const key = this.getReportQtyGroupKey(row)
        if (!key) return
        const reportQty = row.reportQty === null || row.reportQty === undefined ? row.报工数量 : row.reportQty
        const qty = this.parseReportQty(reportQty)
        const current = qtyMap.has(key) ? qtyMap.get(key) : Number.NEGATIVE_INFINITY
        qtyMap.set(key, Math.max(current, qty))
      })
      return qtyMap
    },
    getTaskStartReportQty(row, qtyMap) {
      if (this.isAssemblyAssignee(row)) return '0'
      const key = this.getReportQtyGroupKey(row)
      if (!key || !qtyMap || !qtyMap.has(key)) return row.reportQty
      return this.formatReportQty(qtyMap.get(key))
    },
    recalculateOperatorReportQty(treeData) {
      ;(treeData || []).forEach(operator => {
        const operatorQtyMap = new Map()
        let operatorHasTaskStartKey = false

        ;(operator.children || []).forEach(date => {
          const dateQtyMap = new Map()
          let dateHasTaskStartKey = false

          ;(date.children || []).forEach(detail => {
            const key = detail.reportQtyGroupKey
            if (!key) return
            const qty = this.parseReportQty(detail.reportQty)
            dateHasTaskStartKey = true
            operatorHasTaskStartKey = true
            const currentDateQty = dateQtyMap.has(key) ? dateQtyMap.get(key) : Number.NEGATIVE_INFINITY
            const currentOperatorQty = operatorQtyMap.has(key) ? operatorQtyMap.get(key) : Number.NEGATIVE_INFINITY
            dateQtyMap.set(key, Math.max(currentDateQty, qty))
            operatorQtyMap.set(key, Math.max(currentOperatorQty, qty))
          })

          if (dateHasTaskStartKey) {
            const dateQty = Array.from(dateQtyMap.values()).reduce((sum, qty) => sum + qty, 0)
            date.reportQty = this.formatReportQty(dateQty)
          }
        })

        if (operatorHasTaskStartKey) {
          const operatorQty = Array.from(operatorQtyMap.values()).reduce((sum, qty) => sum + qty, 0)
          operator.reportQty = this.formatReportQty(operatorQty)
        }
      })
    },
    getCurrentSummaryItems() {
      const items = []
      if (this.activeTab === 'project') {
        this.projectTableData.forEach(parent => {
          items.push(...(parent.children || []))
        })
      } else if (this.activeTab === 'operator') {
        this.operatorTableData.forEach(operator => {
          ;(operator.children || []).forEach(date => {
            items.push(...(date.children || []))
          })
        })
      } else if (this.activeTab === 'task') {
        this.taskTableData.forEach(task => {
          items.push(...(task.children || []))
        })
      }

      return items
    },
    handleSearch() {
      // 校验日期是否已选择
      // if (!this.searchForm.startDate || !this.searchForm.endDate) {
      //   this.$message.warning('请选择开始日期和结束日期')
      //   return
      // }
      // // 校验开始日期不能大于结束日期
      // if (this.searchForm.startDate > this.searchForm.endDate) {
      //   this.$message.warning('开始日期不能大于结束日期')
      //   return
      // }
      this.loadCurrentTabData()
    },
    // handleTabChange() {
    //   this.loadCurrentTabData()
    // },
    
    loadCurrentTabData() {
      if (this.activeTab === 'project') {
        this.loadProjectData()
      } else if (this.activeTab === 'operator') {
        this.loadOperatorData()
      } else if (this.activeTab === 'task') {
        this.loadTaskData()
      } else if (this.activeTab === 'device') {
        this.loadDeviceData()
      }
    },
    
    loadProjectData() {
      this.loading = true
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['操作人', this.searchForm.operator || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['工序名称', this.searchForm.processName || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['工时类型', this.searchForm.workHoursType || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || '']
      ]
      const Data = this.CreateData('11', '工时统计_项目工时_查询', param)
      this.ExecDatabase(Data).then(res => {
        this.projectTableData = this.buildProjectTree(res.data || [])
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    
    buildProjectTree(flatData) {
      const level1Map = new Map()
      const level2Items = []
      
      flatData.forEach((row, index) => {
        if (row.Level === 1) {
          const key = `${row.contractNo}_${row.materialCode}`
          level1Map.set(key, {
            id: `p-${index}`,
            level: 1,
            contractNo: row.contractNo,
            materialDesc: row.materialDesc,
            materialCode: row.materialCode,
            qty: row.qty,
            reportQty: row.reportQty,
            planStart: row.planStart,
            planEnd: row.planEnd,
            workHours: row.workHours,
            children: []
          })
        } else if (row.Level === 2) {
          level2Items.push({
            id: `p-${index}`,
            level: 2,
            contractNo: row.contractNo,
            materialCode: row.materialCode,
            processName: row.processName,
            operator: row.operator,
            指派对象: row.指派对象,
            qty: row.qty,
            reportQty: row.reportQty,
            planStart: row.planStart,
            planEnd: row.planEnd,
            workHours: row.workHours,
            订单号:row.订单号,
            操作类别 :row.操作类别,
            工时类型: this.getWorkHoursType(row),
            计划数量: row.计划数量,
            工序说明: row.工序说明
          })
        }
      })
      
      level2Items.forEach(item => {
        const key = `${item.contractNo}_${item.materialCode}`
        const parent = level1Map.get(key)
        if (parent) {
          parent.children.push(item)
        }
      })
      
      return this.sortRowsByStartTime(Array.from(level1Map.values()))
    },
    
    loadOperatorData() {
      this.loading = true
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['操作人', this.searchForm.operator || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['工序名称', this.searchForm.processName || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['工时类型', this.searchForm.workHoursType || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || '']
      ]
      
      const Data = this.CreateData('11', '工时统计_作业者工时_查询', param)
      this.ExecDatabase(Data).then(res => {
        this.operatorTableData = this.buildOperatorTree(res.data || [], true)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    
    loadDeviceData() {
      this.loading = true
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['操作人', this.searchForm.operator || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['工序名称', this.searchForm.processName || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || '']
      ]
      
      const Data = this.CreateData('11', '工时统计_设备工时_查询', param)
      this.ExecDatabase(Data).then(res => {
        this.DeviceTableData = this.buildOperatorTree(res.data || [])
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    buildOperatorTree(flatData, useTaskStartMaxReportQty = false) {
      const level1Map = new Map()
      const level2Map = new Map()
      const reportQtyMap = useTaskStartMaxReportQty ? this.buildTaskStartReportQtyMap(flatData) : null
      
      flatData.forEach((row, index) => {
        if (row.Level === 1) {
          level1Map.set(row.operator, {
            id: `o-${index}`,
            level: 1,
            operator: row.operator,
            reportCount: row.reportCount,
            reportQty: row.reportQty,
            workHours: row.workHours,
            children: []
          })
        } else if (row.Level === 2) {
          const key = `${row.operator}_${row.dateLabel}`
          level2Map.set(key, {
            id: `o-${index}`,
            level: 2,
            operator: row.operator,
            dateLabel: row.dateLabel,
            reportCount: row.reportCount,
            reportQty: row.reportQty,
            workHours: row.workHours,
            children: []
          })
        } else if (row.Level === 3) {
          const key = `${row.operator}_${row.dateLabel}`
          const parent = level2Map.get(key)
          if (parent) {
            const taskAID = this.getTaskAID(row)
            const reportQtyGroupKey = this.getReportQtyGroupKey(row)
            const reportQty = useTaskStartMaxReportQty ? this.getTaskStartReportQty(row, reportQtyMap) : row.reportQty
            parent.children.push({
              id: `o-${index}`,
              level: 3,
              TaskAID: taskAID,
              contractNo: row.contractNo,
              orderNo: row.orderNo,
              productCode: row.productCode,
              productName: row.productName,
              processName: row.processName,
              计划数量: row.计划数量,
              工序说明: row.工序说明,
              工时类型: this.getWorkHoursType(row),
              班次: row.班次,
              报工类型: row.报工类型,
              指派对象: row.指派对象,
              reportQty,
              reportQtyGroupKey,
              startTime: row.startTime,
              endTime: row.endTime,
              workHours: row.workHours,
              异常说明: row.异常说明,
              工序说明: row.工序说明,
              操作类别: row.操作类别,
            })
          }
        }
      })
      
      level2Map.forEach(l2Item => {
        const parent = level1Map.get(l2Item.operator)
        if (parent) {
          parent.children.push(l2Item)
        }
      })
      
      const treeData = this.sortRowsByStartTime(Array.from(level1Map.values()))
      if (useTaskStartMaxReportQty) {
        this.recalculateOperatorReportQty(treeData)
      }
      return treeData
    },
    
    loadTaskData() {
      this.loading = true
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['操作人', this.searchForm.operator || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['工序名称', this.searchForm.processName || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['工时类型', this.searchForm.workHoursType || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || '']
      ]
      const Data = this.CreateData('11', '工时统计_任务工时_查询', param)
      this.ExecDatabase(Data).then(res => {
        this.taskTableData = this.buildTaskTree(res.data || [])
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    
    buildTaskTree(flatData) {
      const level1Map = new Map()
      const level2Items = []
      
      flatData.forEach((row, index) => {
        if (row.Level === 1) {
          const key = `${row.contractNo}_${row.orderNo}_${row.productCode}_${row.processName}_${this.getWorkHoursType(row)}_${row.操作类别 || ''}`
          level1Map.set(key, {
            id: `t-${index}`,
            level: 1,
            contractNo: row.contractNo,
            orderNo: row.orderNo,
            productCode: row.productCode,
            productName: row.productName,
            processName: row.processName,
            计划数量: row.计划数量,
            工序说明: row.工序说明,
            工时类型: this.getWorkHoursType(row),
            qty: row.qty,
            reportQty: row.reportQty,
            workHours: row.workHours,
            children: []
          })
        } else if (row.Level === 2) {
          level2Items.push({
            id: `t-${index}`,
            level: 2,
            contractNo: row.contractNo,
            orderNo: row.orderNo,
            productCode: row.productCode,
            processName: row.processName,
            计划数量: row.计划数量,
            工序说明: row.工序说明,
            工时类型: this.getWorkHoursType(row),
            operator: row.operator,
            指派对象: row.指派对象,
            reportQty: row.reportQty,
            startTime: row.startTime,
            endTime: row.endTime,
            workHours: row.workHours,
            操作类别 :row.操作类别
          })
        }
      })
      
      // 12级关联
      level2Items.forEach(item => {
        const key = `${item.contractNo}_${item.orderNo}_${item.productCode}_${item.processName}_${this.getWorkHoursType(item)}_${item.操作类别 || ''}`
        const parent = level1Map.get(key)
        if (parent) {
          parent.children.push(item)
        }
      })
      
      return this.sortRowsByStartTime(Array.from(level1Map.values()))
    },
    
    tableRowClassName({ row }) {
      if (row.level === 1) {
        return 'order-row'
      }
      if (row.level === 2) {
        return 'process-row'
      }
      return ''
    },
    operatorTableRowClassName({ row }) {
      if (row.level === 1) {
        return 'operator-level1-row'
      }
      if (row.level === 2) {
        return 'operator-level2-row'
      }
      if (row.level === 3) {
        return 'operator-level3-row'
      }
      return ''
    },
    
    // Excel导出
    exportExcel() {
      // 校验日期是否已选择
      // if (!this.searchForm.startDate || !this.searchForm.endDate) {
      //   this.$message.warning('请选择开始日期和结束日期')
      //   return
      // }
      // // 校验开始日期不能大于结束日期
      // if (this.searchForm.startDate > this.searchForm.endDate) {
      //   this.$message.warning('开始日期不能大于结束日期')
      //   return
      // }
      
      // 根据当前Tab确定导出存储过程
      console.log(this.activeTab)
      let procedureName = ''
      if (this.activeTab === 'project') {
        procedureName = '工时统计_项目工时_查询_导出'
      } else if (this.activeTab === 'operator') {
        procedureName = '工时统计_作业者工时_查询_导出'
      } else if (this.activeTab === 'task') {
        procedureName = '工时统计_任务工时_查询_导出'
      } else if (this.activeTab === 'device') {
        procedureName = '工时统计_设备工时_查询_导出'
      }
      
      const param = [
        ['合同号', this.searchForm.contractNo || ''],
        ['操作人', this.searchForm.operator || ''],
        ['产品编码', this.searchForm.productCode || ''],
        ['工序名称', this.searchForm.processName || ''],
        ['订单号', this.searchForm.orderNo || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || '']
      ]
      
      
      this.exporting = true
      const Data = this.CreateData('2001', procedureName, param)
      this.exportExcel_NPOI(Data).finally(() => {
        this.exporting = false
      })
    }
  }
}
</script>

<style scoped>
.work-hours-statistics {
  padding: 10px;
}
.search-container {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.show-text {
  margin-right: 5px;
  font-size: 14px;
}
.record-count-tag {
  float: right;
  color: #909399;
  font-size: 12px;
  margin-right: 10px;
}

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

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

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

::v-deep .el-table .operator-level1-row {
  background: #e8eaed !important;
}
::v-deep .el-table .operator-level1-row:hover > td {
  background-color: #e8eaed !important;
}

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

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

::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: normal;
}

.summary-footer {
  margin-top: 5px;
  padding: 10px 20px;
  background-color: #fdfdfd;
  border-top: 1px solid #ebeef5;
  font-size: 13px;
  color: #606266;
  min-height: 40px;
  line-height: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px 20px;
}

.type-summary-item {
  white-space: nowrap;
}

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