<template>
  <div class="app-container design-hours-report-page">
    <el-card>
      <div class="search-container" @keyup.enter="searchTable">
        <span class="show-text">开始日期:</span>
        <el-date-picker
          v-model="searchForm.startDate"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          size="small"
          style="width: 140px; margin-right: 8px"
        />
        <span class="show-text">结束日期:</span>
        <el-date-picker
          v-model="searchForm.endDate"
          clearable
          type="date"
          value-format="yyyy-MM-dd"
          size="small"
          style="width: 140px; margin-right: 8px"
        />
        <span class="show-text">操作人:</span>
        <el-input v-model="searchForm.operator" clearable size="small" style="width: 120px; margin-right: 8px" />
        <span class="show-text">项目号:</span>
        <el-input v-model="searchForm.projectNo" clearable size="small" style="width: 130px; margin-right: 8px" />
        <span class="show-text">物料编码:</span>
        <el-input v-model="searchForm.itemCode" clearable size="small" style="width: 170px; margin-right: 8px" />
        <span class="show-text">任务ID:</span>
        <el-input v-model="searchForm.did" clearable size="small" style="width: 90px; margin-right: 8px" />
        <el-button :loading="loading" icon="el-icon-search" plain size="small" type="primary" @click="searchTable">查询</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        default-expand-all
        height="74vh"
        row-key="id"
        :tree-props="{ children: 'children' }"
        size="mini"
        style="width: 100%; margin-top: 12px"
      >
        <el-table-column label="操作人 / 日期 / 任务" min-width="260" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.Level <= 2 }">{{ getTreeTitle(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="工作日期" prop="工作日期" width="110" />
        <el-table-column align="center" label="RID" prop="RID" width="70" />
        <el-table-column align="center" label="DID" prop="DID" width="70" />
        <el-table-column align="left" label="项目号" prop="项目号" width="120" show-overflow-tooltip />
        <el-table-column align="left" label="物料编码" prop="物料编码" width="170" show-overflow-tooltip />
        <el-table-column align="left" label="物料名称" prop="物料名称" width="180" show-overflow-tooltip />
        <el-table-column align="left" label="图号" prop="图号" width="120" show-overflow-tooltip />
        <el-table-column align="center" label="报工次数" prop="报工次数" width="90" />
        <el-table-column align="right" label="工时(h)" prop="工时小时" width="90">
          <template slot-scope="scope">
            <span :class="{ 'bold-text': scope.row.Level <= 2 }">{{ formatHours(scope.row.工时小时) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="开始时间" prop="开始时间" width="150" />
        <el-table-column align="center" label="结束时间" prop="结束时间" width="150" />
        <el-table-column align="center" label="校验状态" prop="校验状态" width="90" />
        <el-table-column align="left" label="备注" prop="备注" min-width="160" show-overflow-tooltip />
      </el-table>

      <div class="summary-footer">
        <span>总工时：<strong>{{ totalHours }}</strong> 小时</span>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'DesignReportHoursReport',
  data() {
    return {
      loading: false,
      tableData: [],
      searchForm: {
        startDate: '',
        endDate: '',
        operator: '',
        projectNo: '',
        itemCode: '',
        did: ''
      }
    }
  },
  computed: {
    totalHours() {
      const total = this.tableData.reduce((sum, row) => sum + (Number(row.工时小时) || 0), 0)
      return total.toFixed(2)
    }
  },
  created() {
    this.searchTable()
  },
  methods: {
    buildSearchParams() {
      return [
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || ''],
        ['操作人', this.searchForm.operator || ''],
        ['项目号', this.searchForm.projectNo || ''],
        ['物料编码', this.searchForm.itemCode || ''],
        ['DID', this.searchForm.did || 0]
      ]
    },
    async searchTable() {
      this.loading = true
      const data = this.CreateData('11', '设计报工_工时报表_作业者工时_查询', this.buildSearchParams())
      try {
        const response = await this.ExecDatabase(data)
        this.tableData = this.buildTree(response.data || [])
      } catch (error) {
        console.error('设计工时报表查询失败:', error)
        this.$message.error('查询失败')
      } finally {
        this.loading = false
      }
    },
    buildTree(rows) {
      const personMap = new Map()
      const dateMap = new Map()

      rows.forEach(row => {
        if (row.Level === 1) {
          personMap.set(row.id, { ...row, children: [] })
        }
      })

      rows.forEach(row => {
        if (row.Level === 2) {
          const item = { ...row, children: [] }
          dateMap.set(row.id, item)
          const parent = personMap.get(row.parentId)
          if (parent) parent.children.push(item)
        }
      })

      rows.forEach(row => {
        if (row.Level === 3) {
          const parent = dateMap.get(row.parentId)
          if (parent) parent.children.push({ ...row })
        }
      })

      return Array.from(personMap.values())
    },
    getTreeTitle(row) {
      if (row.Level === 1) return row.操作人 || '未填写操作人'
      if (row.Level === 2) return row.工作日期 ? `日期 ${row.工作日期}` : '未填写日期'
      return row.任务描述 || `${row.DID || ''}`
    },
    formatHours(value) {
      if (value === null || value === undefined || value === '') return ''
      const numberValue = Number(value)
      if (Number.isNaN(numberValue)) return ''
      return numberValue.toFixed(2)
    }
  }
}
</script>

<style scoped>
.design-hours-report-page {
  padding: 12px;
}

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

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

.bold-text {
  font-weight: 600;
}

.summary-footer {
  height: 36px;
  line-height: 36px;
  text-align: right;
  color: #303133;
}
</style>
