<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 {
  getPermissionListApi,
  addPermissionApi,
  editPermissionApi,
  deletePermissionApi,
} from '#/api/core/permission';
import type { PermissionApi } from '#/api/core/permission';
import { Button, Card, Space, Tag, Modal, message } from 'ant-design-vue';
import { ref } from 'vue';

const HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'];

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

const [Form, FormApi] = useVbenForm({
  layout: 'horizontal',
  wrapperClass: 'grid-cols-2',
  showDefaultActions: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'permission_code',
      label: '权限编码',
      formItemClass: 'col-span-2',
      rules: 'required',
      componentProps: { placeholder: '例如：AC0004' },
    },
    {
      component: 'Input',
      fieldName: 'permission_name',
      label: '权限名称',
      formItemClass: 'col-span-2',
      rules: 'required',
      componentProps: { placeholder: '例如：编辑活动' },
    },
    {
      component: 'Input',
      fieldName: 'permission_group',
      label: '权限分组',
      formItemClass: 'col-span-2',
      componentProps: { placeholder: '例如：activity' },
    },
    {
      component: 'Input',
      fieldName: 'api_path',
      label: '接口路径',
      formItemClass: 'col-span-2',
      componentProps: { placeholder: '例如：/api/activity/edit' },
    },
    {
      component: 'Select',
      fieldName: 'http_method',
      label: '请求方法',
      formItemClass: 'col-span-2',
      componentProps: {
        allowClear: true,
        options: HTTP_METHODS.map((m) => ({ label: m, value: m })),
      },
    },
    {
      component: 'Select',
      fieldName: 'status',
      label: '状态',
      formItemClass: 'col-span-2',
      defaultValue: 1,
      componentProps: {
        options: [
          { label: '启用', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
    },
    {
      component: 'Textarea',
      fieldName: 'remark',
      label: '备注',
      formItemClass: 'col-span-2',
      componentProps: { rows: 3 },
    },
  ],
});

const [FormModal, FormModalApi] = useVbenModal({
  confirmText: '保存',
  onConfirm: async () => {
    const values = await FormApi.getValues();
    const params: PermissionApi.Permission = {
      id: editingId.value,
      permission_code: values.permission_code,
      permission_name: values.permission_name,
      permission_group: values.permission_group,
      api_path: values.api_path,
      http_method: values.http_method,
      status: values.status,
      remark: values.remark,
    };
    if (editingId.value) {
      await editPermissionApi(params);
      message.success('更新成功');
    } else {
      await addPermissionApi(params);
      message.success('新增成功');
    }
    FormModalApi.close();
    GridApi.reload();
  },
});

const METHOD_COLORS: Record<string, string> = {
  GET: 'green',
  POST: 'blue',
  PUT: 'orange',
  DELETE: 'red',
  PATCH: 'purple',
};

const gridOptions: VxeGridProps<PermissionApi.Permission> = {
  columns: [
    { field: 'id', title: 'ID', width: 80 },
    { field: 'permission_code', title: '权限编码', width: 130 },
    { field: 'permission_name', title: '权限名称', minWidth: 150 },
    { field: 'permission_group', title: '分组', width: 120 },
    { field: 'api_path', title: '接口路径', minWidth: 200 },
    {
      field: 'http_method',
      title: '方法',
      width: 90,
      slots: { default: 'methodSlot' },
    },
    {
      field: 'status',
      title: '状态',
      width: 90,
      slots: { default: 'statusSlot' },
    },
    { fixed: 'right', slots: { default: 'actionSlot' }, title: '操作', width: 160 },
  ],
  minHeight: 650,
  autoResize: true,
  pagerConfig: {},
  proxyConfig: {
    response: { result: 'items', total: 'total' },
    ajax: {
      query: async ({ page }) => {
        return await getPermissionListApi({
          page: page.currentPage,
          pageSize: page.pageSize,
        });
      },
    },
  },
  rowConfig: { isHover: true },
};

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

function openCreate() {
  editingId.value = undefined;
  FormApi.resetForm();
  FormModalApi.setState({ title: '新增单点权限' });
  FormModalApi.open();
}

function openEdit(row: PermissionApi.Permission) {
  editingId.value = row.id;
  FormApi.setValues({
    permission_code: row.permission_code,
    permission_name: row.permission_name,
    permission_group: row.permission_group,
    api_path: row.api_path,
    http_method: row.http_method,
    status: row.status,
    remark: row.remark,
  });
  FormModalApi.setState({ title: '编辑单点权限' });
  FormModalApi.open();
}

function handleDelete(row: PermissionApi.Permission) {
  Modal.confirm({
    title: '删除确认',
    content: `确认删除权限「${row.permission_name}（${row.permission_code}）」吗？`,
    async onOk() {
      await deletePermissionApi(row.id!);
      message.success('删除成功');
      GridApi.reload();
    },
  });
}
</script>

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

    <Card class="mb-4">
      <template #extra>
        <Button type="primary" @click="openCreate">新增权限</Button>
      </template>
      <template #title>单点权限管理</template>
    </Card>

    <Grid>
      <template #methodSlot="{ row }">
        <Tag v-if="row.http_method" :color="METHOD_COLORS[row.http_method] ?? 'default'">
          {{ row.http_method }}
        </Tag>
        <span v-else>-</span>
      </template>
      <template #statusSlot="{ row }">
        <Tag :color="row.status === 1 ? 'green' : 'red'">
          {{ row.status === 1 ? '启用' : '停用' }}
        </Tag>
      </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>
