<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue';
import { $t } from '@/locales';
import { fetchGetCategoryList } from '@/service/api';
import { useFormOperate } from "./modules/dictionaryTable";
import CategorySearch from './modules/dictionary.vue';
import CategoryOperateDrawer from './modules/dictionary-operate-drawer.vue';
import CategoryHeaderOperation from "./modules/dictionary-header-operation.vue";
import { NButton, NPopconfirm, DataTableColumns } from 'naive-ui';
import { useAppStore } from '@/store/modules/app';
const appStore = useAppStore();

onMounted(async () => {
  try {
    const {data} = await fetchGetCategoryList();
    tableData.value = data as RowData[];
  } catch (error) {
    console.error('Failed to fetch category list:', error);
  }
});

type RowData = Api.Category.Category & {
  children?: RowData[];
};

let loading = ref(false)
// 数据
// let tableData = ref<RowData[]>([]);
  const tableData = ref<RowData[]>([
  {
    id: 1,
    parentId: 0,
    categoryName: 'Root 1',
    level: '1',
    createTime: '2023-10-10',
    categoryType: '网站',
  },
  {
    id: 2,
    parentId: 1,
    categoryName: 'Child 1-1',
    level: '2',
    createTime: '2023-10-11',
    categoryType: '文献',
  },
]);


// 表行
const columns2 = (): DataTableColumns<RowData> => [
  {
    title: $t('page.category.form.categoryName'),
    key: 'categoryName',

  },
  {
    title: $t('page.category.form.categoryType'),
    align: 'center',
    key: 'categoryType',
    width: '25%',
  },
  {
    title: $t('page.category.form.createTime'),
    align: 'center',
    key: 'createTime',
    width: '25%',
  },
  {
    title: $t('common.action'),
    key: 'index',
    align: 'center',
    width: '20%',
    render: row => (
      <div class="flex-center gap-8px">
        <NButton type="primary" text ghost size="small" onClick={() => Add(row!)}>
          {$t('common.add')}
        </NButton>
        <n-divider vertical />
        <NButton type="warning" text ghost size="small" onClick={() => Edit(row!)}>
          {$t('common.edit')}
        </NButton>
        <n-divider vertical />
        <NPopconfirm
          onPositiveClick={() => Delete(row.id!)}
        >
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" text ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
]
const rowKey = (row: RowData) => row.id

const getData = async () => {
  console.log("666")
  loading.value = true;
  // 模拟延迟
  const {data} = await fetchGetCategoryList();
  tableData.value = data as RowData[];
  loading.value = false;
  // 模拟获取数据
};
const saveData = async (data: RowData) => {
  // 模拟保存数据
  console.log('保存表单数据', data);
};
const {
  drawerVisible, // 抽屉是否可见
  operateType,
  editingData,
  handleAdd, // 添加操作
  handleEdit, // 编辑操作
} = useFormOperate({
  getData, // 操作表单后会执行此方法
  saveData
});

// 表头添加操作
const headAdd = () => {
  handleAdd(-1);
}
const refresh = () => {
  console.log("你点击了刷新按钮")
  getData()
}
// 行添加操作
const Add = (item: RowData) => {
  handleAdd(item.parentId);
  console.log("你点击了添加", item.id)
}
// 行编辑操作
const Edit = (item: RowData) => {
  handleEdit(item);
  console.log("你点击了编辑", item.id)
}
// 行删除操作
const Delete = (id: number) => {
  console.log("你点击了删除按钮", id)
}

const checkedRowKeys = reactive<number[]>([]);
const mobilePagination = reactive({
  page: 1,
  pageSize: 10,
});
</script>

<template>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <!-- 查询组件 -->
        <CategorySearch 
          @update="getData"
        />
        <DeleteAlert />
        <NCard 
            :title="$t('page.category.title')" 
            :bordered="false" size="small" 
            header-class="view-card-header"
            class="sm:flex-1-hidden card-wrapper">
            <!-- 表头选项 -->
            <template #header-extra>
                <CategoryHeaderOperation
                :disabled-delete="false"
                :loading="loading"
                :show-delete="false"
                @add="headAdd"
                @refresh="refresh"
                />
            </template>
            <!-- 表格内容 -->
            <!-- <n-data-table
                virtual-scroll
                :max-height="490"
                :columns="columns2()"
                :data="tableData"
                :row-key="rowKey"
                default-expand-all
            /> -->
            <NDataTable
              v-model:checked-row-keys="checkedRowKeys"
              :columns="columns2()"
              :data="tableData"
              :flex-height="!appStore.isMobile"
              :scroll-x="962"
              :loading="loading"
              remote
              :row-key="row => row.id"
              :pagination="mobilePagination"
              class="sm:h-full"
            />
            <!-- 侧边栏 -->
            <CategoryOperateDrawer
                v-model:visible="drawerVisible"
                :operate-type="operateType"
                :row-data="editingData"
                @submitted="getData"
            />
        </NCard>
    </div>

</template>

