<template>
  <div class="app-container design-check-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.operator" clearable size="small" style="width: 120px; margin-right: 8px" />
        <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-select v-model="searchForm.checkStatus" size="small" style="width: 110px; margin-right: 8px">
          <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>
        <el-button :disabled="!multipleSelection.length" icon="el-icon-check" plain size="small" type="success" @click="batchValidate">批量校验</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        height="74vh"
        highlight-current-row
        size="mini"
        style="width: 100%; margin-top: 12px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column align="center" fixed label="RID" prop="RID" width="70" />
        <el-table-column align="center" fixed label="DID" prop="DID" width="70" />
        <el-table-column align="center" label="校验状态" width="90">
          <template slot-scope="scope">
            <el-tag :type="scope.row.已校验 ? 'success' : 'info'" 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="110" 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="right" label="工时(h)" prop="工时小时" width="90" />
        <el-table-column align="left" label="校验人" prop="校验人" width="110" show-overflow-tooltip />
        <el-table-column align="center" label="校验时间" prop="校验时间" width="150" />
        <el-table-column align="left" label="备注" prop="备注" width="180" show-overflow-tooltip />
        <el-table-column align="center" fixed="right" label="操作" width="90">
          <template slot-scope="scope">
            <el-button type="text" size="mini" :disabled="!!scope.row.已校验" @click="openValidate(scope.row)">
              {{ scope.row.已校验 ? '已校验' : '校验' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      :visible.sync="dialogVisible"
      title="设计工时校验"
      width="620px"
      center
      :close-on-click-modal="false"
    >
      <el-form ref="checkForm" :model="formData" :rules="rules" label-width="110px" size="small">
        <el-form-item label="RID">
          <el-input v-model="formData.RID" disabled />
        </el-form-item>
        <el-form-item label="任务">
          <el-input :value="`${formData.DID || ''} ${formData.任务描述 || ''}`" disabled />
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="formData.操作人" disabled />
        </el-form-item>
        <el-form-item label="开始时间" prop="开始时间">
          <el-date-picker v-model="formData.开始时间" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="结束时间">
          <el-date-picker v-model="formData.结束时间" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="工时(h)">
          <el-input :value="calculatedHours" disabled />
        </el-form-item>
        <el-form-item label="校验备注">
          <el-input v-model="formData.备注" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitValidate">保存校验</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DesignReportCheck',
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      tableData: [],
      multipleSelection: [],
      searchForm: {
        did: '',
        projectNo: '',
        itemCode: '',
        operator: '',
        startDate: '',
        endDate: '',
        checkStatus: '未校验'
      },
      formData: {
        RID: '',
        DID: '',
        任务描述: '',
        操作人: '',
        开始时间: '',
        结束时间: '',
        备注: ''
      },
      rules: {
        开始时间: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        结束时间: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      }
    }
  },
  computed: {
    calculatedHours() {
      if (!this.formData.开始时间 || !this.formData.结束时间) return ''
      const start = new Date(this.formData.开始时间)
      const end = new Date(this.formData.结束时间)
      const diff = end.getTime() - start.getTime()
      if (Number.isNaN(diff) || diff <= 0) return ''
      return (diff / 3600000).toFixed(2)
    }
  },
  created() {
    this.searchTable()
  },
  methods: {
    buildSearchParams() {
      return [
        ['DID', this.searchForm.did || 0],
        ['项目号', this.searchForm.projectNo || ''],
        ['物料编码', this.searchForm.itemCode || ''],
        ['操作人', this.searchForm.operator || ''],
        ['开始日期', this.searchForm.startDate || ''],
        ['结束日期', this.searchForm.endDate || ''],
        ['校验状态', this.searchForm.checkStatus || '全部']
      ]
    },
    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
      }
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    openValidate(row) {
      this.formData = {
        RID: row.RID,
        DID: row.DID,
        任务描述: row.任务描述,
        操作人: row.操作人,
        开始时间: row.开始时间 || '',
        结束时间: row.结束时间 || '',
        备注: row.备注 || ''
      }
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.checkForm && this.$refs.checkForm.clearValidate())
    },
    submitValidate() {
      this.$refs.checkForm.validate(async valid => {
        if (!valid) return
        if (new Date(this.formData.结束时间) <= new Date(this.formData.开始时间)) {
          this.$message.error('结束时间必须大于开始时间')
          return
        }
        this.submitLoading = true
        const params = [
          ['RID', this.formData.RID],
          ['开始时间', this.formData.开始时间],
          ['结束时间', this.formData.结束时间],
          ['校验人ID', this.currentUserId()],
          ['校验人', this.currentUserName()],
          ['校验备注', this.formData.备注 || '']
        ]
        const data = this.CreateData('12', '设计报工_工时校验_保存', params)
        try {
          const response = await this.ExecDatabase(data)
          const result = this.getResult(response)
          if (String(result.result) === '1') {
            this.$message.success(result.message || '校验成功')
            this.dialogVisible = false
            this.searchTable()
          } else {
            this.$message.error(result.message || '校验失败')
          }
        } catch (error) {
          console.error('设计工时校验保存失败:', error)
          this.$message.error('校验失败')
        } finally {
          this.submitLoading = false
        }
      })
    },
    batchValidate() {
      const rows = this.multipleSelection.filter(row => !row.已校验 && row.开始时间 && row.结束时间)
      if (!rows.length) {
        this.$message.warning('请选择未校验且已有结束时间的记录')
        return
      }
      this.$confirm(`确定批量校验 ${rows.length} 条设计报工记录吗？`, '提示', { type: 'warning' })
        .then(async () => {
          const params = [
            ['RIDs', rows.map(row => row.RID).join(',')],
            ['校验人ID', this.currentUserId()],
            ['校验人', this.currentUserName()]
          ]
          const data = this.CreateData('12', '设计报工_工时校验_批量保存', params)
          const response = await this.ExecDatabase(data)
          const result = this.getResult(response)
          if (String(result.result) === '1') {
            this.$message.success(result.message || '批量校验成功')
            this.searchTable()
          } else {
            this.$message.error(result.message || '批量校验失败')
          }
        })
        .catch(() => {})
    },
    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) || ''
    }
  }
}
</script>

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

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

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