<script lang="ts" setup>
import { ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, Card, Form, Input, InputNumber, Modal, Space, Table, message } from 'ant-design-vue';

import type { FileGroupRecord } from '#/api/core/file-group';
import {
  createFileGroup,
  deleteFileGroup,
  getFileGroupList,
  updateFileGroup,
} from '#/api/core/file-group';
import { useFileGroupCache } from '#/composables/use-file-group-cache';

defineOptions({ name: 'FileGroup' });

const loading = ref(false);
const items = ref<FileGroupRecord[]>([]);
const modalOpen = ref(false);
const isUpdate = ref(false);
const form = ref<Partial<FileGroupRecord>>({
  name: '',
  sort: 0,
});

const { invalidateGroupOptions } = useFileGroupCache();

const columns = [
  { title: 'ID', dataIndex: 'id', width: 70 },
  { title: '名称', dataIndex: 'name' },
  { title: '排序', dataIndex: 'sort', width: 80 },
  { title: '操作', key: 'action', width: 140 },
];

/** 加载分组列表 */
async function load() {
  loading.value = true;
  try {
    const res = await getFileGroupList();
    const data = (res as any)?.result ?? (res as any)?.data ?? res;
    items.value = Array.isArray(data) ? data : [];
  } finally {
    loading.value = false;
  }
}

function openCreate() {
  isUpdate.value = false;
  form.value = { name: '', sort: 0 };
  modalOpen.value = true;
}

function openEdit(row: FileGroupRecord) {
  isUpdate.value = true;
  form.value = { ...row };
  modalOpen.value = true;
}

/** 提交创建/更新并刷新缓存 */
async function submitForm() {
  if (!form.value.name?.trim()) {
    message.warning('请填写分组名称');
    return;
  }
  if (isUpdate.value && form.value.id) {
    await updateFileGroup({
      id: form.value.id,
      name: form.value.name,
      sort: form.value.sort,
    });
    message.success('更新成功');
  } else {
    await createFileGroup(form.value);
    message.success('创建成功');
  }
  modalOpen.value = false;
  await invalidateGroupOptions();
  await load();
}

function handleDelete(row: FileGroupRecord) {
  Modal.confirm({
    title: '确认删除',
    content: `确定删除分组「${row.name}」吗？组内关联将被移除。`,
    okType: 'danger',
    async onOk() {
      await deleteFileGroup(row.id);
      message.success('删除成功');
      await invalidateGroupOptions();
      await load();
    },
  });
}

void load();
</script>

<template>
  <Page auto-content-height title="分组管理">
    <Card>
      <div class="toolbar">
        <Button type="primary" @click="openCreate">新增分组</Button>
        <Button :loading="loading" @click="load">刷新</Button>
      </div>

      <Table
        :columns="columns"
        :data-source="items"
        :loading="loading"
        :pagination="false"
        row-key="id"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="openEdit(record)">编辑</Button>
              <Button danger type="link" size="small" @click="handleDelete(record)">删除</Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <Modal
      v-model:open="modalOpen"
      :title="isUpdate ? '编辑分组' : '新增分组'"
      ok-text="保存"
      cancel-text="取消"
      @ok="submitForm"
    >
      <Form layout="vertical" class="mt-2">
        <Form.Item label="名称" required>
          <Input v-model:value="form.name" placeholder="如：活动素材" />
        </Form.Item>
        <Form.Item label="排序">
          <InputNumber v-model:value="form.sort" :min="0" class="w-full" />
        </Form.Item>
      </Form>
    </Modal>
  </Page>
</template>

<style scoped lang="scss">
.toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}
</style>
