<template>
  <div>
    <div class="card">
      <div class="card-body" style="padding:10px 14px;">
        <div class="flex-row" style="flex-wrap:wrap;gap:12px;">
          <div class="flex-row">
            <span class="kv-label">设备名称</span>
            <input v-model="query.name" class="kv-input" style="width:140px;" @keyup.enter="fetchData" />
          </div>
          <div class="flex-row">
            <span class="kv-label">状态</span>
            <select v-model="query.status" class="kv-input" style="width:100px;">
              <option value="">全部</option>
              <option v-for="s in statusOptions" :key="s.value" :value="s.value">{{ s.label }}</option>
            </select>
          </div>
          <div class="flex-row">
            <button class="btn btn-primary" @click="fetchData">查询</button>
            <button class="btn btn-outline" @click="openDialog()">＋ 新增设备</button>
          </div>
          <!-- 状态汇总 -->
          <div class="flex-row" style="margin-left:auto;gap:16px;">
            <span v-for="s in statusSummary" :key="s.label" class="kv-label">
              {{ s.label }} <span class="kv-value" :style="{color: s.color}">{{ s.count }}</span>
            </span>
          </div>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="card-header">
        设备台账
        <span class="ch-badge">{{ total }} 台</span>
      </div>
      <div class="table-scroll" v-loading="loading">
        <table class="data-table">
          <thead>
            <tr>
              <th>编号</th><th>名称</th><th>类别</th><th>型号</th>
              <th>位置</th><th>额定功率</th><th>投用日期</th><th>状态</th><th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="row in tableData" :key="row.id">
              <td class="td-num">{{ row.code }}</td>
              <td>{{ row.name }}</td>
              <td class="td-muted">{{ row.category || '—' }}</td>
              <td class="td-muted">{{ row.model || '—' }}</td>
              <td>{{ row.location || '—' }}</td>
              <td class="td-num">{{ row.rated_power ? row.rated_power + ' kW' : '—' }}</td>
              <td class="td-muted">{{ row.install_date ? row.install_date.slice(0,10) : '—' }}</td>
              <td><span :class="['badge', statusBadge(row.status)]">{{ statusLabel(row.status) }}</span></td>
              <td>
                <span class="action-link" @click="openDialog(row)">编辑</span>
                <span class="action-link" @click="viewMaint(row)">维保</span>
              </td>
            </tr>
            <tr v-if="!tableData.length && !loading">
              <td colspan="9" class="td-muted" style="text-align:center;padding:24px;">暂无设备数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 设备弹窗 -->
    <div v-if="dialogVisible" class="modal-mask" @click.self="dialogVisible=false">
      <div class="modal-box" style="width:640px;">
        <div class="modal-header">
          {{ editRow ? '编辑设备' : '新增设备' }}
          <span class="modal-close" @click="dialogVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <div class="grid-2" style="gap:12px;">
            <div class="form-field"><div class="kv-label">设备编号 *</div><input v-model="form.code" class="kv-input" :disabled="!!editRow" /></div>
            <div class="form-field"><div class="kv-label">设备名称 *</div><input v-model="form.name" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">类别</div><input v-model="form.category" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">型号规格</div><input v-model="form.model" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">安装位置</div><input v-model="form.location" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">额定功率 (kW)</div><input v-model.number="form.rated_power" type="number" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">制造厂商</div><input v-model="form.manufacturer" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">投用日期</div><input v-model="form.install_date_d" type="date" class="kv-input" /></div>
            <div class="form-field" v-if="editRow">
              <div class="kv-label">当前状态</div>
              <select v-model="form.status" class="kv-input">
                <option v-for="s in statusOptions" :key="s.value" :value="s.value">{{ s.label }}</option>
              </select>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="dialogVisible=false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="save">{{ saving ? '...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <!-- 维保弹窗 -->
    <div v-if="maintVisible" class="modal-mask" @click.self="maintVisible=false">
      <div class="modal-box" style="width:860px;">
        <div class="modal-header">
          {{ currentEquip && currentEquip.name }} — 维保记录
          <span class="modal-close" @click="maintVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <button class="btn btn-outline" style="margin-bottom:10px;" @click="openMaintDialog()">＋ 新增维保</button>
          <table class="data-table">
            <thead><tr><th>类型</th><th>标题</th><th>开始</th><th>结束</th><th>工时(h)</th><th>费用(元)</th><th>执行人</th><th>结果</th></tr></thead>
            <tbody>
              <tr v-for="m in maintData" :key="m.id">
                <td><span class="badge badge-blue">{{ m.maintenance_type }}</span></td>
                <td>{{ m.title }}</td>
                <td class="td-muted">{{ fmtTime(m.start_time) }}</td>
                <td class="td-muted">{{ fmtTime(m.end_time) }}</td>
                <td class="td-num">{{ m.duration || '—' }}</td>
                <td class="td-num">{{ m.cost || '—' }}</td>
                <td class="td-muted">{{ m.technician || '—' }}</td>
                <td>
                  <span :class="['badge', m.result==='pass' ? 'badge-green' : m.result==='fail' ? 'badge-red' : 'badge-yellow']">
                    {{ m.result === 'pass' ? '通过' : m.result === 'fail' ? '失败' : '待确认' }}
                  </span>
                </td>
              </tr>
              <tr v-if="!maintData.length"><td colspan="8" class="td-muted" style="text-align:center;padding:20px;">暂无记录</td></tr>
            </tbody>
          </table>
        </div>
        <div class="modal-footer"><button class="btn btn-outline" @click="maintVisible=false">关闭</button></div>
      </div>
    </div>

    <!-- 新增维保 -->
    <div v-if="maintDialogVisible" class="modal-mask" @click.self="maintDialogVisible=false">
      <div class="modal-box" style="width:600px;">
        <div class="modal-header">新增维保记录<span class="modal-close" @click="maintDialogVisible=false">✕</span></div>
        <div class="modal-body">
          <div class="grid-2" style="gap:12px;">
            <div class="form-field">
              <div class="kv-label">维保类型</div>
              <select v-model="maintForm.maintenance_type" class="kv-input">
                <option value="repair">故障维修</option>
                <option value="planned">计划检修</option>
                <option value="inspection">巡检</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">结果</div>
              <select v-model="maintForm.result" class="kv-input">
                <option value="pass">通过</option>
                <option value="fail">失败</option>
                <option value="pending">待确认</option>
              </select>
            </div>
            <div class="form-field" style="grid-column:1/-1;"><div class="kv-label">标题 *</div><input v-model="maintForm.title" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">开始时间</div><input v-model="maintForm.start_time" type="datetime-local" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">结束时间</div><input v-model="maintForm.end_time" type="datetime-local" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">执行人</div><input v-model="maintForm.technician" class="kv-input" /></div>
            <div class="form-field"><div class="kv-label">费用(元)</div><input v-model.number="maintForm.cost" type="number" class="kv-input" /></div>
            <div class="form-field" style="grid-column:1/-1;"><div class="kv-label">维保内容</div><textarea v-model="maintForm.description" class="kv-input" rows="2" style="resize:vertical;"></textarea></div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="maintDialogVisible=false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="saveMaint">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getEquipments, createEquipment, updateEquipment, getEquipmentMaintenance, createMaintenance } from '@/api'

const STATUS_MAP = {
  normal:      { label: '正常', badge: 'badge-green', color: 'var(--accent-green)' },
  fault:       { label: '故障', badge: 'badge-red',   color: 'var(--accent-red)'   },
  maintenance: { label: '检修', badge: 'badge-yellow',color: 'var(--accent-yellow)'},
  standby:     { label: '备用', badge: 'badge-gray',  color: 'var(--text-muted)'   },
}

export default {
  name: 'Equipment',
  data() {
    return {
      loading: false, saving: false,
      tableData: [], total: 0,
      query: { page: 1, page_size: 20, name: '', status: '' },
      statusOptions: Object.entries(STATUS_MAP).map(([value, { label }]) => ({ value, label })),
      dialogVisible: false, editRow: null, form: {},
      maintVisible: false, currentEquip: null, maintData: [],
      maintDialogVisible: false, maintForm: {},
    }
  },
  computed: {
    statusSummary() {
      return Object.entries(STATUS_MAP).map(([value, { label, color }]) => ({
        label, color,
        count: this.tableData.filter(r => r.status === value).length
      }))
    }
  },
  created() { this.fetchData() },
  methods: {
    async fetchData() {
      this.loading = true
      try { const res = await getEquipments(this.query); this.tableData = res.data.items; this.total = res.data.total } finally { this.loading = false }
    },
    statusLabel(s) { return STATUS_MAP[s]?.label || s },
    statusBadge(s) { return STATUS_MAP[s]?.badge || 'badge-gray' },
    fmtTime(t) { return t ? t.replace('T',' ').slice(0,16) : '—' },
    openDialog(row = null) {
      this.editRow = row
      this.form = row ? { ...row, install_date_d: row.install_date?.slice(0,10) } : {}
      this.dialogVisible = true
    },
    async save() {
      if (!this.form.code || !this.form.name) { this.$message.error('编号和名称不能为空'); return }
      this.saving = true
      const d = { ...this.form }
      if (d.install_date_d) { d.install_date = d.install_date_d + 'T00:00:00'; delete d.install_date_d }
      try {
        if (this.editRow) await updateEquipment(this.editRow.id, d)
        else await createEquipment(d)
        this.$message.success('保存成功')
        this.dialogVisible = false; this.fetchData()
      } finally { this.saving = false }
    },
    async viewMaint(row) {
      this.currentEquip = row
      const res = await getEquipmentMaintenance(row.id)
      this.maintData = res.data.items
      this.maintVisible = true
    },
    openMaintDialog() {
      this.maintForm = { equipment_id: this.currentEquip.id, equipment_code: this.currentEquip.code, maintenance_type: 'repair', result: 'pending' }
      this.maintDialogVisible = true
    },
    async saveMaint() {
      if (!this.maintForm.title) { this.$message.error('标题不能为空'); return }
      this.saving = true
      const d = { ...this.maintForm }
      if (d.start_time) d.start_time = d.start_time.replace('T', 'T') + ':00'
      if (d.end_time) d.end_time = d.end_time.replace('T', 'T') + ':00'
      try {
        await createMaintenance(d)
        this.$message.success('保存成功')
        this.maintDialogVisible = false
        await this.viewMaint(this.currentEquip)
      } finally { this.saving = false }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables';
.action-link { color: $sms-highlight; cursor: pointer; font-size: 12px; margin-right: 12px; &:hover { text-decoration: underline; } }
.form-field { display: flex; flex-direction: column; gap: 5px; }
.modal-mask { position: fixed; inset: 0; background: rgba(0,0,0,.6); display: flex; align-items: center; justify-content: center; z-index: 9999; }
.modal-box { background: $bg-card; border: 1px solid $border; border-radius: 6px; max-width: 95vw; max-height: 90vh; display: flex; flex-direction: column; }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: $bg-panel; border-bottom: 1px solid $border; font-size: 13px; font-weight: 600; color: $sms-highlight; .modal-close { cursor: pointer; color: $text-muted; &:hover { color: $text-primary; } } }
.modal-body { padding: 16px; overflow-y: auto; }
.modal-footer { padding: 10px 16px; background: $bg-panel; border-top: 1px solid $border; display: flex; justify-content: flex-end; gap: 10px; }
</style>
