<template>
  <div class="rm-container">
    <div class="current-project-bar">当前项目：{{ currentProjectName }}</div>
    <div class="rm-panel">
      <div class="rm-panel-header">
        <span>图纸审查</span>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd">新增审查记录</el-button>
      </div>
      <div class="rm-panel-body">
        <!-- Search -->
        <div class="search-row">
          <el-input v-model="query.drawingName" size="small" placeholder="图纸名称" clearable style="width:160px" @keyup.enter="handleSearch" />
          <el-select v-model="query.status" size="small" placeholder="状态" clearable style="width:110px">
            <el-option label="待审查" value="pending" />
            <el-option label="通过" value="approved" />
            <el-option label="驳回" value="rejected" />
          </el-select>
          <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <el-button size="small" icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </div>

        <!-- Table -->
        <el-table :data="list" v-loading="loading" stripe border highlight-current-row size="small">
          <el-table-column type="index" label="#" width="45" />
          <el-table-column prop="drawingName" label="图纸名称" min-width="160" />
          <el-table-column prop="reviewer" label="审查人" width="90" />
          <el-table-column prop="reviewDate" label="审查日期" width="100" align="center" />
          <el-table-column prop="status" label="结果" width="90" align="center">
            <template slot-scope="scope">
              <el-tag :type="statusTag(scope.row.status)" size="mini">{{ statusLabel(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="reviewOpinion" label="审查意见" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-row">
          <el-pagination :current-page="query.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="query.pageSize"
            :total="total" layout="total, sizes, prev, pager, next, jumper" size="small"
            @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>
      </div>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px" size="small">
        <el-form-item label="图纸名称" prop="drawingName">
          <el-input v-model="form.drawingName" placeholder="关联图纸名称" />
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="审查人" prop="reviewer">
              <el-input v-model="form.reviewer" placeholder="审查人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审查日期" prop="reviewDate">
              <el-date-picker v-model="form.reviewDate" type="date" placeholder="选择日期" style="width:100%" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="结果" prop="status">
              <el-select v-model="form.status" placeholder="请选择" style="width:100%">
                <el-option label="待审查" value="pending" />
                <el-option label="通过" value="approved" />
                <el-option label="驳回" value="rejected" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审查意见" prop="reviewOpinion">
          <el-input v-model="form.reviewOpinion" type="textarea" :rows="3" placeholder="审查意见" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
        <el-button size="small" type="primary" :loading="submitting" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDrawingReview, getDrawingReview, addDrawingReview, updateDrawingReview, delDrawingReview } from '@/api/rm/drawingReview'
import { listProject } from '@/api/rm/project'

export default {
  name: 'RmDrawingReview',
  data() {
    return {
      currentProjectName: this.$route.query.projectName || sessionStorage.getItem('rm_current_project_name') || '',
      loading: false,
      list: [],
      total: 0,
      currentProjectId: null,
      query: { pageNum: 1, pageSize: 10, drawingName: undefined, status: undefined, projectId: undefined },
      dialogVisible: false,
      dialogTitle: '',
      submitting: false,
      form: {},
      rules: { drawingName: [{ required: true, message: '请填写图纸名称', trigger: 'blur' }] }
    }
  },
  created() { this.loadCurrentProject() },
  methods: {
    loadCurrentProject() {
      const pid = this.$route.query.projectId || sessionStorage.getItem('rm_current_project_id')
      if (pid) {
        this.currentProjectId = pid
        this.query.projectId = pid
        this.loadList()
      } else {
        listProject({ pageNum: 1, pageSize: 1 }).then(res => {
          const rows = res.rows || []
          if (rows.length > 0) {
            this.currentProjectId = rows[0].projectId
            this.query.projectId = rows[0].projectId
            this.loadList()
          }
        })
      }
    },
    loadList() {
      this.loading = true
      listDrawingReview(this.query).then(res => {
        this.list = res.rows || []
        this.total = res.total || 0
      }).finally(() => { this.loading = false })
    },
    handleSearch() { this.query.pageNum = 1; this.loadList() },
    handleReset() { this.query = { pageNum: 1, pageSize: 10 }; this.loadList() },
    handleSizeChange(val) { this.query.pageSize = val; this.loadList() },
    handlePageChange(val) { this.query.pageNum = val; this.loadList() },
    handleAdd() {
      this.dialogTitle = '新增审查记录'
      if (!this.currentProjectId) { this.$message.warning('请先在项目总览中创建项目'); return }
      this.form = { projectId: this.currentProjectId, drawingName: '', reviewer: '', reviewDate: '', status: 'pending', reviewOpinion: '', remark: '' }
      this.dialogVisible = true
      this.$nextTick(() => { this.$refs.formRef?.clearValidate() })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑审查记录'
      getDrawingReview(row.reviewId).then(res => {
        this.form = res.data
        this.dialogVisible = true
        this.$nextTick(() => { this.$refs.formRef?.clearValidate() })
      })
    },
    handleDelete(row) {
      this.$confirm(`确认删除 "${row.drawingName}" 的审查记录？`, '提示', { type: 'warning', confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => {
        delDrawingReview(row.reviewId).then(() => { this.$message.success('删除成功'); this.loadList() })
      })
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.submitting = true
        const api = this.form.reviewId ? updateDrawingReview : addDrawingReview
        api(this.form).then(() => {
          this.$message.success(this.form.reviewId ? '更新成功' : '新增成功')
          this.dialogVisible = false
          if (!this.form.reviewId) this.query.pageNum = 1
          this.loadList()
        }).finally(() => { this.submitting = false })
      })
    },
    statusTag(s) { return { pending: 'info', approved: 'success', rejected: 'danger' }[s] || 'info' },
    statusLabel(s) { return { pending: '待审查', approved: '通过', rejected: '驳回' }[s] || s }
  }
}
</script>

<style scoped>
.rm-container { padding: 8px; }
.rm-panel { background: #fff; border-radius: 4px; border: 1px solid #d0d7de; }
.rm-panel-header { padding: 8px 12px; font-size: 14px; font-weight: 600; border-bottom: 1px solid #d0d7de; display: flex; align-items: center; justify-content: space-between; }
.rm-panel-body { padding: 8px 12px; }
.search-row { display: flex; gap: 6px; align-items: center; margin-bottom: 8px; flex-wrap: wrap; }
.pagination-row { margin-top: 10px; display: flex; justify-content: flex-end; }
.dialog-footer { text-align: right; }
</style>
