<template>
  <BasicModal
    width="30%"
    v-bind="$attrs"
    @register="registerModal"
    :title="title"
    @ok="handleSubmit"
  >
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="addProperty()">添加参数</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                color: 'error',
                label: '删除',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicTable, TableAction, useTable } from '@/components/Table';
  import { recommendColumns } from '../data';

  defineOptions({ name: 'KnowledgeModal' });

  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const title = ref();
  const n = ref(1000);
  const tableData = ref([]);
  //获取接口数据并放在下拉框里（这里是打开了一个弹框）
  //初始化表单
  const [registerTable, { reload }] = useTable({
    api: async () => {
      const response = {
        pageNum: '1',
        pageSize: '10',
        pages: '1',
        total: tableData.value.length,
        code: '',
        message: '',
        data: [],
      };
      let data = [];
      data = tableData.value;
      return { ...response, data: data };
    },
    pagination: false,
    columns: recommendColumns,
    useSearchForm: false,
    actionColumn: {
      width: 150,
      title: '操作',
      dataIndex: 'action',
    },
    scroll: {
      y: 300,
    },
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
  });
  //初始化弹框
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    tableData.value = [];
    await reload();
    setModalProps({ confirmLoading: false });
    title.value = data.title;
  });

  async function handleSubmit() {
    closeModal();
    createMessage.success('提交成功');
  }
  /**新增属性*/
  function addProperty() {
    const data = {
      businessId: n.value + 1,
      name: '',
      defaultValue: '',
    };
    tableData.value.push(data);
    n.value++;
    reload();
  }
  /** 删除按钮*/
  function handleDelete(record: Recordable) {
    tableData.value.splice(
      tableData.value.findIndex((item) => item.businessId === record.businessId),
      1,
    );
    createMessage.success('删除成功!');
    reload();
  }
  onMounted(() => {});
</script>
