<template>
	<div class="h-full overflow-hidden">
		<n-card title="课程分类" :bordered="false" class="rounded-16px shadow-sm">
			<n-space class="pb-12px" justify="space-between">
				<!-- 加入查询组件 -->
				<column-search v-if="showSearch" @close="handleCloseSearch" />
				<n-space v-else>
					<n-button type="primary" :data="addData" @click="addTableData">
						<icon-ic-round-plus class="mr-4px text-20px" />
						新增
					</n-button>
					<n-button type="error" @click="deleteTableData" @update:checked-row-keys="handleCheck">
						<icon-ic-round-delete class="mr-4px text-20px" />
						删除
					</n-button>
					<n-button type="success">
						<icon-uil:export class="mr-4px text-20px" />
						导出Excel
					</n-button>
					<!-- 添加查询按钮 -->
					<n-button size="small" type="primary" @click="handleOpenSearch">
						<icon-simple-line-icons:magnifier class="mr-4px text-16px" />
						查询
					</n-button>
				</n-space>
				<n-space align="center" :size="18">
					<n-button size="small" type="primary" @click="getTableData">
						<icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
						刷新表格
					</n-button>
					<column-search v-model:columns="columns" />
				</n-space>
			</n-space>
			<n-data-table :columns="columns" :data="tableData" :loading="loading" :pagination="pagination" :row-key="rowKey"
				@update:checked-row-keys="handleCheck" />
			<table-action-add v-model:visible="visible" :type="modalType" :edit-data="editData" />
		</n-card>
		<!-- <n-input-group>
      <n-input :style="{ width: '100%' }" clearable/>
    </n-input-group>
		<n-input-group>
			<span class="line-height-33.99px mr-5px w-70px">创建时间</span>
      <n-date-picker :style="{ width: '13%' }"/>
      <n-time-picker :style="{ width: '14.2%' ,marginRight:'2%'}"/>
			<span class="line-height-33.99px mr-5px w-70px">修改时间</span>
      <n-date-picker :style="{ width: '13%' }"/>
      <n-time-picker :style="{ width: '14.2%' ,marginRight:'2%'}"/>
				<span class="w-50px  line-height-33.99px">状态</span>
				<n-select  :options="selectOptions" :style="{ width: '21%' ,marginRight:'2%'}"  clearable/>
				<n-button type="primary" ghost>
      	  搜索
    		</n-button>
    </n-input-group> -->
	</div>
</template>

<script lang="tsx" >
import { defineComponent, ref } from 'vue'
import { NButton, NSpace, NTag, NPopconfirm } from 'naive-ui';
import type { DataTableColumns, PaginationProps } from 'naive-ui';
import { useBoolean, useLoading } from '@/hooks';
import type { DataTableRowKey } from 'naive-ui'
import TableActionAdd from './components/table-action-add.vue'
import type { ModalType } from './components/table-action-add.vue';
// import {  userStatusLabels } from '@/constants';
import { userStatusLabels } from '@/constants';
import { selectAll_1, deleteById } from '~/src/service/api/sort';
import type { AddEasEduCategoryParams } from '~/src/service/api/sort';
import ColumnSearch from './components/column-search.vue';
type RowData = {
	key: number
	id: number
	name: string
	description: string
	createTime: string
	modifyTime: string
	createUid: number
	disabled: string
}
const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();

const tableData = ref<any[]>([]);

// const checkedRowKeysRef = ref<DataTableRowKey[]>([])
const pagination: PaginationProps = ref({
	page: 1,
	pageSize: 10,
	showSizePicker: true,
	pageSizes: [10, 20, 50],
	onChange: (page: number) => {
		// 处理页码变化
		pagination.page = page;
	},
	onUpdatePageSize: (pageSize: number) => {
		// 处理每页显示数量变化
		pagination.pageSize = pageSize;
		pagination.page = 1;
	}
}).value;


export async function getTableData() {
	startLoading();
	selectAll_1().then(res => {
		setTimeout(() => {
			tableData.value = res.data as [];
			endLoading();
		}, 1000);
	});
}

const checkedRowKeysRef = ref<DataTableRowKey[]>([])

async function deleteTableData() {
	const ids = checkedRowKeysRef.value;
	// console.log(ids);
	if (ids.length !== 0) {
		console.log(ids);
		for (let id of ids) {
			// 调用删除接口
			console.log(id);
			await deleteById(id as number)
				.then((res) => {
					const deleteRes = res.data;
					if (!deleteRes)
						console.log(`成功删除课程，ID: ${id}`);
					window.$message?.success('删除成功!');
				})
				.catch((error) => {
					// 错误处理
					console.error(`删除课程发生错误，ID: ${id}`, error);
					window.$message?.error('删除失败!');
				});
		}
		getTableData(); // 删除完成后刷新表格数据
	} else {
		// 没有选择任何行时的操作
		console.warn('未选择要删除的行');
	}
}

const createColumns = (): DataTableColumns<UserManagement.User> => [
	{
		type: 'selection',
		align: 'center',
	},
	{
		key: 'id',
		title: "ID",
		align: 'center'
	},
	{
		key: 'name',
		title: '学科名称',
		align: 'center'
	},
	{
		key: 'description',
		title: '学科描述',
		align: 'center'
	},
	{
		key: 'createTime',
		title: '创建时间',
		align: 'center'
	},
	{
		key: 'modifyTime',
		title: '修改时间',
		align: 'center'
	},
	{
		key: 'createUid',
		title: '创建用户ID',
		align: 'center'
	},
	{
		key: 'disabled',
		title: '状态',
		align: 'center',

		render: row => {
			if (row.disabled) {
				const tagTypes: Record<UserManagement.UserStatusKey, NaiveUI.ThemeColor> = {
					'N': 'error',
					'Y': 'success',
				};
				return <NTag type={tagTypes[row.disabled]}>{userStatusLabels[row.disabled]}</NTag>;
			}
			return
		}
	},
	{
		key: 'actions',
		title: '操作',
		align: 'center',
		render: row => {
			return (
				<NSpace justify={'center'}>
					<NButton size={'small'} onClick={() => handleEditTable(row.id)} >
						编辑
					</NButton>
					<NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
						{{
							default: () => '确认删除',
							trigger: () => <NButton size={'small'}>删除</NButton>
						}}
					</NPopconfirm>
				</NSpace>
			);
		}

	},
]

const modalType = ref<ModalType>('add' || 'edit');

function setModalType(type: ModalType) {
	modalType.value = type;
	// console.log(modalType.value);
}

const addData = ref<AddEasEduCategoryParams[]>([]);
function addTableData() {
	openModal();
	setModalType('add');
	getTableData(); // 删除完成后刷新表格数据
	// const params: AddEasEduCategoryParams = {};
	// addEasEduCategory(params).then(res => {
	// 	console.log(res);
	// 	addData.value = res.data as [];
	// });
}

const editData = ref<UserManagement.User | null>(null);
function setEditData(data: UserManagement.User | null) {
	editData.value = data;
}
console.log(tableData.value);
function handleEditTable(rowId: number | null) {
	const findItem = tableData.value.find(item => item.id === rowId);
	setModalType('edit');
	openModal();
	if (findItem) {
		setEditData(findItem);
	}
	// console.log(findItem);
	getTableData(); // 编辑完成后刷新表格数据
}

function handleDeleteTable(rowId: number | null) {
	const findItem = tableData.value.find(item => item.id === rowId);
	if (findItem) {
		deleteById(findItem.id).then((r) => {
			console.log(r);
			getTableData(); // 编辑完成后刷新表格数据
		})
	}
}

const showSearch = ref(false)

function handleOpenSearch() {
	// 点击查询时显示搜索框
	showSearch.value = true;
}
function handleCloseSearch() {
	// 关闭搜索框，并重新显示主页面
	showSearch.value = false;
}


function init() {
	getTableData();
}

// 初始化
init();

export default defineComponent({
	components: {
		TableActionAdd,
		ColumnSearch
	},
	setup() {
		// const checkedRowKeysRef = ref<DataTableRowKey[]>([])
		return {
			showSearch,
			tableData,
			addData,
			loading,
			modalType,
			setEditData,
			editData,
			handleCloseSearch,
			getTableData,
			addTableData,
			setModalType,
			deleteTableData,
			handleEditTable,
			handleOpenSearch,
			visible,
			columns: createColumns(),
			checkedRowKeys: checkedRowKeysRef,
			pagination,
			rowKey: (row: RowData) => row.id,
			handleCheck(rowKeys: DataTableRowKey[]) {
				checkedRowKeysRef.value = rowKeys
				console.log(checkedRowKeysRef.value);
			}
		}
	}
})
</script>
