<template>
	<div class="plan-index-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<splitpanes class="h100" :horizontal="horizontal">
				<pane min-size="16" max-size="25" size="16">
					<el-scrollbar ref="scrollBarRef" noresiz>
						<el-skeleton :loading="state.typeLoading" animated :rows="10">
							<template #default>
								<v-tree-search
									:data="state.typeOptions"
									titleField="name"
									keyField="id"
									selectable
									searchPlaceholder="课件分类名称"
									@select="selectType"
									@unselect="unSelectType"
									ref="treeSearchRef"
								>
									<template #node="{ node }">
										<span>{{ node.name }}</span>
									</template>
								</v-tree-search>
							</template>
						</el-skeleton>
					</el-scrollbar>
				</pane>
				<pane class="h100" style="display: flex; flex: 1; flex-direction: column">
					<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent :disabled="state.tableLoading">
						<el-form-item label="课件名称" prop="Title">
							<el-input v-model="state.queryParams.Title" placeholder="课件名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
						</el-form-item>
						<el-form-item label="格式" prop="FileType">
							<el-select v-model="state.queryParams.FileType" placeholder="请选择" @change="handleQuery" :disabled="state.tableLoading">
                                <el-option
                                    v-for="item in state.filesTypeSelect"
                                    :key="item"
                                    :label="item"
                                    :value="item"
                                />
                            </el-select>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="state.tableLoading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
                            <el-button @click="resetQuery(ruleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置</el-button>
						</el-form-item>
					</el-form>
					<vxe-toolbar
						ref="toolbarRef"
						:loading="state.tableLoading"
						custom
						:refresh="{
							queryMethod: handleQuery,
						}"
					>
						<template #buttons>
							<el-button type="primary" @click="onAdd" v-auth="'course:index:add'" :loading="state.tableLoading">
								<SvgIcon name="ele-Upload" class="mr5" />上传课件
							</el-button>
                            <el-button type="primary" plain @click="onBatchDownload" v-auth="'course:index:batchDownload'" :loading="state.tableLoading" :disabled="isChecked">
                                <SvgIcon name="ele-Download" class="mr5" />批量下载
                            </el-button>
							<el-button type="danger" plain @click="onBatchDelete" v-auth="'course:index:batchDelete'" :loading="state.tableLoading" :disabled="isChecked">
                                <SvgIcon name="ele-Delete" class="mr5" />批量删除
                            </el-button>
						</template>
					</vxe-toolbar>
					<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
						<vxe-table
							border
							:loading="state.tableLoading"
							:data="state.tableData"
							:column-config="{ resizable: true }"
							:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
							ref="tableRef"
							height="auto"
							auto-resize
							show-overflow
							:print-config="{}"
							:scrollY="{ enabled: true, gt: 100 }"
							id="coursewareManage"
							:custom-config="{ storage: true }"
							showHeaderOverflow
							@checkbox-all="selectAllChangeEvent"
							@checkbox-change="selectChangeEvent"
						>
							<vxe-column type="checkbox" width="50" align="center"></vxe-column>
							<vxe-column field="name" title="课件名称" min-width="200"></vxe-column>
							<vxe-column field="sourcewareType" title="课件格式" width="150"></vxe-column>
							<vxe-column field="creatorName" title="创建人" width="150"></vxe-column>
							<vxe-column field="creationTime" title="创建时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column title="操作" fixed="right" width="180" align="center" :show-overflow="false">
								<template #default="{ row }">
                                    <el-button link type="primary" @click="onDownload(row)" title="预览下载" v-auth="'course:index:download'">
										预览下载
									</el-button>
									<el-button link type="primary" @click="onEdit(row)" title="编辑" v-auth="'course:index:edit'">
										编辑
									</el-button>
									<el-button link type="danger" @click="onRowDel(row)" title="删除" v-auth="'course:index:delete'">
										删除
									</el-button>
								</template>
							</vxe-column>
						</vxe-table>
					</div>
					<pagination
						@pagination="queryList"
						:total="state.total"
						v-model:current-page="state.queryParams.PageIndex"
						v-model:page-size="state.queryParams.PageSize"
						:disabled="state.tableLoading"
					/>
				</pane>
			</splitpanes>
		</div>
		
		<!-- 编辑课件 -->
		<course-edit ref="courseEditRef" @updateList="handleQuery" />
		<!-- 上传课件 -->
		<course-upload ref="courseUploadRef" @updateList="handleQuery" />
	</div>
</template>

<script lang="tsx" setup name="coursewareManage">
import { ref, reactive, onMounted, defineAsyncComponent, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import Other from '@/utils/other';
import { downloadFileByStream } from '@/utils/tools';
import { VxeUI } from 'vxe-pc-ui';
import { VTreeSearch } from '@wsfe/vue-tree';
import {deleteCourseware, getCoursewareData, fileDownloadBatch} from '@/api/courseware/index';
import { coursewareTreeList } from '@/api/courseware/type';
import { fileDownloadByUrl } from '@/api/public/file';
import { util } from 'echarts';

// 引入组件
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
const CourseEdit = defineAsyncComponent(() => import('@/views/courseware/index/components/Course-edit.vue')); // 课件编辑
const CourseUpload = defineAsyncComponent(() => import('@/views/courseware/index/components/Course-upload.vue')); // 课件上传

const router = useRouter(); //路由
const horizontal = ref(false);

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 20, //每页条数
        CourseWareTypeID: null, // 课件类型
		Title: null, //课件名称
        FileType: null, // 课件格式
	},
	typeLoading: false, // 类型loading
	typeOptions: [], // 类型数据
    filesTypeSelect: ["doc","rar","jpg","pdf","mp3","xls","xlsx","zip","docx","wmv","mp4","png","svg","avi","jpeg","m4a","txt","wps"],
	tableData: [], //表格数据
	total: 0, //总条数
	loading: false, //表格loading
	tableLoading: false, //表格loading
});
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取课件分类
const getCoursewareType = async () => {
	state.typeLoading = true;
	try {
		const { result } = await coursewareTreeList();
		state.typeOptions = result ?? [];
		state.typeLoading = false;
	} catch (error) {
		state.typeLoading = false;
	}
};
/** 获取课件列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.tableLoading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.name = state.queryParams.Title || '';
	requestParams.value.sourcewareType = state.queryParams.FileType || '';
	requestParams.value.sourcewareCategoryId = state.queryParams.CourseWareTypeID || '';
	Reflect.deleteProperty(requestParams.value, 'Title'); 
	Reflect.deleteProperty(requestParams.value, 'FileType'); 
	Reflect.deleteProperty(requestParams.value, 'CourseWareTypeID'); 
    console.log(requestParams.value)
	getCoursewareData(requestParams.value)
		.then((response: any) => {
            console.log(response)
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.pagination.totalCount;
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
// 选择分类
const selectType = (data: any) => {
	state.queryParams.CourseWareTypeID = data.id;
	handleQuery();
};
// 取消选择
const unSelectType = () => {
	state.queryParams.CourseWareTypeID = null;
	handleQuery();
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const treeSearchRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	treeSearchRef.value.clearKeyword(); // 清空搜索关键词
	treeSearchRef.value.search(); // 搜索
	resetNode();
	setTimeout(() => {
		treeSearchRef.value.setExpandAll(false); // 默认全部收起
	}, 300);
};
// 重置选中的节点
const resetNode = () => {
	state.queryParams.CourseWareTypeID = null;
	handleQuery();
};
// 上传课件
const courseUploadRef = ref<RefType>(); // 修改ref
const onAdd = () => {
	courseUploadRef.value.openDialog();
};
// 批量下载
const onBatchDownload = () => {
	const ids = checkTable.value.map((item: any) => item.attachmentId);
	console.log(ids);
    ElMessageBox.confirm(`您确定要下载选中的课件?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			fileDownloadBatch({
				Source: 'hotline',
				Ids: ids,
			}).then((res: any) => {
				console.log(res);
				let blob: Blob = new Blob([res.data], { type: res.data.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
				let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
				let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
				down.href = href; // 下载地址
				down.download = formatDate(new Date(), 'YYYYmmddHHMMSS')// 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
			});
		})
		.catch(() => {});
}
// 批量删除
const onBatchDelete = () => {
	const ids = checkTable.value.map((item: any) => item.id);
    ElMessageBox.confirm(`您确定要删除选中的课件?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		autofocus: false,
	})
		.then(() => {
			deleteCourseware({ ids: ids }).then(() => {
				queryList();
				ElMessage.success('删除成功');
			});
		})
		.catch(() => {});
}
// 预览下载
const onDownload = (row: any) => {
	ElMessageBox.confirm(`您确定要下载课件，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			fileDownloadByUrl({
				Source: 'hotline',
				Id: row.attachmentId,
			}).then((res: any) => {
				let blob: Blob = new Blob([res.data], { type: res.data.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
				let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
				let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
				down.href = href; // 下载地址
				down.download = row.name // 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
			});
		})
		.catch(() => {});
};
// 修改课件弹窗
const courseEditRef = ref<RefType>(); // 修改ref
const onEdit  = (row: any) => {
	courseEditRef.value.openDialog(row, state.typeOptions);
};
// 删除当前行
const onRowDel = (row: any) => {
  const typeName = row.name.replace(/<span class="keyword-highlight">(.*?)<\/span>/g, '$1');
	ElMessageBox.confirm(`是否确认删除：${typeName}？删除后不可恢复`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
        .then(() => {
			deleteCourseware({id: row.id}).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 表格选中状态
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getCoursewareType();
});
</script>
