<template>
  <PageContainer title="用户管理">
    <QueryToolbar>
      <el-input
        v-model="keyword"
        placeholder="搜索姓名/手机号/邮箱"
        clearable
        class="w-input-md"
        @keyup.enter="handleSearch"
      />
      <el-button @click="handleSearch">搜索</el-button>
      <el-button @click="handleResetSearch">重置搜索</el-button>
      <!-- <el-checkbox v-model="includeDeleted" @change="handleDeletedToggle">包含已删除</el-checkbox> -->
      <el-button
        v-if="canImportUser"
        @click="openImportDialog"
      >
        批量导入
      </el-button>
      <el-button
        v-if="canImportUser"
        @click="downloadUserTemplate"
      >
        下载模板
      </el-button>
      <el-button
        v-if="canCreateUser"
        type="primary"
        @click="openCreateDrawer"
      >
        新增
      </el-button>
      <el-button @click="load">刷新</el-button>
    </QueryToolbar>
    <el-table :data="rows" class="mt-md" empty-text="暂无数据">
      <el-table-column prop="userName" label="姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="roleNames" label="角色信息" width="180">
        <template #default="{ row }">
          <span>{{ row.roleNames || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" :formatter="statusFormatter" />
      <!-- <el-table-column label="删除标记" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.deleted" type="danger" size="small">已删除</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column> -->
      <el-table-column label="账号有效期" width="340">
        <template #default="{ row }">
          <span>{{ row.validFrom || "-" }} ~ {{ row.validTo || "-" }}</span>
          <el-tag v-if="isExpired(row.validTo)" type="danger" size="small" class="ml-sm">已过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用户操作" width="360">
        <template #default="{ row }">
          <el-button
            v-if="canUpdateUser"
            size="small"
            type="primary"
            @click="openEditDrawer(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="canEnableUser"
            size="small"
            type="success"
            :disabled="row.status === 'ENABLED'"
            @click="handleEnable(row.id)"
          >
            启用
          </el-button>
          <el-button
            v-if="canDisableUser"
            size="small"
            type="warning"
            :disabled="row.status !== 'ENABLED'"
            @click="handleDisable(row.id)"
          >
            禁用
          </el-button>
          <el-button
            v-if="canResetPassword"
            size="small"
            @click="handleResetPassword(row.id)"
          >
            重置密码
          </el-button>
          <el-button
            v-if="canReadRoleHistory"
            size="small"
            @click="handleViewRoleHistory(row.id)"
          >
            角色历史
          </el-button>
          <el-button
            v-if="canManageDelegation"
            size="small"
            @click="openDelegation(row.id)"
          >
            代理授权
          </el-button>
          <el-button
            v-if="canDeleteUser && row.status === 'DISABLED'"
            size="small"
            type="danger"
            @click="handleDeleteUser(row.id, row.userName)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex-end mt-md">
      <el-pagination
        :current-page="pageNo"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
      />
    </div>

    <el-drawer v-model="createVisible" :title="drawerTitle" :size="DRAWER_SIZE.md" destroy-on-close>
      <el-form ref="formRef" :model="form" label-position="left" :label-width="LABEL_WIDTH.md" :rules="formRules">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" show-password />
          <PasswordStrengthBar :password="form.password" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="生效时间">
          <el-date-picker
            v-model="form.validFrom"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择生效时间"
          />
        </el-form-item>
        <el-form-item label="失效时间">
          <el-date-picker
            v-model="form.validTo"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择失效时间"
          />
        </el-form-item>
        <el-form-item label="角色分配" v-if="canReadRole">
          <el-select v-model="form.roleId" placeholder="请选择角色" clearable class="w-full">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createVisible = false">取消</el-button>
        <el-button
          v-if="isEditMode ? canUpdateUser : canCreateUser"
          type="primary"
          @click="handleSubmitUser"
        >
          {{ isEditMode ? "保存" : "创建" }}
        </el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="historyVisible" title="角色变更历史" :width="DIALOG_WIDTH.md">
      <el-table :data="historyRows" empty-text="暂无数据">
        <el-table-column prop="oldRoleId" label="旧角色" width="140" :formatter="roleNameFormatter" />
        <el-table-column prop="newRoleId" label="新角色" width="140" :formatter="roleNameFormatter" />
        <el-table-column prop="actionType" label="动作" width="120" :formatter="statusFormatter" />
        <el-table-column prop="createdAt" label="时间" />
      </el-table>
    </el-dialog>
    <el-dialog v-model="delegationVisible" title="代理授权管理" :width="DIALOG_WIDTH.lg">
      <el-form ref="delegationFormRef" :inline="true" :model="delegationForm" label-position="left" :rules="delegationFormRules">
        <el-form-item label="代理人" prop="delegateUserId">
          <el-select v-model="delegationForm.delegateUserId" class="w-input-md" filterable clearable>
            <el-option v-for="u in rows" :key="u.id" :label="`${u.userName}(${u.phone})`" :value="u.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间">
          <el-date-picker
            v-model="delegationForm.effectiveFrom"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择生效时间"
          />
        </el-form-item>
        <el-form-item label="失效时间">
          <el-date-picker
            v-model="delegationForm.effectiveTo"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择失效时间"
          />
        </el-form-item>
        <el-form-item label="原因">
          <el-input v-model="delegationForm.reason" class="w-input-sm" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreateDelegation">新增授权</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="delegationRows" empty-text="暂无数据">
        <el-table-column prop="delegateUserId" label="代理人" width="140" :formatter="userNameFormatter" />
        <el-table-column prop="effectiveFrom" label="生效时间" width="170" />
        <el-table-column prop="effectiveTo" label="失效时间" width="170" />
        <el-table-column prop="status" label="状态" width="100" :formatter="statusFormatter" />
        <el-table-column prop="reason" label="原因" />
        <el-table-column prop="disabledReason" label="停用原因" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              size="small"
              type="warning"
              :disabled="row.status === 'DISABLED' || row.status === 'EXPIRED'"
              @click="handleDisableDelegation(row.id)"
            >
              停用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog v-model="importVisible" title="批量导入用户" :width="DIALOG_WIDTH.lg" destroy-on-close>
      <div class="text-secondary mb-sm">
        支持 `.csv` 或制表符文本。模板字段顺序为：
        `userName, phone, password, email, validFrom, validTo, roleCode`
      </div>
      <div v-if="roles.length" class="text-secondary mb-sm">
        可用角色编码：{{ roles.map((item: any) => item.roleCode).filter(Boolean).join("、") || "-" }}
      </div>
      <el-upload
        :auto-upload="false"
        :show-file-list="false"
        accept=".csv,.txt"
        :on-change="handleImportFileChange"
      >
        <el-button>选择文件</el-button>
      </el-upload>
      <div v-if="importFileName" class="mt-sm text-secondary">已选择文件：{{ importFileName }}</div>
      <el-input
        v-model="importText"
        type="textarea"
        :rows="10"
        class="mt-md"
        placeholder="可直接粘贴 CSV 内容，首行需包含表头"
        @input="syncImportPreview"
      />
      <div v-if="importPreview.length" class="mt-md">
        <div class="mb-sm">预览前 {{ importPreview.length }} 行：</div>
        <el-table :data="importPreview" size="small" max-height="240">
          <el-table-column prop="userName" label="姓名" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="roleCode" label="角色编码" />
        </el-table>
      </div>
      <div v-if="lastImportResult" class="mt-md">
        <el-alert
          :title="`导入结果：成功 ${lastImportResult.success} 条，失败 ${lastImportResult.failed} 条`"
          :type="lastImportResult.failed ? 'warning' : 'success'"
          show-icon
          :closable="false"
        />
        <el-button
          v-if="lastImportResult.errors?.length"
          class="mt-sm"
          @click="downloadUserErrorSnapshot"
        >
          下载失败快照
        </el-button>
        <el-table v-if="lastImportResult.errors?.length" :data="lastImportResult.errors" size="small" class="mt-sm" max-height="220">
          <el-table-column prop="rowNo" label="行号" width="90" />
          <el-table-column prop="identifier" label="标识" width="220" />
          <el-table-column prop="message" label="失败原因" />
        </el-table>
      </div>
      <template #footer>
        <el-button @click="importVisible = false">关闭</el-button>
        <el-button @click="downloadUserTemplate">下载模板</el-button>
        <el-button type="primary" :loading="importLoading" @click="submitImportUsers">开始导入</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import PageContainer from "../../components/PageContainer.vue";
import QueryToolbar from "../../components/QueryToolbar.vue";
import PasswordStrengthBar from "../../components/PasswordStrengthBar.vue";
import { DRAWER_SIZE, DIALOG_WIDTH, LABEL_WIDTH } from "../../constants/ui";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
  assignUserRole,
  batchImportUsers,
  createUser,
  updateUser,
  createUserDelegation,
  deleteUser,
  disableUser,
  disableUserDelegation,
  enableUser,
  fetchRoles,
  fetchUserDelegations,
  fetchUserRoleHistory,
  fetchUsers,
  resetUserPassword,
} from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhStatus } from "../../utils/status";
import { downloadCsvRows, downloadCsvTemplate, findMissingHeaders, parseDelimitedText, readTextFile } from "../../utils/batchImport";

const rows = ref<any[]>([]);
const roles = ref<any[]>([]);
const pageNo = ref(1);
const pageSize = ref(20);
const total = ref(0);
const includeDeleted = ref(false);
const keyword = ref("");
const authStore = useAuthStore();
const canReadUser = computed(() => authStore.hasPermission(PERMS.user.read));
const canCreateUser = computed(() => authStore.hasPermission(PERMS.user.create));
const canImportUser = computed(() => authStore.hasPermission(PERMS.user.import));
const canUpdateUser = computed(() => authStore.hasPermission(PERMS.user.update));
const canReadRole = computed(() => authStore.hasPermission(PERMS.role.read));
const canEnableUser = computed(() => authStore.hasPermission(PERMS.user.enable));
const canDisableUser = computed(() => authStore.hasPermission(PERMS.user.disable));
const canDeleteUser = computed(() => authStore.hasPermission(PERMS.user.delete));
const canResetPassword = computed(() => authStore.hasPermission(PERMS.user.resetPassword));
const canReadRoleHistory = computed(() => authStore.hasPermission(PERMS.user.roleHistoryRead));
const canManageDelegation = computed(() => authStore.hasPermission(PERMS.user.delegationManage));
const createVisible = ref(false);
const isEditMode = ref(false);
const editingUserId = ref<number | null>(null);
const historyVisible = ref(false);
const historyRows = ref<any[]>([]);
const delegationVisible = ref(false);
const delegationRows = ref<any[]>([]);
const delegationUserId = ref<number | null>(null);
const importVisible = ref(false);
const importLoading = ref(false);
const importText = ref("");
const importFileName = ref("");
const importPreview = ref<Array<{ userName: string; phone: string; email: string; roleCode: string }>>([]);
const lastImportResult = ref<any | null>(null);
const lastImportedUsers = ref<Array<{
  userName: string;
  phone: string;
  password: string;
  email: string;
  validFrom: string;
  validTo: string;
  roleCode: string;
}> | null>(null);
const delegationForm = ref({
  delegateUserId: undefined as number | undefined,
  effectiveFrom: "",
  effectiveTo: "",
  reason: "",
});
const form = ref({
  userName: "测试用户",
  phone: "13800000000",
  password: "123456",
  email: "test@example.com",
  validFrom: "",
  validTo: "",
  roleId: undefined as number | undefined,
});

const formRef = ref<FormInstance>();
const delegationFormRef = ref<FormInstance>();
const route = useRoute();
const router = useRouter();

const formRules = computed<FormRules>(() => ({
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  password: [{ required: !isEditMode.value, message: "请输入密码", trigger: "blur" }],
}));

const delegationFormRules = reactive<FormRules>({
  delegateUserId: [{ required: true, message: "请选择代理人", trigger: "change" }],
});

const drawerTitle = computed(() => (isEditMode.value ? "编辑用户" : "新增用户"));
const statusFormatter = (_row: any, _column: any, value: unknown) => toZhStatus(value);
const roleNameFormatter = (_row: any, _column: any, value: unknown) => {
  const roleId = Number(value || 0);
  if (!roleId) {
    return "-";
  }
  const role = roles.value.find((x: any) => Number(x?.id || 0) === roleId);
  return role?.roleName || `角色#${roleId}`;
};
const userNameFormatter = (_row: any, _column: any, value: unknown) => {
  const userId = Number(value || 0);
  if (!userId) {
    return "-";
  }
  const user = rows.value.find((x: any) => Number(x?.id || 0) === userId);
  return user?.userName || user?.phone || `用户#${userId}`;
};

const openCreateDrawer = () => {
  form.value = {
    userName: "测试用户",
    phone: "13800000000",
    password: "123456",
    email: "test@example.com",
    validFrom: "",
    validTo: "",
    roleId: undefined,
  };
  isEditMode.value = false;
  editingUserId.value = null;
  createVisible.value = true;
};

const openImportDialog = () => {
  importVisible.value = true;
  importText.value = "";
  importFileName.value = "";
  importPreview.value = [];
  lastImportResult.value = null;
  lastImportedUsers.value = null;
};

const openEditDrawer = (row: any) => {
  form.value = {
    userName: row.userName,
    phone: row.phone,
    password: "",
    email: row.email,
    validFrom: row.validFrom,
    validTo: row.validTo,
    roleId: row.roleId as number | undefined,
  };
  isEditMode.value = true;
  editingUserId.value = row.id ?? null;
  createVisible.value = true;
};

const load = async () => {
  if (!canReadUser.value) {
    rows.value = [];
    total.value = 0;
    return;
  }
  const resp = await fetchUsers({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    includeDeleted: includeDeleted.value,
    keyword: keyword.value.trim() || undefined,
  });
  rows.value = resp?.data?.list || [];
  total.value = Number(resp?.data?.total || 0);
  if (canReadRole.value) {
    const roleResp = await fetchRoles();
    roles.value = roleResp?.data?.list || [];
  }
};

const handlePageChange = (page: number) => {
  pageNo.value = page;
  load();
};

const handlePageSizeChange = (size: number) => {
  pageSize.value = size;
  pageNo.value = 1;
  load();
};

const handleDeletedToggle = () => {
  pageNo.value = 1;
  load();
};

const syncKeywordFromRoute = async () => {
  const nextKeyword = String(route.query.keyword || "").trim();
  if (keyword.value !== nextKeyword) {
    keyword.value = nextKeyword;
  }
  pageNo.value = 1;
  await load();
};

const pushKeywordQuery = async () => {
  const nextKeyword = keyword.value.trim();
  const nextQuery = { ...route.query } as Record<string, any>;
  if (nextKeyword) {
    nextQuery.keyword = nextKeyword;
  } else {
    delete nextQuery.keyword;
  }
  await router.push({ path: route.path, query: nextQuery });
};

const handleSearch = async () => {
  pageNo.value = 1;
  await pushKeywordQuery();
};

const handleResetSearch = async () => {
  keyword.value = "";
  pageNo.value = 1;
  await pushKeywordQuery();
};

const downloadUserTemplate = () => {
  downloadCsvTemplate("user-import-template.csv", [
    "userName",
    "phone",
    "password",
    "email",
    "validFrom",
    "validTo",
    "roleCode",
  ], [
    ["张三", "13800138000", "Abc12345!", "zhangsan@example.com", "2026-04-20 09:00:00", "2099-12-31 23:59:59", "TENANT_ADMIN"],
  ]);
};

const handleImportFileChange = async (uploadFile: any) => {
  const file = uploadFile?.raw as File | undefined;
  if (!file) {
    return;
  }
  importFileName.value = file.name;
  importText.value = await readTextFile(file);
  syncImportPreview();
};

const syncImportPreview = () => {
  const rows = parseUserImportRows(importText.value);
  importPreview.value = rows.slice(0, 5).map((item) => ({
    userName: item.userName,
    phone: item.phone,
    email: item.email || "",
    roleCode: item.roleCode || "",
  }));
};

const parseUserImportRows = (text: string) => {
  const rows = parseDelimitedText(text);
  if (!rows.length) {
    return [];
  }
  const [header, ...dataRows] = rows;
  const missingHeaders = findMissingHeaders(header, ["userName", "phone", "password"]);
  if (missingHeaders.length) {
    return [];
  }
  const headerIndex = new Map<string, number>();
  header.forEach((name, index) => {
    headerIndex.set(String(name || "").trim(), index);
  });
  return dataRows
    .filter((row) => row.some((cell) => String(cell || "").trim().length > 0))
    .map((row) => ({
      userName: row[headerIndex.get("userName") ?? 0] || "",
      phone: row[headerIndex.get("phone") ?? 1] || "",
      password: row[headerIndex.get("password") ?? 2] || "",
      email: row[headerIndex.get("email") ?? 3] || "",
      validFrom: row[headerIndex.get("validFrom") ?? 4] || "",
      validTo: row[headerIndex.get("validTo") ?? 5] || "",
      roleCode: row[headerIndex.get("roleCode") ?? 6] || "",
    }))
    .map((item) => ({
      ...item,
      userName: item.userName.trim(),
      phone: item.phone.trim(),
      password: item.password.trim(),
      email: item.email.trim(),
      validFrom: item.validFrom.trim(),
      validTo: item.validTo.trim(),
      roleCode: item.roleCode.trim(),
    }));
};

const validateUserImportHeaders = (text: string) => {
  const rows = parseDelimitedText(text);
  if (!rows.length) {
    return { ok: false, missingHeaders: ["userName", "phone", "password"] };
  }
  const [header] = rows;
  const missingHeaders = findMissingHeaders(header, ["userName", "phone", "password"]);
  return { ok: missingHeaders.length === 0, missingHeaders };
};

const submitImportUsers = async () => {
  const headerValidation = validateUserImportHeaders(importText.value);
  if (!headerValidation.ok) {
    ElMessage.warning(`模板表头缺失：${headerValidation.missingHeaders.join("、")}`);
    return;
  }
  const users = parseUserImportRows(importText.value);
  if (!users.length) {
    ElMessage.warning("请先上传或粘贴导入内容");
    return;
  }
  lastImportedUsers.value = users;
  importLoading.value = true;
  try {
    const resp = await batchImportUsers({ users });
    lastImportResult.value = resp?.data || null;
    if ((resp?.data?.failed || 0) > 0) {
      ElMessage.warning(`导入完成：成功 ${resp?.data?.success || 0} 条，失败 ${resp?.data?.failed || 0} 条`);
    } else {
      ElMessage.success(`导入完成：成功 ${resp?.data?.success || 0} 条`);
    }
    await load();
  } finally {
    importLoading.value = false;
  }
};

const downloadUserErrorSnapshot = () => {
  const errors = lastImportResult.value?.errors || [];
  const sourceRows = lastImportedUsers.value || [];
  if (!errors.length || !sourceRows.length) {
    ElMessage.warning("暂无失败快照可下载");
    return;
  }
  const rows: string[][] = [[
    "userName",
    "phone",
    "password",
    "email",
    "validFrom",
    "validTo",
    "roleCode",
    "__error",
  ]];
  errors.forEach((error: any) => {
    const rowIndex = Number(error?.rowNo || 0) - 2;
    const item = sourceRows[rowIndex];
    if (!item) {
      return;
    }
    rows.push([
      item.userName || "",
      item.phone || "",
      item.password || "",
      item.email || "",
      item.validFrom || "",
      item.validTo || "",
      item.roleCode || "",
      String(error?.message || ""),
    ]);
  });
  downloadCsvRows("user-import-error-snapshot.csv", rows);
};

const handleSubmitUser = async () => {
  if (!formRef.value) return;
  const valid = await formRef.value.validate().catch(() => false);
  if (!valid) return;

  if (isEditMode.value && editingUserId.value) {
    const payload: {
      userName: string;
      phone: string;
      email?: string;
      validFrom?: string;
      validTo?: string;
      password?: string;
    } = {
      userName: form.value.userName,
      phone: form.value.phone,
      email: form.value.email,
      validFrom: form.value.validFrom,
      validTo: form.value.validTo,
    };
    if (form.value.password) {
      payload.password = form.value.password;
    }
    await updateUser(editingUserId.value, payload);
    if (form.value.roleId) {
      await assignUserRole({ userId: editingUserId.value, roleId: form.value.roleId });
    }
    ElMessage.success("用户已更新");
  } else {
    const payload = {
      userName: form.value.userName,
      phone: form.value.phone,
      password: form.value.password,
      email: form.value.email,
      validFrom: form.value.validFrom,
      validTo: form.value.validTo,
    };
    const createdResp = await createUser(payload);
    const createdUserId = createdResp?.data?.id;
    if (form.value.roleId && createdUserId) {
      await assignUserRole({ userId: createdUserId, roleId: form.value.roleId });
    }
    ElMessage.success("用户创建成功");
  }
  createVisible.value = false;
  await load();
};

const handleEnable = async (userId: number) => {
  await enableUser(userId);
  ElMessage.success("用户已启用");
  await load();
};

const handleDisable = async (userId: number) => {
  await disableUser(userId);
  ElMessage.success("用户已禁用");
  await load();
};

const handleDeleteUser = async (userId: number, userName: string) => {
  await ElMessageBox.confirm(`确认删除用户「${userName}」？删除后不可恢复。`, "删除用户", {
    type: "warning",
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
  });
  await deleteUser(userId);
  ElMessage.success("用户已删除");
  await load();
};

const handleResetPassword = async (userId: number) => {
  const dialog = await ElMessageBox.prompt("请输入新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: "123456",
  }).catch(() => null);
  if (!dialog) {
    return;
  }
  await resetUserPassword(userId, { newPassword: dialog.value });
  ElMessage.success("密码已重置");
};

const handleViewRoleHistory = async (userId: number) => {
  const resp = await fetchUserRoleHistory(userId);
  historyRows.value = resp?.data?.list || [];
  historyVisible.value = true;
};

const openDelegation = async (userId: number) => {
  delegationUserId.value = userId;
  delegationVisible.value = true;
  await loadDelegations();
};

const loadDelegations = async () => {
  if (!delegationUserId.value) {
    delegationRows.value = [];
    return;
  }
  const resp = await fetchUserDelegations(delegationUserId.value);
  delegationRows.value = resp?.data?.list || [];
};

const handleCreateDelegation = async () => {
  if (!delegationFormRef.value) return;
  const valid = await delegationFormRef.value.validate().catch(() => false);
  if (!valid) return;

  if (!delegationUserId.value) {
    return;
  }
  await createUserDelegation(delegationUserId.value, {
    delegateUserId: delegationForm.value.delegateUserId,
    effectiveFrom: delegationForm.value.effectiveFrom,
    effectiveTo: delegationForm.value.effectiveTo,
    reason: delegationForm.value.reason,
  });
  ElMessage.success("代理授权创建成功");
  await loadDelegations();
};

const handleDisableDelegation = async (id: number) => {
  const dialog = await ElMessageBox.prompt("请输入停用原因", "停用代理授权", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: "手动停用",
  }).catch(() => null);
  if (!dialog) {
    return;
  }
  await disableUserDelegation(id, { reason: dialog.value });
  ElMessage.success("代理授权已停用");
  await loadDelegations();
};

const isExpired = (validTo?: string) => {
  if (!validTo) {
    return false;
  }
  const end = new Date(validTo.replace(" ", "T"));
  if (Number.isNaN(end.getTime())) {
    return false;
  }
  return end.getTime() < Date.now();
};

watch(
  () => route.query.keyword,
  () => {
    syncKeywordFromRoute();
  },
);

onMounted(async () => {
  await syncKeywordFromRoute();
});
</script>
