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

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

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

import MIcon from '#/components/icon/icon.vue';
import type { FileTypeRecord } from '#/api/core/file-type';
import {
  createFileType,
  deleteFileType,
  getFileTypeList,
  updateFileType,
} from '#/api/core/file-type';

defineOptions({ name: 'FileType' });

const loading = ref(false);
const items = ref<FileTypeRecord[]>([]);
const modalOpen = ref(false);
const isUpdate = ref(false);
const form = ref<Partial<FileTypeRecord>>({
  name: '',
  icon: '',
  value: 0,
  suffix: '',
  sort: 0,
  status: 1,
});

const columns = [
  { title: 'ID', dataIndex: 'id', width: 70 },
  { title: '图标', key: 'icon', width: 80 },
  { title: '名称', dataIndex: 'name' },
  { title: '值', dataIndex: 'value', width: 70 },
  { title: '后缀', dataIndex: 'suffix' },
  { title: '排序', dataIndex: 'sort', width: 80 },
  { title: '状态', key: 'status', width: 90 },
  { title: '操作', key: 'action', width: 140 },
];

async function load() {
  loading.value = true;
  try {
    const res = await getFileTypeList();
    const data = (res as any)?.data ?? res;
    items.value = Array.isArray(data) ? data : [];
  } finally {
    loading.value = false;
  }
}

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

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

async function submitForm() {
  if (!form.value.name?.trim() || !form.value.suffix?.trim()) {
    message.warning('请填写名称和后缀');
    return;
  }
  if (isUpdate.value && form.value.id) {
    await updateFileType({
      id: form.value.id,
      name: form.value.name,
      icon: form.value.icon,
      suffix: form.value.suffix,
      sort: form.value.sort,
      status: form.value.status,
    });
    message.success('更新成功');
  } else {
    await createFileType(form.value);
    message.success('创建成功');
  }
  modalOpen.value = false;
  await load();
}

function handleDelete(row: FileTypeRecord) {
  Modal.confirm({
    title: '确认删除',
    content: `确定删除分类「${row.name}」吗？`,
    okType: 'danger',
    async onOk() {
      await deleteFileType(row.id);
      message.success('删除成功');
      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 === 'icon'">
            <MIcon v-if="record.icon" :icon="record.icon" size="18" />
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'status'">
            {{ record.status === 1 ? '启用' : '禁用' }}
          </template>
          <template v-else-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="图标 (Iconify)">
          <Input v-model:value="form.icon" placeholder="ant-design:file-image-outlined" />
          <div v-if="form.icon" class="icon-preview">
            <MIcon :icon="form.icon" size="20" />
          </div>
        </Form.Item>
        <Form.Item v-if="!isUpdate" label="分类值 (对应 xk_file.type)" required>
          <InputNumber v-model:value="form.value" :min="0" :max="99" class="w-full" />
        </Form.Item>
        <Form.Item v-else label="分类值">
          <Input :value="String(form.value)" disabled />
        </Form.Item>
        <Form.Item label="后缀（逗号分隔）" required>
          <Input v-model:value="form.suffix" placeholder="jpg,png,gif" />
        </Form.Item>
        <Form.Item label="排序">
          <InputNumber v-model:value="form.sort" :min="0" class="w-full" />
        </Form.Item>
        <Form.Item label="状态">
          <Switch
            :checked="form.status === 1"
            checked-children="启用"
            un-checked-children="禁用"
            @change="(v) => (form.status = v ? 1 : 0)"
          />
        </Form.Item>
      </Form>
    </Modal>
  </Page>
</template>

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

.icon-preview {
  margin-top: 8px;
}
</style>
