<template>
	<div id="pptlist">
		<el-card class="box-card">
			<div slot="header" class="header">
				<el-form :inline="true" :model="searchform" @submit.native.prevent>
					<el-form-item label="">
						<el-button type="primary" size="medium" @click="addPPT">添加ppt</el-button>
					</el-form-item>
					<el-form-item style="float:right;">
						<el-input @input="search" placeholder="标题/创建人" v-model="searchform.key_word" clearable size="medium">
							<i class="el-icon-search" slot="prefix" @click="search"></i>
						</el-input>
					</el-form-item>
		  		</el-form>
			</div>
			<template>
				<el-table :data="tableData" v-loading="listLoading" element-loading-text="数据加载中..." row-key="id" border default-expand-all :tree-props="{children:'children',hasChildren:'hasChildren'}">
					<el-table-column prop="Title" label="标题" align="center" min-width="140">
						<template slot-scope="scope"> 
							<span v-if="scope.row.Version === 1">{{scope.row.Title}}</span> 
							<span @click="getpptdtl(scope.row.PptId,scope.row.IsAuth)" style="color:#4099ef; cursor:pointer;" v-else>{{scope.row.Title}}</span> 
						</template>
					</el-table-column>
					<el-table-column prop="ModifyTime" label="更新时间" min-width="110" :formatter="formatter" align="center"></el-table-column>
					<el-table-column prop="AdminRealName" label="创建人" align="center" min-width="140">
					</el-table-column>
					<el-table-column label="操作" align="center" min-width="200">
						<!-- <template slot-scope="scope" v-if="scope.row.IsAuth"> -->
						<template slot-scope="scope">
							<div style="color:#4099ef; font-size:24px;">
								<span class="editsty" @click="getpptdtl(scope.row.PptId,scope.row.IsAuth)" v-if="scope.row.Version === 2">预览发布</span>
								&nbsp;
								<!-- new -->
								<template v-if="scope.row.Version === 2">
									<a @click.prevent="downloadPpt(scope.row.PptUrl)" :download="scope.row.Title" class="editsty">下载ppt</a>
									&nbsp;
									<a @click.prevent="downloadPpt(scope.row.PptxUrl)" :download="scope.row.Title" class="editsty">下载pptx</a>
								</template>
								<!-- old -->
								<a @click.prevent="downloadPptOld(scope.row.PptId,'',scope.row.PptUrl)" :download="scope.row.Title" class="editsty" v-else>下载</a>
								&nbsp;
								<span class="editsty" @click="edititem(scope.row)" v-if="scope.row.IsAuth&&scope.row.Version === 2">编辑</span>
								&nbsp;
								<span class="deletesty" @click="deleteitem(scope.row)" v-if="scope.row.IsAuth">删除</span>
							</div>
		  	    		</template>
					</el-table-column>
				</el-table>
			</template>
			<el-col :span="24" class="toolbar">
		  		<el-pagination v-if="ispage" layout="total,prev,pager,next,jumper" background @current-change="handleCurrentChange" :page-size="pageSize" @size-change="handleSizeChange" :total="total" style="float:right;"></el-pagination>
		  	</el-col>
		</el-card>
		<!-- 添加账号弹框 -->
		<el-dialog :title="isadd?'新增banner':'编辑banner'" :modal-append-to-body='false' :visible.sync="aeDialog" :close-on-click-modal="false" :center="true" v-dialogDrag custom-class="dialogclass" width="510px">
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="isadd?$icons.add:$icons.edit" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">{{isadd?'新增banner':'编辑banner'}}</span>
			</div>
			<el-form :model="aeForm" :rules="aerules" ref="aeForm" label-position="right" label-width="0px" class="demo-aeForm" id="login-container" @submit.native.prevent>
				<el-form-item prop="img_url" label="">
					<input type="file" name="file" @change="fileSelected()" id="file" class="true-file" style="display:none;">
					<el-input type="text" v-model="aeForm.img_url" placeholder="上传图片" readonly size="medium" style="width:350px;"></el-input>
					<el-button type="primary" size="medium" @click.native="clickinput" :loading="uploadloading">{{uploadloading?'上传中':'选择图片'}}</el-button>
				</el-form-item>
				<el-form-item prop="jump_url" label="">
					<el-input type="text" v-model="aeForm.jump_url" placeholder="绑定跳转链接" size="medium" style="width:430px;"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" style="text-align:right;">
				<el-button type="primary" plain size="medium" @click.native="aeDialog=false">取 消</el-button>
				<el-button type="primary" size="medium" @click.native="saveDialog">保 存</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { pptlist,pptdelete,pptdetail } from 'api/api.js';
export default{
	data(){
		return {
			searchform:{
				key_word:''
			},
			hostapi:process.env.API_ROOT+'/ppt/download',
			PageIndex:1,
			total:0,
			pageSize:15,
			ispage:true,
			listLoading:false,
			tableData:[],
			aeDialog:false,
			uploadloading:false,
			aeForm:{
				img_url:'',
				banner_type:1,
				jump_url:'',
			},
			aerules:{
				img_url:[{
					required:true,
					message:'请上传图片',
					trigger:'blur'
				}],
				jump_url:[{
					required:true,
					message:'请输入跳转链接',
					trigger:'blur'
				}],
			},
			isadd:true,
		}
	},
	mounted(){
		this.getlist();
		// document.onkeydown=e=>{
		// 	let keyval=window.event.keyCode;
		//     if( keyval===13 && this.$route.path === '/pptlist'){
		// 		this.getlist();
		//     }
		// }
	},
	methods:{
		getpptdtl(id,auth){
			// pptdetail({ppt_id:id}).then(res =>{
			// 	if( res.Ret === 200 ){
			// 		let pptpage=res.result.ppt_pages || [];
			// 		let firstform={
			// 			title:res.result.ppt.title,
			// 			report_type:res.result.ppt.report_type,
			// 			ppt_date:res.result.ppt.ppt_date || http.dateFormatter(new Date(),false),
			// 			img_url:pptpage[0].img_url,
			// 			ppt_pages_id:parseInt(pptpage[0].ppt_pages_id),
			// 			ppt_id:parseInt(pptpage[0].ppt_id),
			// 			back_index:parseInt(pptpage[0].back_index)
			// 		}
			// 		let pageitem=[];
			// 		pptpage.forEach((item,i)=>{
			// 			if( i!=0 ){
			// 				pageitem.push({
			// 					title:item.title,
			// 					ppt_pages_id:parseInt(item.ppt_pages_id),
			// 					ppt_id:parseInt(item.ppt_id),
			// 					resource_id:parseInt(item.resource_id)
			// 				});
			// 			}
			// 		});
			// 		sessionStorage.setItem('firstform',JSON.stringify(firstform));
			// 		sessionStorage.setItem('pageitem',JSON.stringify(pageitem));
					sessionStorage.setItem('ppt_id',id);
					sessionStorage.setItem('ppt_auth',auth);
					// this.$router.push({path:'/pptdtl'});
					let {href} = this.$router.resolve({name:'预览ppt'});
					window.open(href,'_blank');
			// 	}
			// });
		},
		addPPT() {
			let {href} = this.$router.resolve({path:'/addpptNew'});
			window.open(href,'_blank');
		},
		clickinput(){  //上传模拟点击
			$("#file").click();
		},
		fileSelected(){  //选择文件上传
			const that = this;
		    if( document.getElementById('file').files[0] ){
		        let hostfile = document.getElementById('file').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('.png') || hostfile.name.toLowerCase().includes('.jpg') || hostfile.name.toLowerCase().includes('.jpeg') ){
		        	let form = new FormData();
		        	form.append('file',hostfile);  //hostfile.name
					that.uploadloading=true;
					bannerupload(form).then((res) => {
						if( res.code=='0' ){
							// that.$message.success( '上传成功' );
							that.aeForm.img_url=res.data;
						}
						that.uploadloading=false;
						$("#file").val('');
						hostfile = {};
					});
				}else{
					that.$message.error('上传文件格式不正确！');
		        }
		    } 
		},
		edititem(item){  //去编辑
			sessionStorage.setItem('ppt_auth',item.IsAuth);
			// this.$router.push({path:'/editpptNew',query:{id:item.PptId}});
			let {href} = this.$router.resolve({path:'/editpptNew',query:{id:item.PptId}});
			window.open(href,'_blank');
		},
		deleteitem(item){  //删除
			this.$confirm('确认删除该ppt文件?','提示',{
				type:'warning'
			}).then(() => {
				pptdelete({PptId:parseInt(item.PptId)}).then(res =>{
					if( res.Ret === 200 ){
						this.$message.success( res.Msg );
						this.getlist();
					}
				});
			}).catch(() => {});
		},
		saveDialog(){  //保存
			this.$refs.aeForm.validate((valid)=>{
				if( valid ){
					let params={img_url:this.aeForm.img_url,banner_type:this.aeForm.banner_type,jump_url:this.aeForm.jump_url};
					if( this.isadd ){
						banneradd(params).then(res =>{
							if( res.Ret === 200 ){
								this.$message.success( '上传成功' );
								this.getlist();
								this.aeDialog=false;
							}
						});
					}else{
						params.banner_id=this.aeForm.banner_id;
						banneredit(params).then(res =>{
							if( res.Ret === 200 ){
								this.$message.success( '上传成功' );
								this.getlist();
								this.aeDialog=false;
							}
						});
					}
				}
			});
		},
		aeDialogTrue(){  //去新增
			this.aeForm={img_url:'',jump_url:'',banner_type:1};
			this.isadd=true;
			this.aeDialog=true;
		},
		getlist(){  //获取用户列表
			let params={CurrentIndex:this.PageIndex,PageSize:this.pageSize,KeyWord:this.searchform.key_word};
			this.listLoading = true;
			pptlist(params).then((res) => {
				if( res.Ret === 200 ){
					this.tableData = res.Data.List || [];
					this.total=parseInt(res.Data.Paging.Totals);
				}
				this.listLoading = false;
			});
		},
		search(){  //搜索
			this.ispage = false;
			this.$nextTick(() => {
				this.PageIndex = 1;
				this.getlist();
				this.ispage = true;
			});
		},
		handleCurrentChange(current){  //分页页码跳转
			this.PageIndex = current;
			this.getlist();
		},
		handleSizeChange(val){    //分页页码改变
	        this.pageSize=val;
	        this.getlist();
		   },
		downloadPpt(url){
			if(url) {
				// let files = [url1,url2]
				let isIE=false;
				if (!!window.ActiveXObject || 'ActiveXObject' in window) {
					isIE=true;
				} else {
					isIE=false;
				}
				// files.forEach(url => {
						// console.log(url)
						if (isIE) { // IE
								window.open(url, '_blank')
							} else {
								let a = document.createElement('a') // 创建a标签
								a.href = url // 设置下载地址
								a.download = '' // 设置下载文件名
								a.click();
						}
				// })
			}else {
				this.$message.warning('请先预览发布！')
			}
		},
		downloadPptOld(pptId,href,downurl){
			if(downurl) {
				let files = ['/ppt/downloadpptx'+'?PptId='+parseInt(pptId),'/ppt/download'+'?PptId='+parseInt(pptId)] // 所有文件
				let isIE=false;
				if (!!window.ActiveXObject || 'ActiveXObject' in window) {
					isIE=true;
				} else {
					isIE=false;
				}
				files.forEach(url => {
						if (isIE) { // IE
								window.open(url, '_blank')
							} else {
							let a = document.createElement('a') // 创建a标签
							let e = document.createEvent('MouseEvents') // 创建鼠标事件对象
							e.initEvent('click', false, false) // 初始化事件对象
							a.href = process.env.API_ROOT+url // 设置下载地址
							a.download = '' // 设置下载文件名
							a.dispatchEvent(e)
						}
				})
			}else {
				this.$message.warning('请先预览发布！')
			}
		}
	}
}	
</script>

<style scoped lang="scss">
	#pptlist{ overflow:hidden;
		.header .el-form-item{ margin-bottom:0; }
	}
</style>