<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :data-callback="dataCallback">
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="handleCreate"> 新增账号 </el-button>
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)"> 编辑 </el-button>
        <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>

    <UserDialog
      ref="userDialogRef"
      :law-firm-options="lawFirmOptions"
      :law-firm-loading="lawFirmLoading"
      :fetch-law-firms="fetchLawFirmOptions"
      @success="refreshTable"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import type { User } from "@/api/interface";
import { getUserList, addUser, editUser, deleteUser } from "@/api/modules/user";
import { getSelectList } from "@/api/modules/lawyer";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import UserDialog from "./components/UserDialog.vue";

const proTable = ref<ProTableInstance>();
const userDialogRef = ref<InstanceType<typeof UserDialog>>();
const lawFirmOptions = ref<{ label: string; value: string | number }[]>([]);
const lawFirmLoading = ref(false);
const lawFirmMap = ref<Record<string, string>>({});
type UserRow = Partial<User.ResUserList> & { userName?: string };

const statusOptions = [
  { label: "启用", value: 1 },
  { label: "禁用", value: 0 }
];

const columns = reactive<ColumnProps<User.ResUserList & { roleName?: string }>[]>([
  { type: "index", label: "序号", width: 60 },
  { prop: "userName", label: "登录账号", search: { el: "input", props: { placeholder: "请输入登录账号" } } },
  { prop: "userPassword", label: "登录密码" },
  { prop: "roleName", label: "关联律所" },
  {
    prop: "status",
    label: "账号状态",
    width: 100,
    enum: statusOptions,
    fieldNames: { label: "label", value: "value" },
    search: { el: "select", props: { placeholder: "请选择状态" } },
    tag: true
  },
  { prop: "remark", label: "备注", width: 220 },
  { prop: "createdTime", label: "创建时间", width: 200 },
  { prop: "operation", label: "操作", width: 150, fixed: "right" }
]);

const getTableList = (params: any) => {
  const tempParams = { ...params };
  tempParams.page = tempParams.pageNum;
  tempParams.size = tempParams.pageSize;
  delete tempParams.pageNum;
  delete tempParams.pageSize;
  return getUserList(tempParams);
};

const dataCallback = (data: any) => {
  const list = data;
  const total = data?.total ?? data?.records?.length ?? 0;
  const mappedList = list.map((item: any) => ({
    ...item,
    roleName: item.roleName || lawFirmMap.value[String(item.roleId)] || "-"
  }));
  return {
    list: mappedList,
    total
  };
};

const refreshTable = () => {
  proTable.value?.getTableList();
};

const handleCreate = () => {
  userDialogRef.value?.open({
    title: "新增账号",
    mode: "add",
    onSubmit: async payload => {
      await addUser(payload);
      ElMessage.success("新增账号成功");
    }
  });
};

const handleEdit = (row: UserRow) => {
  const editRow = { ...row };
  if (!editRow.roleId && editRow.roleName) {
    const target = lawFirmOptions.value.find(item => item.label === editRow.roleName);
    if (target) editRow.roleId = String(target.value);
  } else if (editRow.roleId && !editRow.roleName) {
    editRow.roleName = lawFirmMap.value[String(editRow.roleId)];
  }
  userDialogRef.value?.open({
    title: "编辑账号",
    mode: "edit",
    row: editRow,
    onSubmit: async payload => {
      await editUser(payload);
      ElMessage.success("编辑账号成功");
    }
  });
};

const handleDelete = (row: UserRow) => {
  if (!row?.id) {
    ElMessage.warning("未找到该账号的唯一标识，无法删除");
    return;
  }
  const displayName = row.userName ?? row.username ?? "";
  ElMessageBox.confirm(`确定删除账号「${displayName}」吗？`, "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  })
    .then(async () => {
      await deleteUser({ id: row.id });
      ElMessage.success("删除账号成功");
      refreshTable();
    })
    .catch(() => {});
};

const fetchLawFirmOptions = async (keyword = "") => {
  lawFirmLoading.value = true;
  try {
    const res: any = await getSelectList({ firmName: keyword });
    const list = res?.data || [];
    lawFirmOptions.value = list.map((item: any) => ({
      label: item.firmName,
      value: item.id
    }));
    if (list.length) {
      const map = { ...lawFirmMap.value };
      list.forEach((item: any) => {
        map[String(item.id)] = item.firmName;
      });
      lawFirmMap.value = map;
    }
  } catch (error) {
    console.error("获取律所列表失败", error);
    lawFirmOptions.value = [];
  } finally {
    lawFirmLoading.value = false;
  }
};

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

<style scoped lang="scss"></style>
