<template>
	<div class="h-full overflow-hidden">

			<n-card title="课程分类" :bordered="false" class="rounded-16px shadow-sm">
				<n-space class="pb-14px" justify="space-between">
					<!-- 加入查询组件 -->
					<n-space>
						<n-button type="primary" @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="primary" @click="handleOpenSearch">
							<icon-simple-line-icons:magnifier class="mr-4px text-16px" />
							查询
						</n-button>
						<div class="mr-5px"></div>
						<n-input-group>
							<n-input :style="{ width: '50%',marginRight:'2%'}" :value="conditionParams.id"
							@input="event => conditionParams.id = event" placeholder="请输入ID..." />
							<n-input :style="{ width: '50%',marginRight:'2%'}" :value="conditionParams.name"
								@input="event => conditionParams.name = event" placeholder="请输入学科名称..." />
							<n-input :style="{ width: '50%',marginRight:'2%' }" :value="conditionParams.description"
								@input="event => conditionParams.description = event" placeholder="请输入学科描述..." />
							<n-input :style="{ width: '50%',marginRight:'2%' }" :value="conditionParams.createUid"
								@input="event => conditionParams.createUid = event" placeholder="请输入创建用户ID..." />
							<n-input :style="{ width: '50%',marginRight:'2%' }" :value="conditionParams.createTime"
								@input="event => conditionParams.createTime = event" placeholder="请输入创建时间..." />
							<n-input :style="{ width: '50%',marginRight:'2%' }" :value="conditionParams.modifyTime"
								@input="event => conditionParams.modifyTime = event" placeholder="请输入修改时间..." />
							<n-select :style="{ width: '50%' }" :value="conditionParams.disabled"
								@input="event => conditionParams.disabled = event" placeholder="输入查询状态..." />
							<n-button type="primary" ghost @click="searchCondition()">
								搜索
							</n-button>
						</n-input-group>
					</n-space>
					<n-space align="center" :size="18">
						<n-button size="small" type="primary" @click="searchCondition">
							<icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
							刷新表格
						</n-button>
					</n-space>
				</n-space>
				<n-scrollbar>
				<!-- <n-data-table  :columns="columns" :data="searchForm" :loading="loading"
					:pagination="pagination" :row-key="rowKey" @update:checked-row-keys="handleCheck" /> -->
				<n-data-table  :columns="columns" :data="tableData" :loading="loading"
					:pagination="pagination" :row-key="rowKey"  />
				<table-action-add v-model:visible="visible" :type="modalType" :edit-data="(editData as SelectByCondition_1Params)" @update:checked-row-keys="handleCheck"/>
				<div style="width: 100%; height: 300px;"></div>
			</n-scrollbar>
			</n-card>

	</div>
</template>

<script setup lang="tsx" >
import { ref, Ref, reactive } 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 {  deleteById } from '~/src/service/api/sort';
import { selectByCondition_1 } from '~/src/service/api/sort';
import type { SelectByCondition_1Params } from '~/src/service/api/sort';
type RowData = {
	key: number
	id: number
	name: string
	description: string
	createTime: string
	modifyTime: string
	createUid: number
	disabled: string
}
const conditionParams: SelectByCondition_1Params = reactive({
	id: null,
	name: null,
	description: null,
	createUid:null,
	createTime: null,
	modifyTime: null,
	disabled: null
});

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();
const tableData = ref<any[]>([]);
const pagination: PaginationProps = ref({
	page: 1,
	pageSize: 10,
	showSizePicker: true,
	pageCount: 12,
	pageSizes: [10, 20, 30,40,50],
	onChange: (page: number) => {
		// 处理页码变化
		pagination.page = page;
	},
	onUpdatePageSize: (pageSize: number) => {
		// 处理每页显示数量变化
		pagination.pageSize = pageSize;
		pagination.page = 1;
	}
}).value;

// function searchCondition() {
// 	const pageNum = searchpagedata.value as number;
// 	const pageSize = searchpagesize.value as number;
// 	const params: SelectByCondition_1Params = {};
// 	if (pageNum && pageSize) {
// 		selectByCondition_1(pageNum, pageSize, params).then(res => {
// 			searchConData.value = res.data as [];
// 			pagination.page = searchpagedata.value
// 			pagination.pageSize = searchpagesize.value
// 			window.$message?.success('查询成功');
// 		})
// 	}
// 	else if (!pageNum && !pageSize) {
// 		searchpagedata.value = 0;
// 		searchpagesize.value = 0;
// 		window.$message?.warning('请输入页码和条数进行查询');
// 	}
// }
// function getTableData() {
// 	startLoading();
// 	selectAll_1().then(res => {
// 		setTimeout(() => {
// 			tableData.value = res.data as [];
// 			endLoading();
// 		}, 1000);
// 	});

// }
function init() {
	searchCondition();
}
// 初始化
init();

// function searchConClear() {
// 	searchConData.value.length = 0
// 	searchpagedata.value = 0;
// 	searchpagesize.value = 0;
// 	getTableData();
// }

const showSearch = ref(false)
function handleOpenSearch() {
	// 点击查询时显示搜索框
	showSearch.value = !showSearch.value;
}
// 输入数据
// function handleChange(v: string) {
// 	searchId.value = Number(v)
// }
// 根据id查询数据
// async function handleSearch() {
// 	if (searchId.value) {
// 		await selectById_1(searchId.value)
// 			.then(res => {
// 				// 更新数据
// 				searchInput.value = res.data as [];
// 				const filteredItems = tableData.value.filter(item => item.id === searchInput.value.id)
// 				searchForm.value = filteredItems;
// 				window.$message?.success('查询成功');
// 			})
// 	}
// 	else {
// 		searchForm.value.length = 0
// 		window.$message?.warning('请输入有效的ID进行查询');
// 	}
// }

// function searchClear() {
// 	searchForm.value.length = 0
// 	getTableData();
// }

const checkedRowKeysRef = ref<DataTableRowKey[]>([])
const s = ref<DataTableRowKey[]>([])
// 根据id进行删除
async function deleteTableData() {
	const ids = checkedRowKeysRef.value.filter((item) => !s.value?.includes(item));
	s.value = checkedRowKeysRef.value
	if (ids.length !== 0) {
		console.log(ids);
		for (const id of ids) {
			// 调用删除接口
			await deleteById(id as number)
				.then((res) => {
					window.$message?.success('删除成功!');
				})
		}
		searchCondition(); // 删除完成后刷新表格数据
	} else {
		// 没有选择任何行时的操作
		window.$message?.error('未选择要删除的行');
	}
}

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

function setModalType(type: ModalType) {
	modalType.value = type;
}
// 添加
function addTableData() {
	openModal();
	setModalType('add');
}

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

function handleDeleteTable(rowId: string) {
	// const findItem = tableData.value.find(item => item.id === rowId);
	const rowIdNumber = Number(rowId);
		deleteById(rowIdNumber)
		init()
}
function deleteSubjectsList() {
	const difference = checkedRowKeysRef.value.filter(item => !s.value.includes(item));
	s.value = checkedRowKeysRef.value
	for (let i = 0; i < difference.length; i++) {
		deleteById(Number(difference[i]));
	}
	init();
}
function searchCondition() {
	selectByCondition_1(pagination.page, pagination.pageSize, conditionParams).then(r => {
		tableData.value = r.data as [];
	}).catch(() => {
		console.log('jdias')
	})
}

const columns: Ref<DataTableColumns<SelectByCondition_1Params>> = ref([
	{
		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>;
			}
		}
	},
	{
		key: 'actions',
		title: '操作',
		align: 'center',
		render: row => {
			return (
				<NSpace justify={'center'}>
					<NButton size={'small'} onClick={() => handleEditTable(row)} >
						编辑
					</NButton>
					<NPopconfirm onPositiveClick={() => handleDeleteTable(row.id.toString())}>
						{{
							default: () => '确认删除',
							trigger: () => <NButton size={'small'}>删除</NButton>
						}}
					</NPopconfirm>
				</NSpace>
			);
		}

	},
])as Ref<DataTableColumns<SelectByCondition_1Params>>
const rowKey = (row: RowData) => row.id
function handleCheck(rowKeys: DataTableRowKey[]) {
	checkedRowKeysRef.value = rowKeys
}
</script>
