<script lang="ts" setup>
import { get, post } from "@/common/http/request";
import DefaultToolButton from "@/components/base/default-tool-button/DefaultToolButton.vue";
import StatusSwitch from "@/components/base/base-switch/StatusSwitch.vue";
import UserFormDialog from "./UserFormDialog.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DefaultStatusSwitchColumn from "@/components/base/default-column/DefaultStatusSwitchColumn.vue";
import DefaultOperateButtonColumn from "@/components/base/default-column/DefaultOperateButtonColumn.vue";

const url = "/api/sys/sysuser/getSysUserPage";
const menu = "sysuser";

const tableRef = ref();
const formDialogVisible = ref(false);
const isEdit = ref(false);
const currentRow = ref<Record<string, any>>({});

const searchers = [
  { name: "loginName", type: "text" as const, placeholder: "请输入账号" },
  { name: "userName", type: "text" as const, placeholder: "请输入姓名" },
];

const userTypeMap: Record<number, string> = {
  0: "普通用户",
  5: "系统管理员",
};

const getUserTypeLabel = (type: number) => userTypeMap[type] || "未知";

const addClick = () => {
  isEdit.value = false;
  currentRow.value = {
    loginName: "",
    userName: "",
    passWord: "",
    confirmPassword: "",
    userType: 0,
    roleIds: [],
    status: 1,
  };
  formDialogVisible.value = true;
};

const editClick = (row: Record<string, any>) => {
  isEdit.value = true;
  currentRow.value = {
    ...row,
    passWord: "",
    confirmPassword: "",
    roleIds: row.roleIds || [],
  };
  formDialogVisible.value = true;
};

const deleteClick = async (row: Record<string, any>) => {
  try {
    await ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await post("/api/sys/sysuser/deleteSysUser", { id: row.id });
    ElMessage.success("删除成功");
    tableRef.value?.refresh();
  } catch (error) {
    // 用户取消删除
  }
};

const handleStatusChange = async (row: Record<string, any>) => {
  try {
    await post("/api/sys/sysuser/setStatus", {
      id: row.id,
      status: row.status,
    });
    ElMessage.success("状态修改成功");
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1;
  }
};

const handleSuccess = () => {
  tableRef.value?.refresh();
};

const getDialogTitle = computed(() => (isEdit.value ? "编辑用户" : "新建用户"));

// 通用状态标签类型映射（启用/禁用）
const getCommonStatusTagType = (code: number | null): string => {
  const tagTypeMap: Record<number, string> = {
    0: "success", // 启用
    1: "info", // 禁用
  };
  return tagTypeMap[code ?? -1] || "info";
};
</script>
<template>
  <BasePageableTable ref="tableRef" :url="url" :searchers="searchers">
    <template #tool-button>
      <DefaultToolButton :add-click="addClick" :menu="menu" />
    </template>
    <template #columns>
      <el-table-column type="selection" width="40" />
      <el-table-column label="账号" prop="loginName" min-width="120" />
      <el-table-column label="姓名" prop="userName" min-width="120" />
      <el-table-column label="角色" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.roleNames || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="用户类型" prop="userType" min-width="100">
        <template #default="{ row }">
          {{ getUserTypeLabel(row.userType) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createDate" min-width="160" />
      <DefaultStatusSwitchColumn :tag-type-mapping="getCommonStatusTagType" />
      <DefaultOperateButtonColumn />
    </template>
  </BasePageableTable>

  <UserFormDialog
    v-model:visible="formDialogVisible"
    v-model:is-edit="isEdit"
    v-model:form-data="currentRow"
    :title="getDialogTitle"
    @success="handleSuccess"
  />
</template>
