<template>
	<div class="system-dept-container layout-padding">
		<el-card shadow="hover" class="layout-padding-auto">
			<div class="system-dept-search mb15">
				<el-select
					@change="handleChangeModule"
					size="default"
					v-model="state.tableData.param.moduleName"
					placeholder="请选择模块"
					clearable
					style="max-width: 180px"
				>
					<el-option
						:data-op="item.id"
						v-for="(item, index) in moduleList"
						:key="index"
						:label="item.moduleName"
						:value="item.moduleName"
					></el-option>
				</el-select>
				<el-select size="default" v-model="state.tableData.param.labelName" placeholder="请选择标签" clearable class="ml10" style="max-width: 180px">
					<el-option v-for="(item, index) in labelList" :key="index" :label="item.name" :value="item.name"></el-option>
				</el-select>
				<el-input size="default" placeholder="请输入附件名称" v-model="state.tableData.param.name" class="ml10" style="max-width: 180px"> </el-input>
				<el-button @click="getTableData" size="default" type="primary" class="ml10">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button @click="downloadSelected" size="default" type="primary" class="ml10">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					批量下载
				</el-button>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%" @selection-change="handleSelectionChange"
			ref="tableRef">
				<el-table-column type="selection" width="55" />
				<el-table-column prop="name" label="附件名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="moduleName" label="模块" show-overflow-tooltip></el-table-column>
				<el-table-column prop="labelName" label="标签" show-overflow-tooltip></el-table-column>
				<el-table-column prop="name" label="上传者" show-overflow-tooltip></el-table-column>
				<el-table-column prop="createtime" label="创建时间" :formatter="dateFormatter" show-overflow-tooltip></el-table-column>
				<el-table-column label="操作">
					<template #default="scope">
						<el-button size="small" text type="primary" @click="toShowDetail(scope.row)">查看详情</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				class="mt15"
				:pager-count="5"
				:page-sizes="[10, 20, 30]"
				v-model:current-page="state.tableData.param.current"
				background
				v-model:page-size="state.tableData.param.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.tableData.total"
			>
			</el-pagination>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="attachmentIndex">
import { onMounted, reactive, ref } from 'vue';
import { articleApi } from '/@/api/article';
import { attachmentApi } from '/@/api/attachment';
import { ElMessage, TableColumnCtx } from 'element-plus';
import { useRouter } from 'vue-router';

const router = useRouter();

// 表格数据
const state = reactive({
	tableData: {
		data: [],
		total: 0,
		loading: false,
		param: {
			labelName: '',
			moduleName: '',
			name: '',
			current: 1,
			size: 10,
		},
	},
	selectedRows: [] as any[], // 用于存储选中的附件
});

// 模块列表
interface Module {
  id: number;
  moduleName: string;
}

const moduleList = ref<Module[]>([]);

// 标签列表
interface Label {
  name: string;
}

const labelList = ref<Label[]>([]);

// 引入 api 请求接口
const artApi = articleApi();
const atcmApi = attachmentApi();

// 获取表格数据
const getTableData = async () => {
	try {
		state.tableData.loading = true;
		let res = await atcmApi.getAttachmentList(state.tableData.param);
		if (res?.success) {
			state.tableData.data = res.data.records;
			state.tableData.total = res.data.total;
		} else {
			ElMessage.error('附件列表获取失败！');
		}
	} catch (error) {
		ElMessage.error('数据加载失败！');
	} finally {
		state.tableData.loading = false;
	}
};

// 处理多选
const handleSelectionChange = (selection: any[]) => {
	state.selectedRows = selection;
};

// 批量下载
const downloadSelected = () => {
	if (!state.selectedRows.length) {
		ElMessage.warning('请先选择附件！');
		return;
	}
	state.selectedRows.forEach((file) => {
		// 假设提供了 API 或工具进行文件下载
		// 示例：使用 Blob URL 或直接调用下载 API
		console.log(`下载文件: ${file.id}`);
	});

	// 需要传给后端ids的数据
	const ids = state.selectedRows.map((item) => item.id);
	console.log(ids);
	atcmApi.downloadFiles(ids);
};

const getModuleList = async () => {
	try {
		let res = await artApi.getModuleList();
		if (res?.success) {
			moduleList.value = res.data;
		} else {
			ElMessage.error('模块列表获取失败！');
		}
	} catch (error) {
		ElMessage.error('模块列表获取失败！');
	} finally {
	}
};

// 模块选择
const handleChangeModule = async (val: any) => {
	try {
		state.tableData.param.labelName = '';
		if (!val) {
			labelList.value = [];
			return;
		}
		const op: any = event?.currentTarget;
		let res = await artApi.getLabelList(op.dataset.op);
		if (res?.success) {
			labelList.value = res.data;
		} else {
			ElMessage.error('标签列表获取失败！');
		}
	} catch (error) {
		ElMessage.error('标签列表获取失败！');
	} finally {
	}
};

// 附件详情
const toShowDetail = (row: any) => {
	router.push({ path: '/attachment/detail', query: { id: row.id, moduleName: row.moduleName, labelName: row.labelName } });
};

// 日期格式化
const dateFormatter = (row: any, column: TableColumnCtx<String>) => {
	let date = new Date(row.createtime);
	return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.tableData.param.size = val;
	getTableData();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.tableData.param.current = val;
	getTableData();
};

onMounted(() => {
	getTableData();
	getModuleList();
});
</script>

<style scoped lang="scss">
.system-dept-container {
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		.el-table {
			flex: 1;
		}
	}
}
</style>
