<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">
        <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="oldVersion" label="优化前版本" width="100" align="center" />
          <el-table-column prop="newVersion" label="优化后版本" width="100" align="center" />
          <el-table-column prop="optimizer" label="优化人" width="80" />
          <el-table-column prop="compareDate" label="优化日期" width="100" align="center" />
          <el-table-column prop="status" label="状态" width="90" align="center">
            <template slot-scope="s">
              <el-tag :type="statusTag(s.row.status)" size="mini">{{ statusLabel(s.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template slot-scope="s">
              <el-button type="text" size="mini" icon="el-icon-view" @click="handleView(s.row)">查看对比</el-button>
              <el-button type="text" size="mini" icon="el-icon-edit" @click="handleEdit(s.row)">编辑</el-button>
              <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(s.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="560px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" size="small">
        <el-row :gutter="16">
          <el-col :span="16"><el-form-item label="图纸名称" prop="drawingName"><el-input v-model="form.drawingName" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="优化人" prop="optimizer"><el-input v-model="form.optimizer" /></el-form-item></el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="8"><el-form-item label="优化前版本" prop="oldVersion"><el-input v-model="form.oldVersion" placeholder="V1.0" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="优化后版本" prop="newVersion"><el-input v-model="form.newVersion" placeholder="V2.0" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="优化日期" prop="compareDate"><el-date-picker v-model="form.compareDate" type="date" style="width:100%" value-format="yyyy-MM-dd" /></el-form-item></el-col>
        </el-row>
        <el-form-item label="优化前问题描述" prop="beforeDesc">
          <el-input v-model="form.beforeDesc" type="textarea" :rows="2" placeholder="优化前存在的问题" />
        </el-form-item>
        <el-form-item label="优化后改进内容" prop="afterDesc">
          <el-input v-model="form.afterDesc" type="textarea" :rows="2" placeholder="优化后改进的内容" />
        </el-form-item>
        <el-form-item label="优化效果评价" prop="diffNotes">
          <el-input v-model="form.diffNotes" type="textarea" :rows="2" placeholder="如：刚度提升15%，振动降低20%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width:100%">
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="approved" />
            <el-option label="已驳回" value="rejected" />
          </el-select>
        </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>

    <!-- View Compare Dialog -->
    <el-dialog title="图纸优化对比" :visible.sync="viewVisible" width="700px" append-to-body>
      <div class="compare-grid" v-if="viewItem">
        <div class="cg-header">对比项</div>
        <div class="cg-header">优化前（{{ viewItem.oldVersion }}）</div>
        <div class="cg-header">优化后（{{ viewItem.newVersion }}）</div>
        <div class="cg-label">问题描述</div>
        <div class="cg-cell">{{ viewItem.beforeDesc || '无' }}</div>
        <div class="cg-cell">{{ viewItem.afterDesc || '无' }}</div>
        <div class="cg-label">改进效果</div>
        <div class="cg-cell cg-ok">{{ viewItem.diffNotes || '无' }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="viewVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDrawingCompareAll, getDrawingCompare, addDrawingCompare, updateDrawingCompare, delDrawingCompare } from '@/api/rm/drawingCompare'
import { listProject } from '@/api/rm/project'

export default {
  name: 'RmDrawingCompare',
  data() {
    return {
      currentProjectName: this.$route.query.projectName || sessionStorage.getItem('rm_current_project_name') || '',
      loading: false, list: [], currentProjectId: null,
      dialogVisible: false, dialogTitle: '', submitting: false, form: {},
      rules: { drawingName: [{ required: true, message: '请填写图纸名称', trigger: 'blur' }] },
      viewVisible: false, viewItem: null
    }
  },
  created() { this.loadCurrentProject() },
  methods: {
    loadCurrentProject() {
      const pid = this.$route.query.projectId || sessionStorage.getItem('rm_current_project_id')
      if (pid) {
        this.currentProjectId = 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.loadList() }
        })
      }
    },
    loadList() {
      this.loading = true
      listDrawingCompareAll({ projectId: this.currentProjectId }).then(r => { this.list = r.data || [] }).finally(() => { this.loading = false })
    },
    handleAdd() {
      if (!this.currentProjectId) { this.$message.warning('请先在项目总览中创建项目'); return }
      this.dialogTitle = '新增图纸优化对比'
      this.form = { projectId: this.currentProjectId, drawingName: '', oldVersion: 'V1.0', newVersion: 'V2.0', optimizer: '', compareDate: '', beforeDesc: '', afterDesc: '', diffNotes: '', status: 'pending' }
      this.dialogVisible = true; this.$nextTick(() => { this.$refs.formRef?.clearValidate() })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑图纸对比'
      getDrawingCompare(row.compareId).then(r => { this.form = r.data; this.dialogVisible = true; this.$nextTick(() => { this.$refs.formRef?.clearValidate() }) })
    },
    handleView(row) {
      this.viewItem = row; this.viewVisible = true
    },
    handleDelete(row) {
      this.$confirm(`确认删除 "${row.drawingName}" 的对比记录？`, '提示', { type: 'warning' }).then(() => { delDrawingCompare(row.compareId).then(() => { this.$message.success('删除成功'); this.loadList() }) })
    },
    handleSubmit() {
      this.$refs.formRef.validate(v => {
        if (!v) return; this.submitting = true
        const api = this.form.compareId ? updateDrawingCompare : addDrawingCompare
        api(this.form).then(() => { this.$message.success('保存成功'); this.dialogVisible = false; 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; }
.dialog-footer { text-align: right; }
.compare-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; border: 1px solid #d0d7de; border-radius: 4px; overflow: hidden; font-size: 13px; }
.cg-header { background: #f0f2f5; font-weight: 600; padding: 10px; border-bottom: 1px solid #d0d7de; }
.cg-label { background: #fafbfc; font-weight: 600; padding: 10px; border-bottom: 1px solid #eee; }
.cg-cell { padding: 10px; border-bottom: 1px solid #eee; }
.cg-ok { color: #67c23a; font-weight: 600; }
</style>
