<template>
  <section>
    <header class="page-head">
      <div>
        <h2>学员管理</h2>
        <p>支持手动新增、修改、删除和查询学员，也可以继续通过 Excel 批量导入。</p>
      </div>
      <el-button type="primary" :icon="Upload" @click="openImportDialog">批量导入学员</el-button>
    </header>

    <el-dialog v-model="importVisible" title="批量导入学员" width="640px" destroy-on-close>
      <div class="import-actions">
        <div>
          <h3>学员 Excel</h3>
          <p>必填姓名和手机号；学员编号、备注为选填。手机号已存在时姓名必须一致。</p>
        </div>
        <el-button :icon="Download" @click="downloadImportTemplate">下载模板</el-button>
      </div>
      <el-upload drag :auto-upload="false" :limit="1" accept=".xlsx" @change="pickImportFile" @remove="importFile = null">
        <el-icon class="upload-icon"><UploadFilled /></el-icon>
        <div>拖入 Excel 文件，或点击选择文件</div>
      </el-upload>
      <el-alert
        v-if="importResult"
        class="import-result"
        :type="importResult.failed_rows ? 'warning' : 'success'"
        :closable="false"
        :title="`处理 ${importResult.total_rows} 行：新建 ${importResult.created_rows}，更新 ${importResult.updated_rows}，未变化 ${importResult.unchanged_rows}，失败 ${importResult.failed_rows}`"
      />
      <el-table v-if="importResult?.errors.length" :data="importResult.errors" size="small" max-height="220">
        <el-table-column prop="row_no" label="行号" width="80" />
        <el-table-column prop="message" label="失败原因" />
      </el-table>
      <template #footer>
        <el-button @click="importVisible = false">关闭</el-button>
        <el-button type="primary" :disabled="!importFile" :loading="importing" @click="importLearners">开始导入</el-button>
      </template>
    </el-dialog>

    <el-card class="panel" shadow="never">
      <div class="form-section-head">
        <div>
          <h3>{{ editingId ? "编辑学员" : "新增学员" }}</h3>
          <p>{{ editingId ? `正在修改 ${form.current_name}` : "姓名和手机号用于证书归属及查询，请确认信息准确。" }}</p>
        </div>
        <el-tag v-if="editingId" type="warning">编辑中</el-tag>
      </div>
      <el-form class="form-grid" label-position="top">
        <el-form-item label="姓名">
          <el-input v-model.trim="form.current_name" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model.trim="form.phone" />
        </el-form-item>
        <el-form-item label="学员编号">
          <el-input v-model.trim="form.student_no" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="启用" value="active" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" class="wide">
          <el-input v-model.trim="form.remark" />
        </el-form-item>
        <div class="form-actions">
          <el-button :icon="RefreshLeft" @click="resetForm">重置</el-button>
          <el-button type="primary" :icon="editingId ? Check : Plus" @click="saveLearner">
            {{ editingId ? "保存修改" : "新增学员" }}
          </el-button>
        </div>
      </el-form>
    </el-card>

    <el-card class="panel" shadow="never">
      <div class="toolbar">
        <el-input v-model.trim="keyword" placeholder="按姓名、手机号、学员编号搜索" clearable @keyup.enter="loadLearners" />
        <el-button @click="loadLearners">搜索</el-button>
      </div>
      <el-table :data="learners" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="current_name" label="姓名" width="140" />
        <el-table-column prop="phone" label="手机号" width="160" />
        <el-table-column prop="student_no" label="学员编号" width="150" />
        <el-table-column prop="certificate_count" label="证书数量" width="100" align="center" />
        <el-table-column label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button size="small" @click="editLearner(row)">修改</el-button>
            <el-button size="small" type="danger" @click="deleteLearner(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </section>
</template>

<script setup lang="ts">
import { Check, Download, Plus, RefreshLeft, Upload, UploadFilled } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, type UploadFile } from "element-plus";
import { onMounted, reactive, ref } from "vue";

import { http, type Learner, type LearnerImportResult } from "../api";
import { apiErrorMessage, downloadFile } from "../download";

const learners = ref<Learner[]>([]);
const keyword = ref("");
const editingId = ref<number | null>(null);
const form = reactive({ current_name: "", phone: "", student_no: "", status: "active", remark: "" });
const importVisible = ref(false);
const importFile = ref<File | null>(null);
const importing = ref(false);
const importResult = ref<LearnerImportResult | null>(null);

function statusText(status: string) {
  return status === "active" ? "启用" : "停用";
}

async function loadLearners() {
  const { data } = await http.get<Learner[]>("/admin/learners", { params: { keyword: keyword.value || undefined } });
  learners.value = data;
}

function editLearner(row: Learner) {
  editingId.value = row.id;
  Object.assign(form, {
    current_name: row.current_name,
    phone: row.phone,
    student_no: row.student_no || "",
    status: row.status,
    remark: row.remark || "",
  });
}

function resetForm() {
  editingId.value = null;
  Object.assign(form, { current_name: "", phone: "", student_no: "", status: "active", remark: "" });
}

async function saveLearner() {
  if (!form.current_name || !form.phone) {
    ElMessage.warning("姓名和手机号必填");
    return;
  }
  const payload = { ...form, student_no: form.student_no || null, remark: form.remark || null };
  if (editingId.value) {
    await http.put(`/admin/learners/${editingId.value}`, payload);
  } else {
    await http.post("/admin/learners", payload);
  }
  ElMessage.success("学员已保存");
  resetForm();
  await loadLearners();
}

async function deleteLearner(row: Learner) {
  await ElMessageBox.confirm(`确认删除学员 ${row.current_name}？`, "删除学员", { type: "warning" });
  await http.delete(`/admin/learners/${row.id}`);
  ElMessage.success("学员已删除");
  await loadLearners();
}

function openImportDialog() {
  importFile.value = null;
  importResult.value = null;
  importVisible.value = true;
}

function downloadImportTemplate() {
  downloadFile("/admin/learners/import-template", "learner-import-template.xlsx");
}

function pickImportFile(file: UploadFile) {
  importFile.value = file.raw || null;
  importResult.value = null;
}

async function importLearners() {
  if (!importFile.value) return;
  importing.value = true;
  try {
    const body = new FormData();
    body.append("file", importFile.value);
    const { data } = await http.post<LearnerImportResult>("/admin/learners/import", body);
    importResult.value = data;
    ElMessage.success(data.failed_rows ? "导入完成，请检查失败行" : "学员导入完成");
    await loadLearners();
  } catch (error: any) {
    ElMessage.error(await apiErrorMessage(error, "学员导入失败"));
  } finally {
    importing.value = false;
  }
}

onMounted(loadLearners);
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.import-actions {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
}

.import-actions h3,
.import-actions p {
  margin: 0;
}

.import-actions p {
  margin-top: 6px;
  color: var(--app-muted);
  font-size: 13px;
}

.upload-icon {
  color: var(--app-primary);
  font-size: 36px;
}

.import-result {
  margin: 16px 0;
}

.panel {
  margin-bottom: 16px;
}

.wide {
  grid-column: span 2;
}

.toolbar {
  justify-content: flex-start;
}

.toolbar .el-input {
  max-width: 380px;
}

@media (max-width: 720px) {
  .wide {
    grid-column: 1;
  }
}
</style>
