<template>
	<div class="app-container">
		<el-card shadow="always">
			<!-- 查询 -->
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="文件名" prop="path">
					<el-input placeholder="模糊查询" clearable @keyup.enter="handleQuery" style="width: 240px" v-model="state.queryParams.name" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" plain @click="handleSearch">
						<SvgIcon name="elementSearch" />
						搜索
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="box-card">
			<template #header>
				<div class="card-header">
					<span class="card-header-text">文件列表</span>
					<div>
						<el-button type="primary" plain v-auth="'file:api:addFile'" @click="onOpenAddModule">
							<!-- <input type="file" id="fileInput" /> -->
							<SvgIcon name="elementPlus" />
							上传文件
						</el-button>
						<el-button type="primary" plain v-auth="'file:api:addCatalogue'" @click="onOpenAddCatalogue">
							<SvgIcon name="elementPlus" />
							创建目录
						</el-button>
						<el-button type="danger" plain :disabled="state.multiple" v-auth="'file:api:delete'" @click="onTabelRowDel">
							<SvgIcon name="elementDelete" />
							删除
						</el-button>
					</div>
				</div>
			</template>
			<div @click="handleBack" v-if="state.treeIdArr.length" style="margin: 10px 0; color: rgb(92, 160, 181); cursor: pointer">上一级</div>
			<!--数据表格-->
			<el-table v-loading="state.loading" :data="state.tableData" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="文件名" align="center" prop="file_name">
					<template #default="scope">
						<div @click="handleClick(scope.row)" style="display: flex; align-items: center; gap: 8px; cursor: pointer">
							<span>
								<svg
									v-if="scope.row.is_folder == 1"
									t="1711027477155"
									class="icon"
									viewBox="0 0 1024 1024"
									version="1.1"
									xmlns="http://www.w3.org/2000/svg"
									p-id="1475"
									width="16"
									height="16"
								>
									<path
										d="M848.8576 199.1936H415.7568c0-26.5728-21.5424-48.128-48.128-48.128H175.1424c-26.5728 0-48.128 21.5424-48.128 48.128V343.5648c0 26.5984 21.5424 48.1408 48.128 48.1408h673.728c26.5728 0 48.128-21.5424 48.128-48.1408v-96.2432c-0.0128-26.5856-21.5552-48.128-48.1408-48.128z"
										fill="#CCA352"
										p-id="1476"
									></path>
									<path
										d="M800.7424 247.3088H223.2576c-26.5728 0-48.128 21.5424-48.128 48.128v48.128c0 26.5984 21.5424 48.1408 48.128 48.1408h577.472c26.5728 0 48.128-21.5424 48.128-48.1408v-48.128c0-26.5728-21.5424-48.128-48.1152-48.128z"
										fill="#FFFFFF"
										p-id="1477"
									></path>
									<path
										d="M848.8576 295.4368H175.1424c-26.5728 0-48.128 21.5424-48.128 48.128v481.2544c0 26.5472 21.5424 48.128 48.128 48.128h673.728c26.5728 0 48.128-21.568 48.128-48.128V343.552c-0.0128-26.5728-21.5552-48.1152-48.1408-48.1152z"
										fill="#FFCC66"
										p-id="1478"
									></path>
								</svg>
								<svg
									v-else
									t="1711029218257"
									class="icon"
									viewBox="0 0 1024 1024"
									version="1.1"
									xmlns="http://www.w3.org/2000/svg"
									p-id="2489"
									width="14"
									height="14"
								>
									<path
										d="M913.29536 941.04064c0.0256 24.82688-16.54784 44.96384-37.0176 44.98432l-708.23936 0.6912c-20.46464 0.02048-37.07904-20.08576-37.10464-44.91264l-0.83968-859.02848c-0.0256-24.82688 16.54784-44.96384 37.0176-44.98432l521.10848-0.50688 224.39424 210.50368 0.68096 693.25312z"
										fill="#E6E4E2"
										p-id="2490"
									></path>
									<path
										d="M913.29536 253.26592l-189.11744 0.18432c-20.46464 0.02048-37.07904-20.08576-37.10464-44.91264l-0.16384-165.77024 226.38592 210.49856z"
										fill="#C4BCB1"
										p-id="2491"
									></path>
									<path
										d="M720.72192 396.84096a22.54848 22.54848 0 0 1-22.54848 22.54848H326.13376a22.54848 22.54848 0 0 1 0-45.09696h372.0448a22.54848 22.54848 0 0 1 22.54336 22.54848zM720.72192 565.95456a22.54848 22.54848 0 0 1-22.54848 22.54848H326.13376a22.54848 22.54848 0 0 1 0-45.09696h372.0448a22.54848 22.54848 0 0 1 22.54336 22.54848zM720.72192 746.33728a22.54848 22.54848 0 0 1-22.54848 22.54848H326.13376a22.54848 22.54848 0 0 1 0-45.09696h372.0448a22.54848 22.54848 0 0 1 22.54336 22.54848z"
										fill="#C4BCB1"
										p-id="2492"
									></path>
								</svg>
							</span>
							<span>{{ scope.row.file_name }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="文件大小" align="center" prop="file_size"
					><template #default="scope">
						<div v-if="scope.row.is_folder == 1">-</div>
						<div v-else>{{ (scope.row.file_size / 1024).toFixed(0) }}KB</div>
					</template></el-table-column
				>
				<el-table-column label="创建时间" align="center" prop="create_time"
					><template #default="scope">
						<span>{{ dateStrFormat(scope.row.create_time) }}</span>
					</template></el-table-column
				>
				<el-table-column label="创建者" align="center">{{ userInfos.userInfos.username }}</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template #default="scope">
						<el-popover placement="left">
							<template #reference>
								<el-button type="primary" circle>
									<SvgIcon name="elementStar" />
								</el-button>
							</template>
							<div>
								<el-button text type="primary" v-auth="'file:api:edit'" @click="onOpenEditModule(scope.row)">
									<SvgIcon name="elementEdit" />重命名
								</el-button>
							</div>
							<div>
								<el-button text type="primary" v-auth="'file:api:delete'" @click="onTabelRowDel(scope.row)">
									<SvgIcon name="elementDelete" />删除
								</el-button>
							</div>
						</el-popover>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页设置-->
			<div v-show="state.count > 0">
				<el-divider></el-divider>
				<el-pagination
					background
					:total="state.count"
					:current-page="state.queryParams.pageNum"
					:page-size="state.queryParams.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-card>
		<!-- 添加或修改配置参数对话框 -->
		<EditModule ref="editModuleRef" :currentId="state.currentId" :title="state.title" />
		<EditCatalogue :currentId="state.currentId" ref="editCatalogueRef" :title="state.title" />
	</div>
</template>

<script lang="ts" setup>
import { ref, toRefs, reactive, onMounted, getCurrentInstance, onUnmounted, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { get } from '@/api/files/list';
import EditModule from './component/editModule.vue';
import EditCatalogue from './component/editCatalogue.vue';
import { delFile } from '@/utils/util';
import { Session } from '@/utils/storage';
import { useUserInfosState } from '@/stores/userInfos';

const userInfos = useUserInfosState();
const { proxy } = getCurrentInstance() as any;
const editModuleRef = ref();
const editCatalogueRef = ref();
const state = reactive({
	// 遮罩层
	loading: true,
	// 选中数组
	ids: [],
	// 非单个禁用
	single: true,
	// 非多个禁用
	multiple: true,
	// 弹出层标题
	title: '',
	// 配置参数表格数据
	tableData: [] as any,
	allTableData: [],
	// 总条数
	total: 0,
	methodOptions: [],
	currentId: 0, // 默认层级 0
	treeIdArr: [], // 记录当前已进栈的文件id
	// 查询参数
	queryParams: {
		// 页码
		pageNum: 1,
		// 每页大小
		pageSize: 10,
		path: undefined,
		name: undefined,
		description: undefined,
		method: undefined,
		apiGroup: undefined,
	},
});

// 获取用户信息 vuex
// const getUserInfos = computed(() => {
// 	return userInfos.userInfos;
// });

const handleSort = (data: any) => {
	const newData = [...data];
	newData.sort((obj1: any, obj2: any) => {
		if (obj1.is_folder == 1 && (obj2.is_folder == 0 || !obj2.is_folder)) {
			return -1; // obj1排在前面
		} else if ((obj1.is_folder == 0 || !obj1.is_folder) && obj2.is_folder == 1) {
			return 1; // obj2排在前面
		} else {
			return 0; // 保持原有顺序
		}
	});
	return newData;
};

/** 查询配置参数列表 */
const handleQuery = () => {
	state.loading = true;
	get({ isPublic: 0, userId: userInfos.userInfos.userId }).then((res: any) => {
		// 数据处理
		let newData = [];
		state.allTableData = handleSort(res) || [];
		if (state.currentId == 0) {
			newData = state.allTableData.filter((item) => item.parent_id == state.currentId || !item.parent_id);
		} else {
			newData = state.allTableData.filter((item) => item.parent_id == state.currentId);
		}
		state.tableData = handleSort(newData) || [];
		state.loading = false;
	});
};
/** 前端搜索 */
const handleSearch = () => {
	if (!state.queryParams.name) {
		handleQuery();
		return;
	}
	state.loading = true;
	const search: any = state.tableData.filter((item) => {
		return item.file_name.includes(state.queryParams.name);
	});
	state.tableData = search;
	state.loading = false;
};
/** 重置按钮操作 */
const resetQuery = () => {
	state.queryParams.path = undefined;
	state.queryParams.description = undefined;
	state.queryParams.method = undefined;
	state.queryParams.apiGroup = undefined;
	handleQuery();
};

// 打开新增配置参数弹窗
const onOpenAddModule = () => {
	state.title = '创建公共文件';
	editModuleRef.value.openDialog({});
};

// 打开新增目录弹窗
const onOpenAddCatalogue = () => {
	state.title = '创建文件目录';
	editCatalogueRef.value.openDialog({});
};

// 打开编辑配置参数弹窗
const onOpenEditModule = (row: object) => {
	state.title = '修改文件名';
	editCatalogueRef.value.openDialog(row);
};
/** 删除按钮操作 */
const onTabelRowDel = (row: any) => {
	const id = row.file_id || state.ids;
	ElMessageBox({
		message: '是否确认删除?',
		title: '警告',
		showCancelButton: true,
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(function () {
		if (Array.isArray(id)) {
			const delFilePromises = id.map((item) => {
				return delFile(item);
			});
			return Promise.all(delFilePromises).then((results) => {
				// 所有上传操作完成后的处理逻辑
				if (results.length == id.length) {
					handleQuery();
					ElMessage.success('删除成功');
				}
			});
		}
		return delFile(id).then((res) => {
			if (res) {
				handleQuery();
				ElMessage.success('删除成功');
			} else {
				ElMessage.error('删除失败');
			}
		});
	});
};

// 多选框选中数据
const handleSelectionChange = (selection: any) => {
	state.ids = selection.map((item: any) => item.file_id);
	state.single = selection.length != 1;
	state.multiple = !selection.length;
};

// 点击目录
const handleClick = (row: any) => {
	state.loading = true;
	if (row.is_folder == 1) {
		// 目录，加载该目录下的数据
		const newData = state.allTableData.filter((item) => item.parent_id == row.id);
		state.tableData = newData || [];
		state.currentId = row.id;
		state.treeIdArr.push(row.id);
		state.loading = false;
	} else {
		window.open(row.file_Path + '?token' + Session.get('token'));
		state.loading = false;
	}
};

// 返回上一级
const handleBack = () => {
	const curIndex = state.treeIdArr.findIndex((item) => item == state.currentId);
	if (curIndex > 0) {
		state.currentId = state.treeIdArr[curIndex - 1];
		const newTreeIdArr = [...state.treeIdArr];
		newTreeIdArr.pop();
		state.treeIdArr = newTreeIdArr;
	} else {
		state.currentId = 0;
		state.treeIdArr = [];
	}
	let newData = [];
	if (state.currentId == 0) {
		newData = state.allTableData.filter((item) => item.parent_id == state.currentId || !item.parent_id);
	} else {
		newData = state.allTableData.filter((item) => item.parent_id == state.currentId);
	}
	state.tableData = newData || [];
};

//分页页面大小发生变化
const handleSizeChange = (val: any) => {
	state.queryParams.pageSize = val;
	handleQuery();
};
//当前页码发生变化
const handleCurrentChange = (val: any) => {
	state.queryParams.pageNum = val;
	handleQuery();
};

// 页面加载时
onMounted(() => {
	// 查询配置参数信息
	handleQuery();
	proxy.mittBus.on('onEditApiModule', (res: any) => {
		console.log('onEditApiModule', res);

		handleQuery();
	});
});
// 页面卸载时
onUnmounted(() => {
	proxy.mittBus.off('onEditApiModule');
});
</script>
