<template>
  <div class="insp-layout">
    <div class="insp-sidebar">
      <div class="sidebar-header">
        巡检点位
        <span class="add-btn" @click="openLocDialog()">＋</span>
      </div>
      <div class="loc-list">
        <div
          v-for="loc in locations"
          :key="loc.id"
          :class="['loc-item', { active: selectedLoc && selectedLoc.id === loc.id }]"
          @click="selectLocation(loc)"
        >
          <div class="loc-code">{{ loc.code }}</div>
          <div class="loc-name">{{ loc.name }}</div>
        </div>
        <div v-if="!locations.length" class="loc-empty">暂无点位</div>
      </div>
    </div>

    <div class="insp-main">
      <div v-if="!selectedLoc" class="empty-tip">请选择点位</div>
      <template v-else>
        <div class="card">
          <div class="card-header" style="display:flex;align-items:center;justify-content:space-between;">
            <span>{{ selectedLoc.name }}&nbsp;<span class="td-muted" style="font-size:11px;">{{ selectedLoc.code }}</span></span>
            <button class="btn btn-primary" @click="openRecordDialog(null)">录入巡检</button>
          </div>
        </div>

        <div class="card">
          <div class="card-header">关联设备</div>
          <div class="table-scroll">
            <table class="data-table">
              <thead>
                <tr>
                  <th>设备编号</th><th>设备名称</th><th>类别</th><th>状态</th><th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="eq in locationEquipments" :key="eq.id">
                  <td class="td-num">{{ eq.code }}</td>
                  <td>{{ eq.name }}</td>
                  <td>{{ eq.category || '—' }}</td>
                  <td><span :class="['badge', eqStatusBadge(eq.status)]">{{ eqStatusLabel(eq.status) }}</span></td>
                  <td><span class="action-link" @click="openRecordDialog(eq)">录入</span></td>
                </tr>
                <tr v-if="!locationEquipments.length">
                  <td colspan="5" class="td-muted" style="text-align:center;padding:16px;">该点位暂无关联设备</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="card">
          <div class="card-header">
            巡检历史
            <span class="ch-badge">{{ records.length }} 条</span>
          </div>
          <div class="table-scroll" v-loading="loadingRecords">
            <table class="data-table">
              <thead>
                <tr>
                  <th>时间</th><th>设备</th><th>二维码</th><th>结果</th><th>巡检人</th><th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="r in records" :key="r.id">
                  <td class="td-muted">{{ fmtTime(r.created_at) }}</td>
                  <td>{{ r.equipment_name || r.equipment_code || '—' }}</td>
                  <td class="td-num">{{ r.scan_code || '—' }}</td>
                  <td><span :class="['badge', resultBadge(r.result)]">{{ resultLabel(r.result) }}</span></td>
                  <td>{{ r.inspector }}</td>
                  <td>{{ r.notes || '—' }}</td>
                </tr>
                <tr v-if="!records.length && !loadingRecords">
                  <td colspan="6" class="td-muted" style="text-align:center;padding:16px;">暂无巡检记录</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </template>
    </div>

    <div v-if="recordDialogVisible" class="modal-mask" @click.self="recordDialogVisible=false">
      <div class="modal-box" style="width:460px;">
        <div class="modal-header">
          录入巡检
          <span class="modal-close" @click="recordDialogVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <div style="display:flex;flex-direction:column;gap:12px;">
            <div class="form-field">
              <div class="kv-label">点位</div>
              <input class="kv-input" :value="selectedLoc.name" disabled />
            </div>
            <div class="form-field">
              <div class="kv-label">设备编号</div>
              <input v-model="recordForm.equipment_code" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">设备名称</div>
              <input v-model="recordForm.equipment_name" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">二维码</div>
              <input v-model="recordForm.scan_code" class="kv-input" ref="scanInput" />
            </div>
            <div class="form-field">
              <div class="kv-label">巡检结果 *</div>
              <select v-model="recordForm.result" class="kv-input">
                <option value="normal">正常</option>
                <option value="abnormal">异常</option>
                <option value="pending">待处理</option>
              </select>
            </div>
            <div class="form-field">
              <div class="kv-label">巡检人 *</div>
              <input v-model="recordForm.inspector" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">备注</div>
              <textarea v-model="recordForm.notes" class="kv-input" rows="3"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="recordDialogVisible=false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="saveRecord">{{ saving ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <div v-if="locDialogVisible" class="modal-mask" @click.self="locDialogVisible=false">
      <div class="modal-box" style="width:380px;">
        <div class="modal-header">
          新增点位
          <span class="modal-close" @click="locDialogVisible=false">✕</span>
        </div>
        <div class="modal-body">
          <div style="display:flex;flex-direction:column;gap:12px;">
            <div class="form-field">
              <div class="kv-label">点位编号 *</div>
              <input v-model="locForm.code" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">点位名称 *</div>
              <input v-model="locForm.name" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">描述</div>
              <input v-model="locForm.description" class="kv-input" />
            </div>
            <div class="form-field">
              <div class="kv-label">排序</div>
              <input v-model.number="locForm.sort_order" type="number" class="kv-input" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-outline" @click="locDialogVisible=false">取消</button>
          <button class="btn btn-primary" :disabled="saving" @click="saveLocation">{{ saving ? '保存中...' : '保存' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getInspectionLocations, createInspectionLocation,
  getInspectionRecords, createInspectionRecord,
  getEquipments,
} from '@/api'

const EQ_STATUS = {
  normal:      { label: '正常', badge: 'badge-green' },
  fault:       { label: '故障', badge: 'badge-red' },
  maintenance: { label: '检修', badge: 'badge-yellow' },
  standby:     { label: '备用', badge: 'badge-gray' },
}

const RESULT_MAP = {
  normal:   { label: '正常',  badge: 'badge-green' },
  abnormal: { label: '异常',  badge: 'badge-red' },
  pending:  { label: '待处理', badge: 'badge-yellow' },
}

export default {
  name: 'Inspection',
  data() {
    return {
      locations: [],
      selectedLoc: null,
      allEquipments: [],
      records: [],
      loadingRecords: false,
      saving: false,
      recordDialogVisible: false,
      locDialogVisible: false,
      recordForm: { result: 'normal', inspector: '', equipment_code: '', equipment_name: '', scan_code: '', notes: '' },
      locForm: { code: '', name: '', description: '', sort_order: 0 },
    }
  },
  computed: {
    locationEquipments() {
      if (!this.selectedLoc) return []
      return this.allEquipments.filter(e => e.location === this.selectedLoc.name)
    },
  },
  created() {
    this.fetchLocations()
    this.fetchAllEquipments()
  },
  methods: {
    async fetchLocations() {
      const res = await getInspectionLocations()
      this.locations = res.data || []
    },
    async fetchAllEquipments() {
      const res = await getEquipments({ page: 1, page_size: 200 })
      this.allEquipments = res.data?.items || []
    },
    async selectLocation(loc) {
      this.selectedLoc = loc
      await this.fetchRecords()
    },
    async fetchRecords() {
      if (!this.selectedLoc) return
      this.loadingRecords = true
      try {
        const res = await getInspectionRecords({ location_id: this.selectedLoc.id, page_size: 50 })
        this.records = res.data?.items || []
      } finally {
        this.loadingRecords = false
      }
    },
    openRecordDialog(eq) {
      this.recordForm = {
        result: 'normal',
        inspector: '',
        equipment_code: eq ? eq.code : '',
        equipment_name: eq ? eq.name : '',
        scan_code: '',
        notes: '',
      }
      this.recordDialogVisible = true
      this.$nextTick(() => { if (this.$refs.scanInput) this.$refs.scanInput.focus() })
    },
    async saveRecord() {
      if (!this.recordForm.inspector) { this.$message.error('巡检人不能为空'); return }
      this.saving = true
      try {
        await createInspectionRecord({ ...this.recordForm, location_id: this.selectedLoc.id })
        this.$message.success('保存成功')
        this.recordDialogVisible = false
        await this.fetchRecords()
      } finally {
        this.saving = false
      }
    },
    openLocDialog() {
      this.locForm = { code: '', name: '', description: '', sort_order: 0 }
      this.locDialogVisible = true
    },
    async saveLocation() {
      if (!this.locForm.code || !this.locForm.name) { this.$message.error('编号和名称不能为空'); return }
      this.saving = true
      try {
        await createInspectionLocation(this.locForm)
        this.$message.success('保存成功')
        this.locDialogVisible = false
        await this.fetchLocations()
      } finally {
        this.saving = false
      }
    },
    eqStatusLabel(s) { return EQ_STATUS[s]?.label || s },
    eqStatusBadge(s) { return EQ_STATUS[s]?.badge || 'badge-gray' },
    resultLabel(r) { return RESULT_MAP[r]?.label || r },
    resultBadge(r) { return RESULT_MAP[r]?.badge || 'badge-gray' },
    fmtTime(t) { return t ? t.slice(0, 16).replace('T', ' ') : '—' },
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables';

.insp-layout {
  display: flex;
  gap: 14px;
  height: 100%;
  overflow: hidden;
}

.insp-sidebar {
  width: 220px;
  flex-shrink: 0;
  background: $bg-card;
  border: 1px solid $border;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 10px 12px;
  font-size: 12px;
  font-weight: 600;
  color: $sms-highlight;
  border-bottom: 1px solid $border;
  background: $bg-panel;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.add-btn {
  cursor: pointer;
  color: $sms-highlight;
  font-size: 16px;
  line-height: 1;
  &:hover { opacity: .7; }
}

.loc-list {
  flex: 1;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: $border transparent;
}

.loc-item {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid rgba($border, .5);
  transition: background .12s;
  &:hover { background: rgba(255,255,255,.03); }
  &.active { background: rgba(0,200,255,.08); border-left: 3px solid $sms-highlight; }
}

.loc-code { font-size: 10px; font-family: $font-mono; color: $text-muted; }
.loc-name { font-size: 12px; color: $text-primary; margin-top: 2px; }
.loc-empty { padding: 20px; text-align: center; font-size: 12px; color: $text-muted; }

.insp-main {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 14px;
  min-width: 0;
  scrollbar-width: thin;
  scrollbar-color: $border transparent;
}

.empty-tip {
  padding: 40px;
  text-align: center;
  color: $text-muted;
  font-size: 13px;
}

.action-link { color: $sms-highlight; cursor: pointer; font-size: 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>
