<template>
	<div class="assets-category-container">
		<el-card shadow="hover">
			<div class="assets-category-search mb15">
				<el-form :inline="true" :model="tableData.param">
					<el-form-item label="名称">
						<el-input size="default" v-model="tableData.param.name" placeholder="请输入分类名称" clearable style="width: 200px" />
					</el-form-item>
					<el-form-item>
						<el-button size="default" type="primary" @click="AlistCategories" >
							<el-icon><ele-Search /></el-icon>
							查询
						</el-button>
						<el-button size="default" type="success" @click="onOpenAddCategory()">
							<el-icon><ele-FolderAdd /></el-icon>
							新增
						</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-table
				:data="tableData.data"
				style="width: 100%"
				row-key="id"
				default-expand-all
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				v-loading="tableData.loading"
			>
				<!-- <el-table-column type="index" label="序号" width="80" /> -->
				<el-table-column prop="name" label="分类名称" show-overflow-tooltip min-width="100" />
				<el-table-column prop="sort" label="排序" width="80" />
				<el-table-column prop="createdAt" label="创建时间" width="180" show-overflow-tooltip />
				<el-table-column prop="updatedAt" label="修改时间" width="180" show-overflow-tooltip />
				<el-table-column prop="status" label="状态" width="100">
					<template #default="scope">
						<el-switch
							v-model="scope.row.status"
							:active-value="1"
							:inactive-value="0"
							inline-prompt
							active-text="显示"
							inactive-text="隐藏"
							@change="onStatusChange(scope.row)"
						/>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="250" fixed="right">
					<template #default="scope">
						<el-button size="small" class="op-btn-add" text type="primary" @click="onOpenAddCategory(scope.row)">新增</el-button>
						<el-button size="small" text type="primary" @click="onOpenEditCategory(scope.row)">修改</el-button>
						<el-button size="small" text type="info" @click="onViewLog(scope.row)">日志</el-button>
						<el-button size="small" text type="danger" @click="onRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<EditCategory ref="editCategoryRef" @getCategoryList="getCategoryList" />
		<OperationLogDialog ref="operationLogRef" />
	</div>
</template>

<script lang="ts">
export default {
	name: 'assetsCategory',
};
</script>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EditCategory from './component/editCategory.vue';
import OperationLogDialog from '../component/operationLogDialog.vue';
import { getCategoryTree, deleteCategory, updateCategoryStatus,listCategories } from '/@/api/assets/category';

interface CategoryRow {
	id: string;
	name: string;
	level: number;
	type: string;
	status: number;
	sort?: number;
	createdAt: string;
	updatedAt: string;
	children?: CategoryRow[] | null;
}

const editCategoryRef = ref();
const operationLogRef = ref();
const tableData = reactive({
	data: [] as CategoryRow[],
	loading: false,
	param: {
		name: '',
		type: '',
	},
});

// 获取分类列表
const getCategoryList = () => {
	tableData.loading = true;
	getCategoryTree(tableData.param)
		.then((res: any) => {
			// 主类目不做展示，直接取主类目的children
			const tree = res.data?.tree ?? [];
			
			// 递归函数，将所有id字段转换为字符串
			const convertIdsToString = (items: any[]): any[] => {
				return items.map(item => ({
					...item,
					id: item.id?.toString(),
					children: item.children && item.children.length > 0 ? convertIdsToString(item.children) : []
				}));
			};
			
			const processedTree = convertIdsToString(tree);
			tableData.data = processedTree.length > 0 && processedTree[0].children ? processedTree[0].children : [];
		})
		.catch(() => {
			tableData.data = [];
		})
		.finally(() => {
			tableData.loading = false;
		});
};

// 查询功能
const AlistCategories = () => {
	const keyword = tableData.param.name?.trim();
	// 如果没有输入关键词，则获取完整树形结构
	if (!keyword) {
		getCategoryList();
		return;
	}
	// 有关键词时进行搜索
	tableData.loading = true;
	listCategories(keyword)
		.then((res: any) => {
			// 搜索结果直接展示为列表
			tableData.data = res.data?.list ?? res.data ?? [];
		})
		.catch(() => {
			tableData.data = [];
			ElMessage.error('查询失败');
		})
		.finally(() => {
			tableData.loading = false;
		});
}
// 打开新增弹窗
const onOpenAddCategory = (row?: CategoryRow) => {
	editCategoryRef.value.openDialog(row?.id);
};

// 打开修改弹窗
const onOpenEditCategory = (row: CategoryRow) => {
	editCategoryRef.value.openDialog(row, true);
};

// 删除
const onRowDel = (row: CategoryRow) => {
	ElMessageBox.confirm(`此操作将永久删除分类："${row.name}"，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			deleteCategory(row.id).then(() => {
				ElMessage.success('删除成功');
				getCategoryList();
			});
		})
		.catch(() => {});
};

// 状态切换
const onStatusChange = (row: CategoryRow) => {
	updateCategoryStatus(row.id, row.status)
		.then(() => {
			ElMessage.success('状态更新成功');
		})
		.catch(() => {
			// 失败时恢复原状态
			row.status = row.status === 1 ? 0 : 1;
		});
};

// 查看日志
const onViewLog = (row: CategoryRow) => {
	operationLogRef.value?.openDialog(row.id);
};

onMounted(() => {
	getCategoryList();
});
</script>

<style scoped lang="scss">
.assets-category-container {
	.assets-category-search {
		display: flex;
		flex-wrap: wrap;
	}
}
</style>
