<template>
  <el-card v-loading="loading" shadow="never">
    <template #header>
      <div class="toolbar">
        <div class="head-left">
          <router-link :to="{ name: 'devices' }" class="back-link">← 设备列表</router-link>
          <span class="title">设备详情</span>
          <el-tag v-if="device" :type="statusTagType(device.status)" size="small">
            {{ statusLabel(device.status) }}
          </el-tag>
        </div>
        <div v-if="device" class="head-actions">
          <el-button type="primary" @click="openSwapDialog">发起换机申请</el-button>
        </div>
      </div>
    </template>

    <template v-if="device">
      <el-descriptions :column="2" border class="block">
        <el-descriptions-item label="MID">{{ device.mid ?? "—" }}</el-descriptions-item>
        <el-descriptions-item label="设备别名">{{ device.alias ?? "—" }}</el-descriptions-item>
        <el-descriptions-item label="站点">{{ device.site ?? "—" }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="statusTagType(device.status)" size="small">
            {{ statusLabel(device.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="首次发现时间">{{ formatTime(device.firstSeenAt) }}</el-descriptions-item>
        <el-descriptions-item label="最近心跳时间">{{ formatTime(device.lastHeartbeatAt) }}</el-descriptions-item>
      </el-descriptions>

      <h3 class="section-title">SN 绑定时间线</h3>
      <el-table :data="bindingRows" border stripe style="width: 100%">
        <el-table-column prop="bindTypeLabel" label="绑定类型" min-width="120" />
        <el-table-column prop="licenseSnId" label="许可 SN ID" min-width="160" show-overflow-tooltip />
        <el-table-column label="绑定时间" width="180">
          <template #default="{ row }">{{ formatTime(row.bindAt) }}</template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
      </el-table>
    </template>

    <el-empty v-else-if="!loading" description="未加载到设备数据" />

    <el-dialog v-model="swapDialogVisible" title="发起换机申请" width="480px" destroy-on-close @closed="resetSwapForm">
      <el-form ref="swapFormRef" :model="swapForm" :rules="swapRules" label-width="120px">
        <el-form-item label="新设备 MID" prop="newMid">
          <el-input v-model="swapForm.newMid" maxlength="200" placeholder="请输入新设备 MID" />
        </el-form-item>
        <el-form-item label="换机原因" prop="reason">
          <el-input v-model="swapForm.reason" maxlength="500" placeholder="选填" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="swapForm.remark" maxlength="500" placeholder="选填" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="swapDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="swapSaving" @click="handleSwap">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { useAuthStore } from "../stores/auth";
import { getDevice, getDeviceBindings, createDeviceSwapRequest } from "../api/platform";
import { apiErrorMessage } from "../utils/apiErrorMessage";

const auth = useAuthStore();
const route = useRoute();

const loading = ref(false);
const device = ref(null);
const bindingRows = ref([]);

const swapDialogVisible = ref(false);
const swapSaving = ref(false);
const swapFormRef = ref(null);
const swapForm = ref({ newMid: "", reason: "", remark: "" });
const swapRules = {
  newMid: [{ required: true, message: "请输入新设备 MID", trigger: "blur" }],
};

const deviceId = computed(() => route.params.id);

onMounted(async () => {
  auth.restoreAxiosAuth();
  await loadDevice();
  await loadBindings();
});

function statusLabel(s) {
  if (s == null || s === "") return "—";
  const u = String(s).toUpperCase();
  const map = {
    ACTIVE: "ACTIVE",
    INACTIVE: "INACTIVE",
    DECOMMISSIONED: "DECOMMISSIONED",
  };
  return map[u] ?? String(s);
}

function statusTagType(s) {
  const u = String(s ?? "").toUpperCase();
  if (u === "ACTIVE") return "success";
  if (u === "INACTIVE") return "warning";
  if (u === "DECOMMISSIONED") return "info";
  return "";
}

function formatTime(v) {
  if (v == null) return "—";
  if (typeof v === "string") return v.replace("T", " ").slice(0, 19);
  return String(v);
}

async function loadDevice() {
  const id = deviceId.value;
  if (id == null || id === "") return;
  loading.value = true;
  try {
    const { data } = await getDevice(id);
    device.value = data && typeof data === "object" ? data : null;
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载设备失败"));
    device.value = null;
  } finally {
    loading.value = false;
  }
}

async function loadBindings() {
  const id = deviceId.value;
  if (id == null || id === "") return;
  try {
    const { data } = await getDeviceBindings(id);
    const raw = Array.isArray(data) ? data : Array.isArray(data?.content) ? data.content : [];
    bindingRows.value = raw;
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载绑定记录失败"));
    bindingRows.value = [];
  }
}

function openSwapDialog() {
  swapForm.value = { newMid: "", reason: "", remark: "" };
  swapDialogVisible.value = true;
}

function resetSwapForm() {
  swapForm.value = { newMid: "", reason: "", remark: "" };
  swapFormRef.value?.resetFields?.();
}

async function handleSwap() {
  const f = swapFormRef.value;
  if (!f) return;
  try {
    await f.validate();
  } catch {
    return;
  }
  swapSaving.value = true;
  const payload = {
    newMid: swapForm.value.newMid.trim(),
    reason: swapForm.value.reason?.trim() || undefined,
    remark: swapForm.value.remark?.trim() || undefined,
  };
  try {
    await createDeviceSwapRequest(deviceId.value, payload);
    ElMessage.success("换机申请已提交");
    swapDialogVisible.value = false;
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "提交失败"));
  } finally {
    swapSaving.value = false;
  }
}
</script>

<style scoped>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.head-left {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.back-link {
  color: var(--el-color-primary);
  text-decoration: none;
  font-size: 14px;
}
.back-link:hover {
  text-decoration: underline;
}
.block {
  margin-bottom: 20px;
}
.section-title {
  margin: 20px 0 12px;
  font-size: 15px;
  font-weight: 600;
}
</style>
