<template>
	<div class="videoList_contaier">
		<div class="videoList_top">
			<div>
				<el-button type="primary" @click="addVideo" style="marginRight:10px;width:80px;">添加</el-button>
				<!-- <el-button type="primary" style="width:80px;marginRight:10px;" @click="publishHandle">发布</el-button> -->
			</div>
			<el-input
			placeholder="关键字搜索"
			v-model="search_txt"
			style="maxWidth:520px"
			@input="searchHandle"
			clearable>
				<i slot="prefix" class="el-input__icon el-icon-search"></i>
			</el-input>
		</div>
		<div class="videoList_bot">
			<el-table
			:data="tableData" 
			v-loading="listLoading"
			@selection-change="selectchange" 
			element-loading-text="数据加载中..." 
			border
			style="width:100%;">
				<!-- <el-table-column type="selection" width="40" align="center"></el-table-column> -->
				<el-table-column prop="VideoCoverUrl" label="封面" align="center" width="240">
					<template slot-scope="scope">
						<img :src="scope.row.VideoCoverUrl" alt="" style="width:150px;height:70px">
					</template>
				</el-table-column>
				<el-table-column label="标签" align="center" min-width="100">
					<template slot-scope="scope">{{scope.row.TagsName}}</template>
				</el-table-column>
				<el-table-column label="标题" align="center" min-width="120">
					<template slot-scope="scope">
						<span>{{scope.row.Title}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="ModifyTime" label="更新时间" min-width="150" :formatter="formatter" align="center"></el-table-column>
				<el-table-column label="时长" min-width="110" align="center">
					<template slot-scope="scope">
						<span>{{scope.row.PlaySeconds|formmaterTime}}</span>
					</template>
				</el-table-column>
				<el-table-column label="状态" align="center">
					<template slot-scope="scope">
						<span v-if="scope.row.Status===1" style="color:#46C371;">已发布</span>
						<span v-else>未发布</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" min-width="130">
					<template slot-scope="scope">
						<div v-if="scope.row.Status===0" style="color:#4099ef; font-size:24px;">
							<span class="editsty" style="marginRight:10px;" @click="publishOwn(scope.row)">发布</span>
							<span class="editsty" style="marginRight:10px;" @click="editHandle(scope.row)">编辑</span>
							<span class="deletesty" @click="delHandle(scope.row)">删除</span>
						</div>
						<div v-else>
							<span @click="canclepublish(scope.row)" style="color:red; cursor:pointer;">取消发布</span>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-col :span="24" class="toolbar">
				<el-pagination 
				layout="total,prev,pager,next,jumper" 
				background 
				:current-page="page_no"
				@current-change="handleCurrentChange"
				:page-size="pageSize"
				:total="total"
				style="float:right;">
				</el-pagination>
			</el-col>
		</div>
		<!-- 添加视频弹窗 -->
		<el-dialog
		:visible.sync="isShowdia"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		@close="cancelHandle"
		center
		width="700px">
			<div slot="title" style="display:flex;alignItems:center;">
				<!-- <img :src="title=='添加视频'?$icons.pick:title=='申请解冻'?$icons.lock:title=='申请延期'?$icons.delay:''" style="color:#fff;width:16px;height:16px;marginRight:5px;"> -->
				<span style="fontSize:16px;">{{dialog_title}}</span>
			</div>
			<el-form 
			:model="diaform" 
			:rules="diaRule" 
			ref="diaform" 
			label-position="right" 
			label-width="100px"
			 @submit.native.prevent>
				<el-form-item prop="title" label="标题">
					<el-input type="text" v-model="diaform.title" placeholder="请输入标题" size="small" style="width:330px;"></el-input>
				</el-form-item>
				<el-form-item prop="tag" label="标签">
					 <el-checkbox-group v-model="diaform.tag">
						<el-checkbox-button v-for="item in tagList" :label="item.TagsId" :key="item.TagsId" >{{item.TagsName}}</el-checkbox-button>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item prop="video_url" label="视频">
					<input type="file" name="file" @change="fileSelected()" id="file" class="true-file" style="display:none;">
					<el-input type="text" v-model="diaform.video_url" placeholder="上传视频" size="medium" style="width:330px;"></el-input>
					<el-button type="primary" size="medium" @click.native="clickinput(1)" :loading="videoloading">{{videoloading?'上传中':'选择视频'}}</el-button>
					<span style="display:block;fontSize:12px;height:24px;lineHeight:24px;color:#f00;" v-if="diaform.duration">(时长{{diaform.duration|formmaterTime}})</span>
				</el-form-item>
				<el-form-item prop="post" label="封面">
					<input type="file" name="file2" @change="fileSelected2()" id="file2" class="true-file" style="display:none;">
					<el-button type="primary" size="medium" @click="clickinput(2)" style="display:block;">选择封面</el-button>
					<img :src="diaform.post" alt="" v-if="diaform.post" width="215" height="100" style="margin-top:10px;">
					<!-- <i class="el-icon-plus" style="font-size:28px;color:#8c939d;width:78px;height:78px;line-height: 78px;text-align: center;border:dashed 1px #aaa;" @click="clickinput(2)"></i> -->
				</el-form-item>
			</el-form>
			<div style="display:flex;justify-content:flex-end;margin:75px 0 50px;">
				<el-button type="primary" style="width:80px;marginRight:10px;" @click="saveHandle">保存</el-button>
				<el-button type="primary" plain style="width:80px;marginRight:10px;" @click="publishDia">发布</el-button>
				<el-button style="width:80px;" @click="cancelHandle">取消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { videoInterence,customInterence } from '@/api/api.js'
export default {
	name:'',
	components: {},
	filters: {
		/* 处理秒为时分秒 */
		formmaterTime(value) {
			var secondTime = parseInt(value);// 秒
			var minuteTime = 0;// 分
			var hourTime = 0;// 小时
			if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
				//获取分钟，除以60取整数，得到整数分钟
				minuteTime = parseInt(secondTime / 60);
				//获取秒数，秒数取佘，得到整数秒数
				secondTime = parseInt(secondTime % 60);
				//如果分钟大于60，将分钟转换成小时
				if(minuteTime > 60) {
						//获取小时，获取分钟除以60，得到整数小时
						hourTime = parseInt(minuteTime / 60);
						//获取小时后取佘的分，获取分钟除以60取佘的分
						minuteTime = parseInt(minuteTime % 60);
				}
			}
			var result = "" + parseInt(secondTime) + "秒";
			if(minuteTime > 0) {
			result = "" + parseInt(minuteTime) + "分" + result;
			}
			if(hourTime > 0) {
			result = "" + parseInt(hourTime) + "小时" + result;
			}
			return result;
		}
	},
	data () {
		return {
			configHeader:{
				Authorization:localStorage.getItem('auth')
			},
			uploadurl:process.env.API_ROOT+'/resource/image/upload',//上传图片
			search_txt:'',//关键字搜索
			total:0,
			pageSize:10,
			page_no:1,
			selectId:[],//选中的
			tableData:[],//表格数据
			isShowdia:false,
			dialog_title:'添加视频',
			isEdit:false,
			videoloading:false,//上传中
			tagList:[],//标签
			diaform: {
				id:'',
				title:'',
				tag:[],
				video_url:'',
				duration:'',//时长
				post:''
			},//弹窗表单
			diaRule:{
				title:[
					{ required: true, message: '标题不能为空', trigger: 'blur' },
				],//
				tag:[
					{ required: true, message: '标签不能为空', trigger: 'change' },
				],//
				// video_url:[
				// 	{ required: true, message: '视频地址不能为空', trigger: 'blur' },
				// ],
				post:[
					{ required: true, message: '视频封面不能为空', trigger: 'blur' },
				]
			}
		};
	},
	methods: {
		/* 获取列表 */
		getDataList() {
			videoInterence.getVideoList({
				PageSize:this.pageSize,
				CurrentIndex:this.page_no,
				KeyWord:this.search_txt
			}).then(res => {
				if(res.Ret === 200) {
					this.total = res.Data.Paging.Totals;
					this.tableData = res.Data.List?res.Data.List:[];
				}
			})
		},
		/* 获取标签分类 */
		getTag() {
			videoInterence.tagList().then(res => {
				if(res.Ret === 200) {
					this.tagList = res.Data.List || [];
				}
			})
		},
		/* 关键字搜索 */
		searchHandle() {
			this.page_no = 1;
			this.getDataList();
		},
		/* 选择项发生变化 */
		selectchange(arr) {
			this.selectId = arr.map((item)=>{ return item.VideoId});
		},
		// 页码改变
		handleCurrentChange(page) {
			this.page_no = page;
			this.getDataList();
		},
		/* 添加视频 */
		addVideo() {
			this.dialog_title = '添加视频';
			this.isShowdia = true;
		},
		/* 取消弹窗 */
		cancelHandle() {
			this.diaform = {
				id:'',
				title:'',
				tag:[],
				video_url:'',
				post:''
			}
			this.isEdit = false;
			this.videoloading = false;
			this.isShowdia = false;
			this.$refs.diaform.resetFields();
		},
		/* 图片上传 */
		fileSelected2() {
			const that = this;
		    if( document.getElementById('file2').files[0] ){
		        let hostfile = document.getElementById('file2').files[0];
		        let size = Math.floor(hostfile.size / 1024 / 1024);
		        if( size>200 ){
		            that.$message.error('上传文件大小不能大于200M！');
		            hostfile = {};
		            return false
		        }
		        if( hostfile.name.toLowerCase().includes('.jpg') || hostfile.name.toLowerCase().includes('.png')|| hostfile.name.toLowerCase().includes('.gif')){
		        	let form = new FormData();
		        	form.append('file',hostfile);  //hostfile.name
					customInterence.upload(form).then((res) => {
						if( res.Ret === 200 ){
							// that.$message.success( '上传成功' );
							this.$set(this.diaform,'post',res.Data.ResourceUrl);
						}
						$("#file2").val('');
						hostfile = {};
					});
				}else{
					that.$message.error('上传文件格式不正确！');
		        }
		    } 
		},
		clickinput(type){  //上传模拟点击
			type==1?$("#file").click():$("#file2").click();
		},
		fileSelected(){  //选择视频上传
			const that = this;
		    if( document.getElementById('file').files[0] ){
		        let hostfile = document.getElementById('file').files[0];
		        if( hostfile.name.toLowerCase().includes('.mp4') || hostfile.name.toLowerCase().includes('.avi')){
		        	let form = new FormData();
		        	form.append('file',hostfile);  //hostfile.name
					that.videoloading=true;
					videoInterence.upload(form).then((res) => {
						if( res.Ret === 200 ){
							// that.$message.success( '上传成功' );
							this.diaform.video_url = res.Data.ResourceUrl;
							this.diaform.duration = res.Data.PlaySeconds;
						}
						that.videoloading=false;
						$("#file").val('');
						hostfile = {};
					});
				}else{
					that.$message.error('上传文件格式不正确！');
		        }
		    } 
		},
		/* 保存视频 新增视频*/
		saveHandle() {
			this.$refs.diaform.validate((valid) => {
				if (valid) {
					// console.log(this.diaform)
					if(!this.isEdit) {
						videoInterence.saveVideo({
							PlaySeconds:Number(this.diaform.duration),
							TagsIdStr:this.diaform.tag.join(','),
							Title:this.diaform.title,
							VideoCoverUrl:this.diaform.post,
							VideoUrl:this.diaform.video_url
						}).then(res => {
							if(res.Ret === 200) {
								this.$message.success('新增视频成功')
								this.cancelHandle();
								this.page_no = 1;
								this.getDataList();
							}
						})
					}else {
						videoInterence.editVideo({
							VideoId:Number(this.diaform.id),
							PlaySeconds:Number(this.diaform.duration),
							TagsIdStr:this.diaform.tag.join(','),
							Title:this.diaform.title,
							VideoCoverUrl:this.diaform.post,
							VideoUrl:this.diaform.video_url
						}).then(res => {
							if(res.Ret === 200) {
								this.$message.success('修改视频成功')
								this.cancelHandle();
								this.page_no = 1;
								this.getDataList();
							}
						})
					}
				}
			})	
		},
		/* 编辑 */
		editHandle(item) {
			let tagArr = item.TagsId.split(',').map(item => {
				return Number(item);
			})
			this.diaform = {
				id:item.VideoId,
				title:item.Title,
				tag:tagArr,
				video_url:item.VideoUrl,
				duration:item.PlaySeconds,//时长
				post:item.VideoCoverUrl
			}
			console.log(this.diaform)
			this.isEdit = true;
			this.dialog_title = '修改视频';
			this.isShowdia = true;
		},
		/* 删除 */
		delHandle(item) {
			this.$confirm('确认删除这条视频吗?','提示',{
				type:'warning'
			}).then(() => {
				videoInterence.delVideo({VideoId:parseInt(item.VideoId)}).then(res =>{
					if( res.Ret === 200 ){
						this.$message.success( res.Msg );
						this.page_no = 1;
						this.getDataList();
					}
				});
			}).catch(() => {});
		},
		/* 取消发布 */
		canclepublish(item) {
			videoInterence.cancelPublish({
				VideoIds:String(item.VideoId)
			}).then(res => {
				if(res.Ret === 200) {
					this.$message.success('取消发布成功！');
					item.Status = 0;
				}
			})
		},
		/* 弹窗发布 先保存再发布 */
		publishDia() {
			this.$refs.diaform.validate((valid) => {
				if (valid) {
					if(!this.isEdit) {
						videoInterence.saveVideo({
							PlaySeconds:Number(this.diaform.duration),
							TagsIdStr:this.diaform.tag.join(','),
							Title:this.diaform.title,
							VideoCoverUrl:this.diaform.post,
							VideoUrl:this.diaform.video_url
						}).then(res => {
							if(res.Ret === 200) {
								videoInterence.publish({
									VideoIds:String(res.Data.VideoId)
								}).then(res2 => {
									if(res2.Ret === 200) {
										this.$message.success('视频发布成功！');
										this.cancelHandle();
										this.page_no = 1;
										this.getDataList();
									}
								})
							}
						})
					}else {
						videoInterence.publish({
							VideoIds:String(this.diaform.id)
						}).then(res => {
							if(res.Ret === 200) {
								this.$message.success('视频发布成功！');
								this.cancelHandle();
								this.page_no = 1;
								this.getDataList();
							}
						})
					}
				}
			})		
		},
		/* 单条发布 */
		publishOwn(item) {
			videoInterence.publish({
				VideoIds:String(item.VideoId)
			}).then(res => {
				if(res.Ret === 200) {
					this.$message.success('视频发布成功！');
					this.page_no = 1;
					this.getDataList();
				}
			})
		},
		/* 群发布 */
		publishHandle() {
			if(this.selectId.length) {
				videoInterence.publish({
					VideoIds:this.selectId.join(',')
				}).then(res => {
					if(res.Ret === 200) {
						this.$message.success('视频发布成功！');
						this.page_no = 1;
						this.getDataList();
					}
				})
			}else {
				this.$message.warning('请选择需要发布的视频！')
			}
		}
	},
	created() {},
	mounted() {
		this.getTag();
		this.getDataList();
	},
}
</script>
<style lang='scss' scoped>
.videoList_contaier {
	.videoList_top {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 28px;
		padding: 20px 30px;
		background: #fff;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
	.videoList_bot {
		min-height: calc(100vh - 335px);
		padding: 30px 30px 80px;
		background: #fff;
		position: relative;
		border: 1px solid #ECECEC;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
}
</style>