<script setup lang="tsx">
import { NButton, NPopconfirm } from 'naive-ui';
import type { InternalRowData } from 'naive-ui/es/data-table/src/interface';
import { fetchAddTag, fetchDeleteTag, fetchEditTag, fetchGetTagList } from '@/service/api/goods/tag';
import { useTable } from '@/components/zt/Table/hooks/useTable';
import { useModalFrom } from '@/components/zt/ModalForm/hooks/useModalForm';

const columns: NaiveUI.TableColumn<InternalRowData>[] = [
  {
    key: 'name',
    title: '标签名称',
    align: 'center',
    minWidth: 100
  }
];

const [registerTable, { refresh, setTableLoading }] = useTable({
  searchFormConfig: {
    schemas: [
      {
        field: 'name',
        label: '标签名称',
        component: 'NInput'
      }
    ],
    inline: false,
    size: 'small',
    labelPlacement: 'left',
    isFull: false
  },
  tableConfig: {
    keyField: 'id',
    title: '标签列表',
    showAddButton: true
  }
});

async function handleDelete(row: Recordable) {
  setTableLoading(true);
  await fetchDeleteTag([row.id]);
  refresh();
}
const [registerModalForm, { openModal, closeModal, getFieldsValue, setFieldsValue }] = useModalFrom({
  modalConfig: {
    title: '标签 ',
    width: 400,
    isShowHeaderText: true,
    height: 100
  },
  formConfig: {
    schemas: [
      {
        label: '',
        field: 'id',
        component: 'NInput',
        show: false
      },
      {
        field: 'name',
        label: '标签名称',
        component: 'NInput',
        required: true
      }
    ],
    gridProps: {
      cols: '1'
    },
    labelWidth: 120
  }
});
async function handleSubmit() {
  const form = await getFieldsValue();
  if (form.id) {
    await fetchEditTag(form);
  } else {
    await fetchAddTag(form);
  }
  closeModal();
  refresh();
}

async function edit(row: Recordable) {
  openModal(row);
  setFieldsValue(row);
}
</script>

<template>
  <LayoutTable>
    <ZTable :columns="columns" :api="fetchGetTagList" @register="registerTable" @add="openModal">
      <template #op="{ row }">
        <NButton size="small" ghost type="primary" @click="edit(row)">编辑</NButton>
        <NPopconfirm @positive-click="handleDelete(row)">
          <template #trigger>
            <NButton size="small" type="error" ghost>删除</NButton>
          </template>
          确定删除吗？
        </NPopconfirm>
      </template>
    </ZTable>
    <BasicModelForm @register-modal-form="registerModalForm" @submit-form="handleSubmit"></BasicModelForm>
  </LayoutTable>
</template>

<style scoped></style>
