<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NFlex } from 'naive-ui';
import type { ProEditDataTableColumns } from 'pro-naive-ui';
import { createProForm } from 'pro-naive-ui';

interface DataSourceType {
  id: string;
  title?: string;
  now?: number;
  rate?: number;
}

const editableKeys = ref<string[]>([]);
const form = createProForm({
  initialValues: {
    list: [
      {
        id: '1',
        now: Date.now(),
        rate: 4,
        title: '任务一'
      },
      {
        id: '2',
        now: Date.now(),
        rate: 3,
        title: '任务二'
      },
      {
        id: '3',
        now: Date.now(),
        rate: 5,
        title: '任务三'
      }
    ]
  },
  onSubmit: console.log
});

function cancelEditable(id: string) {
  editableKeys.value = editableKeys.value.filter(key => key !== id);
}

const columns: ProEditDataTableColumns<DataSourceType> = [
  {
    title: 'Title',
    path: 'title',
    field: 'input',
    width: 200
  },
  {
    title: '时间',
    path: 'now',
    field: 'date-time',
    width: 200
  },
  {
    title: '评分',
    path: 'rate',
    field: 'rate'
  },
  {
    title: '操作',
    width: 120,
    fixed: 'right',
    render: (row, rowIndex, { remove, editable }) => {
      return (
        <NFlex>
          {editable ? (
            <NButton text={true} type="primary" onClick={() => cancelEditable(row.id)}>
              保存
            </NButton>
          ) : (
            [
              <NButton text={true} type="primary" onClick={() => editableKeys.value.push(row.id)}>
                编辑
              </NButton>,
              <NButton
                text={true}
                type="error"
                onClick={() => {
                  remove(rowIndex);
                  cancelEditable(row.id);
                }}
              >
                删除
              </NButton>
            ]
          )}
        </NFlex>
      );
    }
  }
];
</script>

<template>
  <ProForm :form="form" label-placement="left">
    <ProConfigProvider
      :prop-overrides="{
        ProFormItem: {
          showFeedback: false
        }
      }"
    >
      <ProEditDataTable
        v-model:editable-keys="editableKeys"
        path="list"
        :columns="columns"
        :record-creator-props="{
          record: () => ({ id: Date.now() })
        }"
        row-key="id"
      >
        <template #toolbar>
          <NFlex>
            <NButton attr-type="reset">重置</NButton>
            <NButton type="primary" attr-type="submit">提交</NButton>
          </NFlex>
        </template>
      </ProEditDataTable>
    </ProConfigProvider>
  </ProForm>
</template>
