<template>
  <el-card shadow="never">
    <template #header>
      <div class="toolbar">
        <span class="title">许可 SN</span>
        <div class="actions">
          <el-select
            v-model="filterProjectId"
            clearable
            filterable
            placeholder="按项目筛选"
            style="width: 200px"
          >
            <el-option v-for="p in projectOptions" :key="p.id" :label="p.name || String(p.id)" :value="p.id" />
          </el-select>
          <el-input
            v-model="keyword"
            clearable
            placeholder="按 SN 编码搜索"
            class="search"
            @keyup.enter="load"
          />
          <el-button type="primary" :loading="loading" @click="load">查询</el-button>
          <el-button type="success" v-permission="'license:sn:rw'" @click="goNew">新建许可 SN</el-button>
          <el-button v-permission="'license:sn:rw'" @click="batchDialogVisible = true">批量导入</el-button>
        </div>
      </div>
    </template>

    <el-table v-loading="loading" :data="rows" stripe style="width: 100%">
      <el-table-column prop="snCode" label="SN 编码" min-width="160" show-overflow-tooltip />
      <el-table-column label="项目" min-width="160" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.projectName ?? projectNameById(row.projectId) }}
        </template>
      </el-table-column>
      <el-table-column label="合同行 ID" width="110">
        <template #default="{ row }">{{ row.contractLineId ?? "—" }}</template>
      </el-table-column>
      <el-table-column label="状态" width="110">
        <template #default="{ row }">
          <el-tag :type="snStatusTagType(row.status)" size="small">{{ snStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170">
        <template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="goDetail(row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @current-change="load"
        @size-change="onSizeChange"
      />
    </div>
    <el-dialog v-model="batchDialogVisible" title="批量导入 SN" width="520px">
      <el-form label-width="120px">
        <el-form-item label="SN 编码">
          <el-input v-model="batchSnText" type="textarea" :rows="8" placeholder="每行一个 SN 编码" />
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="batchProjectId" clearable filterable placeholder="选填" style="width:100%">
            <el-option v-for="p in projectOptions" :key="p.id" :label="p.name || String(p.id)" :value="p.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="激活备注">
          <el-input v-model="batchRemark" maxlength="512" placeholder="选填" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="batchImporting" @click="handleBatchImport">导入</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useAuthStore } from "../stores/auth";
import { listLicenseSns, listProjects, batchImportLicenseSns } from "../api/platform";
import { apiErrorMessage } from "../utils/apiErrorMessage";

const auth = useAuthStore();
const router = useRouter();

const loading = ref(false);
const rows = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const keyword = ref("");
const filterProjectId = ref(undefined);
const projectOptions = ref([]);
/** @type {import('vue').Ref<Map<string | number, string>>} */
const projectMap = ref(new Map());
const batchDialogVisible = ref(false);
const batchSnText = ref('');
const batchProjectId = ref(undefined);
const batchRemark = ref('');
const batchImporting = ref(false);

onMounted(async () => {
  auth.restoreAxiosAuth();
  await loadProjects();
  await load();
});

function onSizeChange() {
  page.value = 1;
  load();
}

function projectNameById(id) {
  if (id == null) return "—";
  return projectMap.value.get(id) ?? String(id);
}

function snStatusLabel(s) {
  const u = String(s ?? "").toUpperCase();
  const map = {
    REGISTERED: "已登记",
    ISSUED: "已发放",
    ACTIVATED: "已激活",
    SUSPENDED: "已暂停",
    REVOKED: "已吊销",
  };
  return map[u] ?? String(s ?? "—");
}

function snStatusTagType(s) {
  const u = String(s ?? "").toUpperCase();
  if (u === "REGISTERED") return "info";
  if (u === "ISSUED") return "";
  if (u === "ACTIVATED") return "success";
  if (u === "SUSPENDED") return "warning";
  if (u === "REVOKED") return "danger";
  return "";
}

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

async function loadProjects() {
  try {
    const { data } = await listProjects({ page: 0, size: 500 });
    const body = data && typeof data === "object" ? data : {};
    const list = Array.isArray(body.content) ? body.content : [];
    projectOptions.value = list;
    const m = new Map();
    for (const p of list) {
      if (p?.id != null) m.set(p.id, p.name ?? String(p.id));
    }
    projectMap.value = m;
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载项目失败"));
    projectOptions.value = [];
    projectMap.value = new Map();
  }
}

async function load() {
  loading.value = true;
  try {
    const { data } = await listLicenseSns({
      page: page.value - 1,
      size: pageSize.value,
      keyword: keyword.value?.trim() || undefined,
      projectId: filterProjectId.value ?? undefined,
    });
    const body = data && typeof data === "object" ? data : {};
    rows.value = Array.isArray(body.content) ? body.content : [];
    total.value = Number(body.totalElements ?? body.total ?? 0);
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, "加载许可 SN 失败"));
    rows.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

function goNew() {
  router.push({ name: "license-sn-new" });
}

function goDetail(id) {
  router.push({ name: "license-sn-detail", params: { id: String(id) } });
}

async function handleBatchImport() {
  const codes = batchSnText.value.split('\n').map(s => s.trim()).filter(Boolean)
  if (codes.length === 0) { ElMessage.warning('请输入 SN 编码'); return }
  batchImporting.value = true
  try {
    const { data } = await batchImportLicenseSns({
      snCodes: codes,
      projectId: batchProjectId.value || undefined,
      activationRemark: batchRemark.value || undefined,
    })
    ElMessage.success(`导入完成：成功 ${data.success} 条，失败 ${data.failed} 条`)
    batchDialogVisible.value = false
    batchSnText.value = ''
    load()
  } catch (e) {
    ElMessage.error(apiErrorMessage(e, '批量导入失败'))
  } finally {
    batchImporting.value = false
  }
}
</script>

<style scoped>
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}
.search {
  width: 200px;
}
.pager {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
