<template>
  <div class="app-container design-report-page">
    <el-card>
      <div class="search-container" @keyup.enter="searchTable">
        <span class="show-text">任务ID:</span>
        <el-input v-model="searchForm.did" clearable size="small" style="width: 90px; 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">图号:</span>
        <el-input v-model="searchForm.drawingNo" clearable size="small" style="width: 120px; margin-right: 8px" />
        <span class="show-text">父件编码:</span>
        <el-input v-model="searchForm.parentItemCode" clearable size="small" style="width: 170px; margin-right: 8px" />
        <span class="show-text">状态:</span>
        <el-select v-model="searchForm.status" clearable size="small" style="width: 110px; margin-right: 8px">
          <el-option label="全部" value="全部" />
          <el-option label="待开始" value="待开始" />
          <el-option label="执行中" value="执行中" />
          <el-option label="已结束" value="已结束" />
          <el-option label="已完成" value="已完成" />
        </el-select>
        <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
        height="74vh"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 12px"
      >
        <el-table-column align="center" fixed label="DID" prop="DID" width="70" />
        <el-table-column align="center" fixed label="状态" prop="单据状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.单据状态)" size="mini">{{ scope.row.单据状态 }}</el-tag>
          </template>
        </el-table-column>
        <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="left" label="任务描述" prop="任务描述" width="220" show-overflow-tooltip />
        <el-table-column align="left" label="指派对象" prop="指派对象" width="180" show-overflow-tooltip />
        <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="center" label="未结束" prop="未结束报工数" width="80" />
        <el-table-column align="center" label="最后开始" prop="最后开始时间" width="150" />
        <el-table-column align="center" label="最后结束" prop="最后结束时间" width="150" />
        <el-table-column align="left" label="设计要求" prop="设计要求" width="220" show-overflow-tooltip />
        <el-table-column align="center" fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="mini" :disabled="!canStart(scope.row)" @click="startTask(scope.row)">开始</el-button>
            <el-button type="text" size="mini" :disabled="!canEnd(scope.row)" @click="endTask(scope.row)">结束</el-button>
            <el-button type="text" size="mini" :disabled="!canComplete(scope.row)" @click="completeTask(scope.row)">完成</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'DesignReportWork',
  data() {
    return {
      loading: false,
      actionLoading: false,
      tableData: [],
      searchForm: {
        did: '',
        projectNo: '',
        itemCode: '',
        drawingNo: '',
        parentItemCode: '',
        status: ''
      }
    }
  },
  created() {
    this.searchTable()
  },
  methods: {
    buildSearchParams() {
      return [
        ['DID', this.searchForm.did || 0],
        ['项目号', this.searchForm.projectNo || ''],
        ['物料编码', this.searchForm.itemCode || ''],
        ['图号', this.searchForm.drawingNo || ''],
        ['关联父件物料编码', this.searchForm.parentItemCode || ''],
        ['预计开始时间_Start', ''],
        ['预计开始时间_End', ''],
        ['预计结束时间_Start', ''],
        ['预计结束时间_End', ''],
        ['单据状态', this.searchForm.status || '']
      ]
    },
    async searchTable() {
      this.loading = true
      const data = this.CreateData('11', '设计报工_任务_查询', this.buildSearchParams())
      try {
        const response = await this.ExecDatabase(data)
        this.tableData = response.data || []
      } catch (error) {
        console.error('设计报工任务查询失败:', error)
        this.$message.error('查询失败')
      } finally {
        this.loading = false
      }
    },
    canStart(row) {
      return row.单据状态 !== '已完成' && Number(row.未结束报工数 || 0) === 0
    },
    canEnd(row) {
      return row.单据状态 !== '已完成' && Number(row.未结束报工数 || 0) > 0
    },
    canComplete(row) {
      return row.单据状态 !== '已完成' && Number(row.未结束报工数 || 0) === 0 && Number(row.报工次数 || 0) > 0
    },
    startTask(row) {
      this.runAction('设计报工_任务_开始', [
        ['DID', row.DID],
        ['操作人ID', this.currentUserId()],
        ['操作人', this.currentUserName()]
      ], '开始成功')
    },
    endTask(row) {
      this.runAction('设计报工_任务_结束', [
        ['DID', row.DID],
        ['操作人ID', this.currentUserId()],
        ['操作人', this.currentUserName()]
      ], '结束成功')
    },
    completeTask(row) {
      this.$confirm(`确定完成设计任务 DID ${row.DID} 吗？`, '提示', { type: 'warning' })
        .then(() => {
          this.runAction('设计报工_任务_完成', [
            ['DID', row.DID],
            ['操作人', this.currentUserName()]
          ], '完成成功')
        })
        .catch(() => {})
    },
    async runAction(procedure, params, defaultMessage) {
      if (this.actionLoading) return
      this.actionLoading = true
      const data = this.CreateData('12', procedure, params)
      try {
        const response = await this.ExecDatabase(data)
        const result = this.getResult(response)
        if (String(result.result) === '1') {
          this.$message.success(result.message || defaultMessage)
          this.searchTable()
        } else {
          this.$message.error(result.message || '操作失败')
        }
      } catch (error) {
        console.error(`${procedure}失败:`, error)
        this.$message.error('操作失败')
      } finally {
        this.actionLoading = false
      }
    },
    getResult(response) {
      const data = response && response.data
      if (Array.isArray(data)) return data[0] || {}
      if (data && Array.isArray(data.result)) return data.result[0] || {}
      return data || {}
    },
    currentUserId() {
      return (this.$store && this.$store.getters && this.$store.getters.id) || ''
    },
    currentUserName() {
      return (this.$store && this.$store.getters && this.$store.getters.name) || ''
    },
    getStatusType(status) {
      if (status === '已完成') return 'success'
      if (status === '执行中') return 'warning'
      if (status === '已结束') return 'primary'
      return 'info'
    }
  }
}
</script>

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

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

.show-text {
  margin-right: 4px;
}
</style>
