<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">
			<el-form-item label="计划名称" prop="TrainName">
				<el-input v-model="queryParams.TrainName" placeholder="请输入计划名称" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="培训类别" prop="ZcsZhuanYe">
				<el-select v-model="queryParams.ZcsZhuanYe" placeholder="请选择培训类别" clearable>
					<el-option v-for="dict in dict.type.jxjy_zhuanye" :key="dict.value" :label="dict.label"
						:value="dict.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="审核状态" prop="ShenHe">
				<el-select v-model="queryParams.ShenHe" placeholder="请选择审核状态" clearable>
					<el-option  label="未审核" value="0" />
					<el-option  label="已审核" value="1" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					>新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
					>修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					>删除</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="TrainingList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="培训类别" align="center">
				<template slot-scope="scope"> 
					<dict-tag :options="dict.type.jxjy_zhuanye" :value="scope.row.ZYId" /> 
				</template>
			</el-table-column>
			<el-table-column label="课程名称" align="center" prop="ClassName" width="400px" />
			<el-table-column label="类型" align="center">
				<template slot-scope="scope">
					<dict-tag :options="dict.type.jxjy_kclx" :value="scope.row.ClassSort" />
				</template>
			</el-table-column>
			<el-table-column label="学时" align="center" prop="XueShi" />
			<el-table-column label="审核" align="center" prop="ShenHe">
				<template slot-scope="scope">
					<div>
						<span v-if="scope.row.ShenHe == 0" >
							<span style="color: #F56C6C;margin-right: 10px;">
								未审核
							</span>
						</span>
						<span v-else>
							<span style="margin-right: 10px;">
								已审核
							</span>
						</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
						>修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						>删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
			@pagination="getList" />

		<!-- 添加或修改继续教育培训计划对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="80vw" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="100px">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="培训类别" prop="ZYId">
							<el-select v-model="form.ZcsZhuanYe" disabled placeholder="请选择培训类别">
								<el-option v-for="dict in dict.type.jxjy_zhuanye" :key="dict.value" :label="dict.label"
									:value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="课程类型" prop="ClassSort">
							<el-select v-model="form.ClassSort" placeholder="请选择培训类别">
								<el-option v-for="dict in dict.type.jxjy_kclx" :key="dict.value" :label="dict.label"
									:value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="学时" prop="XueShi">
							<div style="display: flex;align-items: center;">
								<el-input v-model="form.XueShi" placeholder="请输入学时" style="width: 80%;" /><span style="margin-left: 4px;">个</span>
							</div>
						</el-form-item>
					</el-col>
					<el-col :span="24"> 
						<el-form-item label="课程名称" prop="ClassName">
							<el-input v-model="form.ClassName" placeholder="请输入培训计划名称" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="是否审核" prop="ShenHe">
							<el-select v-model="form.ShenHe" placeholder="请选择审核状态" clearable>
								<el-option  label="未审核" value="0" />
								<el-option  label="已审核" value="1" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="2">
						<div style="float: right;height: 36px;line-height: 36px;font-weight: bold;">
							添加文件
						</div>
					</el-col>
					<el-col :span="22">
						<el-row :gutter="20" v-for="(v,i) in form.videos">
							<el-col :span="4">
								<el-form-item label="类型" label-width="60px" prop="type"  >
									<el-select v-model="v.type" placeholder="请选择培训类别">
										<el-option v-for="dict in dict.type.file_type" :key="dict.value" :label="dict.label"
											:value="dict.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item :label="'文件'+(i+1)" label-width="60px"  >
									<!-- <el-upload action="uploadUrl" :action="uploadUrl"  :limit="1"  :file-list="fileList[i]" :before-upload="function(file){beforeUpload(file,i)} " :http-request="chunkedUpload" :on-success="function(file){return handleAvatarSuccess(file,i)}" :on-remove="function(file){return handleRemove(file,i)}" :on-error="function(file){return haveError(file,i)}" v-if="v.type == 1">
										<el-button size="small" type="primary" v-if="v.VPath == null">点击上传</el-button>
									</el-upload> -->
									<el-upload action="uploadUrl" :action="uploadUrl" v-loading="v.load"  :limit="1"  :file-list="fileList[i]" :before-upload="function(file){return beforeUpload(file,i)} " :http-request="function(parme){return chunkedUpload(parme,i)} " :on-remove="function(file){return handleRemove(file,i)}" :on-error="function(file){return haveError(file,i)}" v-if="v.type == 1">
										<el-button size="small" type="primary" v-if="v.VPath == null">点击上传</el-button>
									</el-upload>
									<el-input v-model="v.VPath" v-else placeholder="请输入文件路径" />
								</el-form-item>
							</el-col>
							<el-col :span="6">
								<el-form-item label="文件名称" label-width="80px" >
									<el-input v-model="v.VName" placeholder="请输入文件名称" />
								</el-form-item>
							</el-col>
							<el-col :span="4" v-if="v.type == 1">
								<el-form-item label="视频总时长(分钟)"  label-width="120px">
									<el-input v-model="v.Undef1" placeholder="视频总时长" readonly />
								</el-form-item>
							</el-col>
							<el-col :span="3">
								<div style="display: flex;align-items: center;justify-content: space-between;">
									<el-button type="info" :disabled="v.VPath == null" @click="yvlan(v)">预览</el-button>
									<el-button type="primary" :disabled="v.load" v-if="i==0" @click="addVideos">新增文件</el-button>
									<el-button type="danger" :disabled="v.load" v-if="i!=0" @click="delVideos(i)">删除文件</el-button>
								</div>
							</el-col>
						</el-row>
					</el-col>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="预览" :visible.sync="ylShow" top="6vh" width="60vw" append-to-body>
			<div v-if="ylShow">
				<div v-if="ylForm.type == 1">
					<video-player ref="videoPlayer" class="video-player vjs-custom-skin" :playsinline="false" :options="playOptions" />
				</div>
				<div v-else-if="ylForm.type == 2" style="height: 70vh;">
					<vuePptx :src="ylForm.VPath"></vuePptx>
				</div>
				<div v-else style="height: 70vh;"> 
					<iframe :src="ylForm.VPath" style="width: 100%;height: 100%;"></iframe> 
				</div>
				
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listClass,
		getClass,
		addClass,
		updateClass,
		delClass,
		isUpload
	} from "@/api/xiehui/jxjy/kcgl"; 
	import SparkMD5 from 'spark-md5'
	import axios from 'axios' 
	import { getToken } from "@/utils/auth";
	export default {
		name: "KechengGl",
		dicts: ['jxjy_zhuanye',"jxjy_kclx","file_type"],
		data() {
			return {
				uploadUrl: process.env.VUE_APP_BASE_API + "/manage/video/upload", //上传路径
				uploadPromises: [], // 记录并发上传分片的线程
				uploadPercentage: 0, //上传进度
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 继续教育培训计划表格数据
				TrainingList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
				
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {
					ClassSort:{
						required: true,
						message: '请选择课程类型',
						trigger: ['blur', 'change']
					},
					XueShi:{
						required: true,
						message: '请填写学时',
						trigger: ['blur', 'change']
					},
					ClassName:{
						required: true,
						message: '请填写课程名称',
						trigger: ['blur', 'change']
					},
					ShenHe:{
						required: true,
						message: '请选择是否审核',
						trigger: ['blur', 'change']
					}
					
				},
				fileList:[],//图片列表
				ylShow:false,
				ylForm:{},
				videoForm:{},
				playOptions: {
					height: "200px",
					width: "100%",
					playbackRates: [1.0], // 可选的播放速度
					autoplay: false, // 如果为true,浏览器准备好时开始回放
					muted: false, // 默认情况下静音播放
					loop: false, // 是否视频一结束就重新开始
					preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据，auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
					language: "zh-CN",
					aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值，值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
					fluid: true, // 当true时，Video.js player将拥有流体大小，换句话说，它将按比例缩放以适应其容器
					sources: [{
						type: "application/x-mpegURL", // 类型
						src: null, // url地址，在使用本地的资源时，需要用require()引入，否则控制台会报错
					}, ],
					// poster: "./gcy-logo-200.png", // 设置封面地址
					notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息
					controlBar: {
						currentTimeDisplay: true,
						progressControl: true, // 是否显示进度条
						// progressControl: true, // 是否显示进度条
						playbackRateMenuButton: true, // 是否显示调整播放倍速按钮
						timeDivider: true, // 当前时间和持续时间的分隔符
						durationDisplay: true, // 显示持续时间
						remainingTimeDisplay: true, // 是否显示剩余时间功能
						fullscreenToggle: true, // 是否显示全屏按钮
					},
				},
			};
		},
		created() {
			this.getList();
		},
		methods: {
			/** 查询继续教育培训计划列表 */
			getList() {
				this.loading = true;
				listClass(this.queryParams).then(response => {
					this.TrainingList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					ZYId:'8',
					ZcsZhuanYe:'8',
					ClassName:null,
					ClassSort:null,
					XueShi:null,
					ShenHe:null,
					videos:[]
				};
				this.fileList = []
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.ClassId)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.form.videos = [{VName:null,Undef1:null,VPath:null,type:null,load:false}]
				this.fileList = [[]]
				this.open = true;
				this.title = "添加继续教育课程";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const ClassId = row.ClassId || this.ids
				getClass(ClassId).then(response => {
					this.form = response.data;
					if(response.data.videos.length >0){
						this.fileList = response.data.videos.map( item => {
							let obj = [{ name:item.VPath,url:item.VPath,type:item.type}]
							return obj
						})
					}else{
						this.form.videos = [{VName:null,Undef1:null,VPath:null,type:null,load:false}]
						this.fileList = [[]]
					}
					
					this.open = true;
					this.title = "修改继续教育课程";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.ClassId != null) {
							updateClass(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addClass(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ClassIds = row.ClassId || this.ids;
				this.$modal.confirm('您确认删除吗？？').then(function() {
					return delClass(ClassIds);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			//修改状态
			changeType(row,type){
				this.reset();
				const ClassId = row.ClassId || this.ids
				getClass(ClassId).then(response => {
					this.form = response.data;
					this.form.ShenHe = type
					this.$confirm('您要改变当前审核状态吗?', '提示', {
					  confirmButtonText: '确定',
					  cancelButtonText: '取消',
					  type: 'info'
					}).then(() => {
						updateClass(this.form).then(response => {
							this.$modal.msgSuccess("修改成功");
							this.getList();
						}); 
					}).catch(() => {
				          
					});
				});
			},
			//
			handleAvatarSuccess(file,index){ 
				this.form.videos[index].VPath = file.fileName
				this.form.videos[index].Undef1 = file.minute+Math.ceil((file.second/60)* 100) / 100
			},
			handleRemove(file,index){
				this.videoForm = {}
				this.uploadPromises = []
				this.form.videos[index].VPath = null
				this.form.videos[index].Undef1 = null
			},
			haveError(filr,index){
				this.videoForm = {}
				this.uploadPromises = []	
				this.form.videos[index].VPath = null
				this.fileList[index] = []
			},
			//添加视频
			addVideos(){
				this.fileList.push([])
				this.form.videos.push({VName:null,Undef1:null,VPath:null,type:null,load:false})
			},
			//删除视频
			delVideos(i){
				this.fileList.splice(i,1)
				this.form.videos.splice(i,1)
			},
			yvlan(v){
				this.ylForm = {...v}
				if(v.type == 1){
					this.playOptions.sources[0].src = process.env.VUE_APP_BASE_API+v.VPath
				}
				this.ylShow = true
			},
			
			//上传相关方法
			beforeUpload: async function(file,i) { 
				this.form.videos[i].load = true
				// 在上传之前获取视频的宽高和分辨率
				const video = document.createElement('video')
				video.src = URL.createObjectURL(file)
				video.preload = 'metadata'
				const loadedMetadata = new Promise(resolve => {
					video.onloadedmetadata = () => {
						window.URL.revokeObjectURL(video.src)
						const width = video.videoWidth
						const height = video.videoHeight 
						this.videoForm.width = width
						this.videoForm.height = height
						this.form.videos[i].Undef1 = (video.duration/60).toFixed(2) 
						resolve();
					}
				});
				// 等待视频的宽高和分辨率获取完成
				await loadedMetadata;
			
				// 计算文件的md5值
				const reader = new FileReader()
				const md5Promise = new Promise(resolve => {
					reader.onload = () => {
						const spark = new SparkMD5.ArrayBuffer()
						spark.append(reader.result)
						const md5 = spark.end(false)
						this.videoForm.identifier = md5 // 将MD5值存储到form中
						resolve(md5);
					}
				});
				reader.readAsArrayBuffer(file); // 读取文件内容并计算MD5值
				const md5 = await md5Promise;
			
				// 检查文件是否已被上传
				const response = await isUpload(md5); 
				if (response.msg === "存在") { 
					// 取消上传
					this.$message({
						type:"warning",
						message:"文件已存在"
					})
					this.form.videos[i].load = false
					this.$refs.upload.abort(file)
					return false;
				} else {
					return true;
				}
			},
			chunkedUpload({
				file
			},index) {
				this.form.videos[index].load = true
				const totalSize = file.size
				const chunkCount = Math.ceil(totalSize / (5 * 1024 * 1024)) // 每个分片5MB
				// 创建分片上传请求数组
				// 上传分片
				for (let i = 0; i < chunkCount; i++) {
					const start = i * (5 * 1024 * 1024)
					const end = Math.min((i + 1) * (5 * 1024 * 1024), totalSize)
					const chunk = file.slice(start, end)
					const formData = new FormData()
					formData.append('file', chunk)
					formData.append('filename', file.name)
					formData.append('totalChunks', chunkCount)
					formData.append('chunkNumber', i)
					formData.append('identifier', this.videoForm.identifier) // 添加文件的MD5值作为参数
					// 发送分片上传请求
					const source = axios.CancelToken.source() // 创建cancelToken
					const uploadPromise = this.uploadChunk(formData, source.token, (progressEvent) => { 
						this.uploadPercentage = Math.round((progressEvent.loaded / progressEvent.total) *100) // 更新进度条的值;
					}).catch(error => {
						
						// 弹出告警消息
						this.$message({
							type: 'error',
							message: '视频上传失败！'
						})
					})
					this.uploadPromises.push({
						promise: uploadPromise,
						source
					}) // 保存cancelToken
				}
				// 等待所有分片上传完成
				return Promise.all(this.uploadPromises)
					.then(responses => { 
						responses.forEach(res=>{ 
							res.promise.then(qwe=>{ 
								if(qwe.data.code==200 && qwe.data.flag == 1){
									this.form.videos[index].VPath = qwe.data.msg
									this.form.videos[index].load = false
									this.videoForm = {}
									this.uploadPromises = []
								}
							})
							
						}) 
					}).catch(error => { 
						this.form.videos[index].load = false 
						this.$refs.upload.abort(file)
					})
			},
			/**更新进度*/
			onProgress(event, file) {
				this.uploadPercentage = Math.floor((event.loaded / event.total) * 100);
			}, 
			/**上传分片*/
			uploadChunk(formData, onProgress) {
				return axios.post(process.env.VUE_APP_BASE_API + '/manage/video/upload', formData, {
					headers:{
						"Authorization" : "Bearer " + getToken()
					},
					onUploadProgress: onProgress // 添加进度回调
				}).then(response => {
					return response
				})
			},  
		}
	};
</script>
<style lang="scss" scoped>
	::v-deep .el-input.is-disabled .el-input__inner {
		background-color: #fff !important;
		color: #303133 !important
	}
	::v-deep .el-upload{
		display: block !important;
	}
</style>