<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { useVbenModal, useVbenForm, Page } from '@vben/common-ui';
import { Button, Card, Space, Tag, Modal, message } from 'ant-design-vue';
import { ref } from 'vue';
import dayjs from 'dayjs';
import type { UserInfo } from '#/model/admin.user';
import {
  getAdminListApi,
  addAdminApi,
  editAdminApi,
  deleteAdminApi,
} from '#/api/core/admin.user';

const ROLE_MAP: Record<number, { label: string; color: string }> = {
  0: { label: '超级管理员', color: 'red' },
  1: { label: '管理员', color: 'blue' },
  2: { label: '普通用户', color: 'green' },
  99: { label: '外包翻译', color: 'orange' },
};

const editingId = ref<number | undefined>(undefined);

const [Form, FormApi] = useVbenForm({
  layout: 'horizontal',
  wrapperClass: 'grid-cols-2',
  showDefaultActions: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'username',
      label: '用户名',
      formItemClass: 'col-span-1',
      rules: 'required',
      componentProps: { placeholder: '登录用户名' },
    },
    {
      component: 'InputPassword',
      fieldName: 'password',
      label: '密码',
      formItemClass: 'col-span-1',
      componentProps: { placeholder: '留空则不修改密码' },
    },
    {
      component: 'Input',
      fieldName: 'real_name',
      label: '真实姓名',
      formItemClass: 'col-span-1',
      componentProps: { placeholder: '真实姓名' },
    },
    {
      component: 'Input',
      fieldName: 'nickname',
      label: '昵称',
      formItemClass: 'col-span-1',
      componentProps: { placeholder: '昵称' },
    },
    {
      component: 'Input',
      fieldName: 'phone',
      label: '手机号',
      formItemClass: 'col-span-1',
      componentProps: { placeholder: '手机号' },
    },
    {
      component: 'Input',
      fieldName: 'email',
      label: '邮箱',
      formItemClass: 'col-span-1',
      componentProps: { placeholder: '邮箱地址' },
    },
    {
      component: 'Select',
      fieldName: 'role',
      label: '角色',
      formItemClass: 'col-span-1',
      defaultValue: 1,
      rules: 'required',
      componentProps: {
        options: [
          { label: '超级管理员', value: 0 },
          { label: '管理员', value: 1 },
          { label: '普通用户', value: 2 },
          { label: '外包翻译', value: 99 },
        ],
      },
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: '状态',
      formItemClass: 'col-span-1',
      defaultValue: 1,
      rules: 'required',
      componentProps: {
        options: [
          { label: '正常', value: 1 },
          { label: '禁用', value: 0 },
        ],
      },
    },
    {
      component: 'Input',
      fieldName: 'group',
      label: '用户组',
      formItemClass: 'col-span-2',
      componentProps: { placeholder: '用户组标识（可选）' },
    },
    {
      component: 'Textarea',
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2',
      componentProps: { rows: 3 },
    },
  ],
});

const [FormModal, FormModalApi] = useVbenModal({
  confirmText: '保存',
  onConfirm: async () => {
    const { valid } = await FormApi.validate();
    if (!valid) return;
    const values = await FormApi.getValues();
    const params: UserInfo = {
      id: editingId.value,
      username: values.username,
      password: values.password || '',
      real_name: values.real_name,
      nickname: values.nickname,
      phone: values.phone,
      email: values.email,
      role: values.role,
      status: values.status,
      group: values.group,
      remark: values.remark,
    };
    if (editingId.value) {
      await editAdminApi(params);
      message.success('更新成功');
    } else {
      if (!params.password) {
        message.error('新增用户必须填写密码');
        return;
      }
      await addAdminApi(params);
      message.success('新增成功');
    }
    FormModalApi.close();
    GridApi.reload();
  },
});

const gridOptions: VxeGridProps<UserInfo> = {
  columns: [
    { field: 'id', title: 'ID', width: 60 },
    { field: 'username', title: '用户名', width: 120 },
    { field: 'real_name', title: '真实姓名', width: 110 },
    { field: 'nickname', title: '昵称', width: 110 },
    { field: 'phone', title: '手机号', width: 130 },
    {
      field: 'role',
      title: '角色',
      width: 120,
      slots: { default: 'roleSlot' },
    },
    {
      field: 'status',
      title: '状态',
      width: 90,
      slots: { default: 'statusSlot' },
    },
    {
      field: 'lastLoginTime',
      title: '最后登录',
      minWidth: 160,
      slots: { default: 'loginTimeSlot' },
    },
    { field: 'lastLoginIp', title: '登录IP', width: 130 },
    { field: 'remark', title: '备注', minWidth: 120 },
    { fixed: 'right', slots: { default: 'actionSlot' }, title: '操作', width: 160 },
  ],
  minHeight: 650,
  autoResize: true,
  pagerConfig: {},
  proxyConfig: {
    response: { result: 'data', total: 'total' },
    ajax: {
      query: async () => {
        return await getAdminListApi();
      },
    },
  },
  rowConfig: { isHover: true },
};

const [Grid, GridApi] = useVbenVxeGrid({ gridOptions });

function openCreate() {
  editingId.value = undefined;
  FormApi.resetForm();
  FormModalApi.setState({ title: '新增管理员' });
  FormModalApi.open();
}

function openEdit(row: UserInfo) {
  editingId.value = row.id;
  FormApi.setValues({
    username: row.username,
    password: '',
    real_name: row.real_name,
    nickname: row.nickname,
    phone: row.phone,
    email: row.email,
    role: row.role,
    status: row.status,
    group: row.group,
    remark: row.remark,
  });
  FormModalApi.setState({ title: `编辑管理员 - ${row.username}` });
  FormModalApi.open();
}

function handleDelete(row: UserInfo) {
  Modal.confirm({
    title: '删除确认',
    content: `确认删除管理员「${row.username}」吗？此操作不可撤销。`,
    okType: 'danger',
    async onOk() {
      await deleteAdminApi(row.id!);
      message.success('删除成功');
      GridApi.reload();
    },
  });
}

function formatTime(ts: number | undefined) {
  if (!ts) return '-';
  return dayjs.unix(ts).format('YYYY-MM-DD HH:mm');
}
</script>

<template>
  <Page auto-content-height>
    <FormModal>
      <Form />
    </FormModal>

    <Card class="mb-4">
      <template #title>管理员列表</template>
      <template #extra>
        <Button type="primary" @click="openCreate">新增管理员</Button>
      </template>
    </Card>

    <Grid>
      <template #roleSlot="{ row }">
        <Tag :color="ROLE_MAP[row.role]?.color ?? 'default'">
          {{ ROLE_MAP[row.role]?.label ?? `角色${row.role}` }}
        </Tag>
      </template>
      <template #statusSlot="{ row }">
        <Tag :color="row.status === 1 ? 'green' : 'red'">
          {{ row.status === 1 ? '正常' : '禁用' }}
        </Tag>
      </template>
      <template #loginTimeSlot="{ row }">
        {{ formatTime(row.lastLoginTime) }}
      </template>
      <template #actionSlot="{ row }">
        <Space>
          <Button size="small" type="primary" @click="openEdit(row)">编辑</Button>
          <Button danger size="small" @click="handleDelete(row)">删除</Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
