<template>
	<a-card>
		<!-- 标签页 -->
		<a-tabs v-model:activeKey="formState.verifyStatus" @change="tabChange">
			<a-tab-pane key="0" tab="未发布" v-if="!pageType"></a-tab-pane>
			<a-tab-pane key="1" tab="待审核"></a-tab-pane>
			<a-tab-pane key="2" tab="已发布" v-if="!pageType"></a-tab-pane>
			<!-- <a-tab-pane key="3" tab="已审核" v-if="pageType == 'economize'"></a-tab-pane> -->
			<a-tab-pane key="4" tab="回收站"></a-tab-pane>
		</a-tabs>
		<!-- 搜索和操作区域 -->
		<a-row :gutter="16" style="margin-bottom: 16px">
			<a-col :span="18">
				<a-input v-model:value="formState.fileName" placeholder="请输入资源名称" style="width: 200px" />
				<a-cascader
					style="width: 200px; margin-left: 8px"
					v-model:value="formState.majorIdName"
					:options="collegeMajorOptions"
					:fieldNames="{ label: 'name', value: 'parentId', children: 'children' }"
					placeholder="请选择院系"
					changeOnSelect
					@change="changeCollegeMajor"
				/>
				<a-select
					v-model:value="formState.courseTypeName"
					style="width: 200px; margin-left: 8px"
					:options="courseTypeOptions"
					placeholder="请选择资源类型"
				/>
				<a-select v-model:value="formState.suffix" placeholder="课件格式" style="width: 200px; margin-left: 8px">
					<a-select-option value="mp4">mp4</a-select-option>
					<a-select-option value="ppt">ppt</a-select-option>
					<a-select-option value="word">word</a-select-option>
					<a-select-option value="pdf">pdf</a-select-option>
				</a-select>
				<!-- <a-select
					v-model:value="formState.suffix"
					style="width: 200px; margin-left: 8px"
					:options="suffixTypeOptions"
					placeholder="请选择课件格式"
				/> -->
				<a-button type="primary" style="margin-left: 8px" @click="handleSearch">查询</a-button>
				<a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
			</a-col>
			<a-col :span="6" style="text-align: right">
				<a-button
					type="primary"
					style="margin-right: 8px"
					v-if="formState.verifyStatus === '0'"
					@click="batchPublish"
					:disabled="selectedRowKeys.length === 0"
				>
					+ 批量发布
				</a-button>
				<a-button type="primary" @click="showUploadModal">+ 上传资源</a-button>
			</a-col>
		</a-row>

		<!-- 表格 -->
		<a-table
			:columns="currentColumns"
			:data-source="dataSource"
			:pagination="false"
			:loading="loading"
			bordered
			:row-key="(record) => record.id"
			:row-selection="rowSelection"
		>
			<template #bodyCell="{ column, text, record }">
				<template
					v-if="
						['fileName', 'collegeIdName', 'majorIdName', 'courseTypeName', 'suffix', 'uploadTime'].includes(
							column.dataIndex
						)
					"
				>
					<div class="multiLine-ellipsis" :title="text">{{ text || '-' }}</div>
				</template>
				<!-- 状态列 -->
				<template v-if="column.key === 'verifyStatus'">
					<span v-if="record.verifyStatus === '0'">
						<a-badge status="processing" text="处理中" />
					</span>
					<span v-else-if="record.verifyStatus === 'uploaded'">
						<a-badge status="success" text="已上传" />
					</span>
					<span v-else-if="record.verifyStatus === '1'">
						<a-badge status="default" text="待审核" />
					</span>
					<span v-else-if="record.verifyStatus === '2'">
						<a-badge status="success" text="已发布" />
					</span>
					<span v-else-if="record.verifyStatus === '4'">
						<a-badge status="error" text="已删除" />
					</span>
				</template>
				<!-- 操作列 -->
				<template v-else-if="column.key === 'action'">
					<div class="editable-cell">
						<a v-if="formState.verifyStatus === '0' && !pageType" @click="handlePublish(record)">发布</a>
						<a v-if="formState.verifyStatus === '1' && pageType == 'economize'" @click="handleAudit(record)">审核</a>
						<a v-if="formState.verifyStatus === '2' && pageType == 'economize'" @click="handlePermission(record)"
							>权限</a
						>
						<a v-if="formState.verifyStatus === '4'" @click="handleRestore(record)">恢复</a>
						<a-divider type="vertical" />
						<a-dropdown>
							<a class="ant-dropdown-link">
								更多
								<DownOutlined />
							</a>
							<template #overlay>
								<a-menu>
									<a-menu-item>
										<a href="javascript:;" @click="handleView(record)">播放</a>
									</a-menu-item>
									<a-menu-item>
										<a href="javascript:;">下载</a>
									</a-menu-item>
									<a-menu-item v-if="formState.verifyStatus === '2'">
										<a href="javascript:;" @click="edit(record)">编辑</a>
									</a-menu-item>
									<a-menu-item>
										<a-popconfirm title="确认删除吗?" @confirm="resourcesDelete(record, 1)">
											<a href="javascript:;">删除</a>
										</a-popconfirm>
									</a-menu-item>
								</a-menu>
							</template>
						</a-dropdown>
					</div>
				</template>
			</template>
		</a-table>
		<div class="dis-flex-sb margin-top">
			<div>
				<a-button @click="selectAll">选择全部</a-button>
				<a-button @click="invertSelection" style="margin-left: 8px">反选选择</a-button>
			</div>
			<div>
				<CustomPagination
					:total="pagination.total"
					:current="pagination.pageNum"
					:pageSize="pagination.pageSize"
					:showQuickJumper="true"
					:showSizeChanger="true"
					:showTotal="(total) => `共 ${total} 条数据`"
					@change="handlePageChange"
					@showSizeChange="handlePageSizeChange"
				/>
			</div>
		</div>
		<!-- 权限树模态框 -->
		<permissionTree v-if="permissionTreeVisible" @close="permissionTreeVisible = false"></permissionTree>
		<!-- 审核播放模态框 -->
		<auditModal
			v-if="auditModalVisible"
			:recordData="publishedData"
			:isAudit="auditState"
			@confirm="auditConfirm"
			@close="auditModalVisible = false"
		></auditModal>
		<!-- 资源上传模态框 -->
		<resourceUpload
			v-if="uploadModalVisible"
			:isState="isState"
			:resourcesId="editResourcesId"
			@close="uploadModalVisible = false"
			@getList="getList"
		></resourceUpload>
		<!-- 发布模态框 -->
		<releaseModal v-if="releaseVisible" @close="releaseVisible = false" @confirm="confirm"></releaseModal>
	</a-card>
</template>

<script setup>
	import { ref, onMounted } from 'vue'
	import { DownOutlined } from '@ant-design/icons-vue'
	import releaseModal from './releaseModal.vue'
	import resourceUpload from './resourceUpload.vue'
	import resourceAuditApi from '@/api/resourceAudit.js'
	import permissionTree from './permissionTree.vue'
	import auditModal from './auditModal.vue'
	import CustomPagination from '@/components/customPagination.vue'
	import tool from '@/utils/tool'
	// eslint-disable-next-line vue/no-setup-props-destructure
	const { pageType } = defineProps({
		pageType: {
			type: String,
			default: () => {}
		}
	})
	// 数据源
	const dataSource = ref([])
	//发布按钮状态
	const releaseVisible = ref(false)
	const permissionTreeVisible = ref(false) //权限树
	const auditModalVisible = ref(false) //播放审核
	const isPublishBulk = ref(false) //是否批量发布
	const loading = ref(false) // 列表loading
	const isState = ref(0) //是否是编辑  0:新增 1:编辑
	const editResourcesId = ref(null) //资源id
	// 搜索值
	const searchValue = ref('')
	//课程类型
	const courseTypeOptions = tool.dictList('COURSE_TYPE')
	const suffixTypeOptions = ref([])
	const pagination = reactive({
		pageSize: 10,
		pageNum: 1,
		total: 0
	})
	const formState = reactive({
		fileName: null,
		verifyStatus: '0',
		resourcesId: null,
		majorIdName: null,
		courseTypeName: null,
		suffix: null
	})
	// 添加选择状态
	const selectedRowKeys = ref([])
	const selectedRows = ref([])
	const publishedData = ref([]) //当前点击数据
	// 行选择配置
	const rowSelection = computed(() => {
		return {
			selectedRowKeys: selectedRowKeys.value,
			onChange: (keys, rows) => {
				selectedRowKeys.value = keys
				selectedRows.value = rows
			},
			onSelectAll: (selected, selectedRows, changeRows) => {
				if (selected) {
					// 全选当前页
					selectedRowKeys.value = dataSource.value.map((item) => item.id)
					selectedRows.value = dataSource.value
				} else {
					// 取消全选
					selectedRowKeys.value = []
					selectedRows.value = []
				}
			},
			onSelectInvert: () => {
				// 反选当前页
				const allKeys = dataSource.value.map((item) => item.id)
				const newSelectedKeys = allKeys.filter((key) => !selectedRowKeys.value.includes(key))
				selectedRowKeys.value = newSelectedKeys
				selectedRows.value = dataSource.value.filter((item) => newSelectedKeys.includes(item.id))
			}
		}
	})
	// 列定义
	const columnsUnpublished = [
		{
			title: '编号',
			align: 'center',
			dataIndex: 'fileId',
			key: 'fileId'
		},
		{
			title: '资源名称',
			align: 'center',
			dataIndex: 'fileName',
			key: 'fileName'
		},
		{
			title: '课件格式',
			align: 'center',
			dataIndex: 'suffix',
			key: 'suffix'
		},
		{
			title: '上传时间',
			dataIndex: 'uploadTime',
			align: 'center',
			key: 'uploadTime'
		},
		{
			title: '状态',
			align: 'center',
			key: 'verifyStatus'
		},
		{
			title: '操作',
			align: 'center',
			key: 'action'
		},
		{
			title: '资源缩略图',
			align: 'center',
			key: 'image'
		}
	]

	const columnsPending = [
		{
			title: '编号',
			dataIndex: 'id',
			align: 'center',
			key: 'id'
		},
		{
			title: '资源名称',
			align: 'center',
			dataIndex: 'fileName',
			key: 'fileName'
		},
		{
			title: '所属院系',
			align: 'center',
			dataIndex: 'collegeAllIdName',
			key: 'collegeAllIdName'
		},
		// {
		// 	title: '所属课程',
		// 	align: 'center',
		// 	dataIndex: 'collegeIdName',
		// 	key: 'collegeIdName'
		// },
		// {
		// 	title: '所属专业',
		// 	align: 'center',
		// 	dataIndex: 'majorIdName',
		// 	key: 'majorIdName'
		// },
		{
			title: '资源类型',
			align: 'center',
			dataIndex: 'courseTypeName',
			key: 'courseTypeName'
		},
		{
			title: '资源格式',
			align: 'center',
			dataIndex: 'suffix',
			key: 'suffix'
		},
		{
			title: '上传时间',
			align: 'center',
			dataIndex: 'uploadTime',
			key: 'uploadTime'
		},
		{
			title: '状态',
			align: 'center',
			key: 'verifyStatus'
		},
		{
			title: '操作',
			align: 'center',
			key: 'action'
		},
		{
			title: '资源缩略图',
			align: 'center',
			key: 'image'
		}
	]

	const columnsPublished = [...columnsPending]
	const columnsRecycle = [...columnsPending]
	const collegeMajorOptions = ref([])
	const currentColumns = computed(() => {
		switch (formState.verifyStatus) {
			case '0':
				return columnsUnpublished
			case '1':
				return columnsPending
			case '2':
				return columnsPublished
			case '3':
				return columnsPublished
			case '4':
				return columnsRecycle
			default:
				return []
		}
	})
	const getListData = () => {
		loading.value = true
		let params = {
			current: pagination.pageNum,
			size: pagination.pageSize,
			verifyStatus: formState.verifyStatus,
			fileName: formState.fileName,
			majorIdName: formState.majorIdName?.join(','),
			courseTypeName: formState.courseTypeName,
			suffix: formState.suffix
		}
		resourceAuditApi
			.page(params)
			.then((res) => {
				console.log(res, '资源审核列表')
				dataSource.value = res.data.records
				pagination.total = res.data.total
				loading.value = false
			})
			.catch((err) => {
				console.log(err)
				dataSource.value = []
				pagination.total = 0
				loading.value = false
			})
	}
	const getList = () => {
		getListData()
	}
	//院系组织查询
	const getOrgTreeSelector = () => {
		resourceAuditApi
			.orgTreeSelector()
			.then((res) => {
				console.log(res.data, '获取组织树选择器')
				collegeMajorOptions.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	// 方法
	const handleSearch = () => {
		console.log('Search:', searchValue.value)
		getListData()
	}

	const handleReset = () => {
		searchValue.value = null
		formState.majorIdName = null
		formState.fileName = null
		formState.courseTypeName = null
		formState.suffix = null
		getListData()
	}
	const tabChange = () => {
		dataSource.value = []
		getListData()
	}
	//发布
	const handlePublish = (record) => {
		publishedData.value = record
		releaseVisible.value = true
		isPublishBulk.value = false
	}
	// 批量发布方法
	const batchPublish = () => {
		if (selectedRows.value.length === 0) {
			message.warning('请至少选择一条记录')
			return
		}
		isState.value = 0
		isPublishBulk.value = true
		releaseVisible.value = true
	}
	// 全选当前页数据
	const selectAll = () => {
		selectedRowKeys.value = dataSource.value.map((item) => item.id)
		selectedRows.value = dataSource.value
	}

	// 反选当前页数据
	const invertSelection = () => {
		const allKeys = dataSource.value.map((item) => item.id)
		const newSelectedKeys = allKeys.filter((key) => !selectedRowKeys.value.includes(key))
		selectedRowKeys.value = newSelectedKeys
		selectedRows.value = dataSource.value.filter((item) => newSelectedKeys.includes(item.id))
	}
	//发布确定
	const confirm = (obj) => {
		console.log(obj, selectedRows.value, '传回来的数据')
		releaseVisible.value = false
		if (isPublishBulk.value) {
			// const batchParams = selectedRows.value.map((item) => ({
			// 	id: item.id,
			// 	coverImage: item.coverImage,
			// 	resourceDesc: item.resourceDesc,
			// 	verifyStatus: 1
			// }))
			const params = {
				ids: selectedRows.value.map((item) => item.id).join(','),
				coverImage: obj.coverImageId,
				resourceDesc: obj.resourceDesc,
				verifyStatus: 1
			}
			console.log(params, '批量发布参数')
			// handleRelease(params)
		} else {
			const params = {
				ids: publishedData.value.id,
				coverImage: obj.coverImageId,
				resourceDesc: obj.resourceDesc,
				verifyStatus: 1
			}
			console.log(params, '发布参数')
			handleRelease(params)
		}
	}
	// updateStatus接口调用
	const handleRelease = (Params) => {
		resourceAuditApi
			.updateStatus(Params)
			.then((res) => {
				getListData()
				selectedRowKeys.value = []
			})
			.catch((err) => {
				console.error(err)
			})
	}
	const auditState = ref(null)
	const handleAudit = (record) => {
		console.log('Audit:', record)
		publishedData.value = record
		auditState.value = true
		auditModalVisible.value = true
	}
	const handleView = (record) => {
		publishedData.value = record
		auditState.value = false
		auditModalVisible.value = true
	}

	const handlePermission = (record) => {
		console.log('Permission:', record)
		permissionTreeVisible.value = true
	}
	const auditConfirm = (obj) => {
		console.log('auditConfirm:', obj)
		const params = {
			ids: obj.id,
			verifyStatus: obj.auditResult
		}
		resourceAuditApi
			.updateStatus(params)
			.then((res) => {
				if (res.code == 200) {
					auditModalVisible.value = false
				}
				getListData()
			})
			.catch((err) => {
				console.error(err)
			})
	}

	const handleDelete = (record) => {
		console.log('Delete:', record)
	}
	const handleRestore = (record) => {
		const params = {
			ids: record.id,
			verifyStatus: 1
		}
		resourceAuditApi
			.updateStatus(params)
			.then((res) => {
				getListData()
			})
			.catch((err) => {
				console.error(err)
			})
	}
	//资源编辑
	const edit = (record) => {
		console.log('Restore:', record)
		uploadModalVisible.value = true
		isState.value = 1
		editResourcesId.value = record.id
	}
	//资源删除
	const resourcesDelete = (record) => {
		const params = {
			ids: record.id,
			verifyStatus: 4
		}
		if (formState.verifyStatus == 4) {
			resourceAuditApi
				.deletefile(params)
				.then((res) => {
					getListData()
				})
				.catch((err) => {
					console.error(err)
				})
		} else {
			resourceAuditApi
				.updateStatus(params)
				.then((res) => {
					getListData()
				})
				.catch((err) => {
					console.error(err)
				})
		}



	}

	// 上传资源模态框
	const uploadModalVisible = ref(false)

	// 显示上传模态框
	const showUploadModal = () => {
		isState.value = 0
		uploadModalVisible.value = true
	}
	// 翻页
	const handlePageChange = (page) => {
		pagination.pageNum = page
		getListData()
	}
	// 每页条数
	const handlePageSizeChange = (pageNum, size) => {
		pagination.pageNum = 1
		pagination.pageSize = size
		getListData()
	}

	onMounted(() => {
		if (pageType == 'economize') {
			formState.verifyStatus = '1'
		}
		getOrgTreeSelector()
		getListData()
	})
</script>

<style scoped>
	.editable-cell {
		position: relative;
	}

	.ant-dropdown-link {
		margin-left: 8px;
	}

	.upload-area {
		border: 2px dashed #3ca9f5;
		padding: 40px;
		text-align: center;
	}

	.upload-area p {
		margin: 10px 0;
	}

	.file-item {
		display: flex;
		align-items: center;
		margin: 10px 0;
	}

	.file-item .ant-progress {
		flex: 1;
		margin: 0 10px;
	}
</style>
