<template>
	<div id="editreport">
		<div id="leftfroala">
			<froala id="froala-editor" ref='froalaEditor' :tag="'textarea'" :config="froalaConfig" v-model="aeForm.content"></froala>
		</div>
		<div id="rightitems">
			<div style="text-align:right; padding:0px 0 15px 0; box-sizing:border-box;">
				<div v-show="lastsavetime" style="color:#666; margin-bottom:15px;">最近保存时间：{{lastsavetime}}</div>
				<el-button type="primary" size="medium" plain @click.native="clickreportadd('yl')">预览</el-button>
				<el-button type="primary" size="medium" plain @click.native="clickreportadd('cg')">存草稿</el-button>
				<el-button type="primary" size="medium" @click.native="clickreportadd('fb')" :loading="isPublishloading">发布</el-button>
			</div>
			<div style="margin:0px 0 0 20px; padding:10px 20px; box-sizing:border-box; background:#fff; border:1px solid #3464E0;">
				<div id="tabs">
					<p @click="tabsactive='基础信息'" :class="{active:tabsactive=='基础信息'?true:false}">基础信息</p>
					<p @click="tabsactive='图表插入'" :class="{active:tabsactive=='图表插入'?true:false}">图表插入</p>
				</div>
				<div v-if="tabsactive=='基础信息'" style="height:calc(100vh - 280px); overflow-y:auto;">
					<el-form :model="aeForm" :rules="aerules" ref="aeForm" label-position="right" label-width="90px" class="demo-aeForm" id="login-container" @submit.native.prevent>
						<el-form-item prop="add_type" label="新增方式">
							<el-select v-model="aeForm.add_type" @change="userclassidreportdetail" placeholder="请选择" size="medium" disabled style="width:270px;">
								<el-option label="新增报告" :value="1"></el-option>
								<el-option label="继承报告" :value="2"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item prop="classifynameArr" label="分类">
							<el-cascader @change="userclassidreportdetail" :options="optionsArr" v-model="aeForm.classifynameArr" placeholder="类型筛选" size="medium" style="width:270px;"></el-cascader>
						</el-form-item>
						<el-form-item prop="title" label="标题">
							<el-input type="textarea" :rows="2" placeholder="请输入" v-model="aeForm.title" size="medium"></el-input>
						</el-form-item>
						<el-form-item label="摘要">
							<el-input type="textarea" :rows="2" placeholder="请输入" v-model="aeForm.abstract" size="medium"></el-input>
						</el-form-item>
						<el-form-item label="作者">
							<el-select v-model="aeForm.author" multiple placeholder="请选择" size="medium" style="width:270px;">
							    <el-option v-for="(item,i) in authorlist" :key="i" :label="item.ReportAuthor" :value="item.ReportAuthor"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="频度">
						    <el-select v-model="aeForm.frequency" placeholder="请选择" size="medium" style="width:270px;">
								<el-option label="年度" value="年度"></el-option>
								<el-option label="半年度" value="半年度"></el-option>
								<el-option label="季度" value="季度"></el-option>
								<el-option label="月度" value="月度"></el-option>
								<el-option label="双周度" value="双周度"></el-option>
								<el-option label="周度" value="周度"></el-option>
								<el-option label="日度" value="日度"></el-option>
								<el-option label="不定时" value="不定时"></el-option>
						    </el-select>
						</el-form-item>
						<el-form-item label="创建时间">
							<el-date-picker v-model="aeForm.create_time" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" size="medium" :clearable="false" style="width:270px;"></el-date-picker>
						</el-form-item>
					</el-form>
				</div>
				<div v-if="tabsactive=='图表插入'">
					<el-input placeholder="标题/子标题/作者" v-model="key_word" size="medium" prefix-icon="el-icon-search" @input="getreportlist(key_word)">
					</el-input>
					<div style="height:calc(100vh - 320px); overflow-x:hidden; overflow-y:auto;">
						<div v-for="(item,index) in newreportlist" :key="index" class="liststy">
							<p class="color_primary">{{item.element__title}}</p>
							<img :src="item.image" :id="'listnode'+index" @click="insertHtml(item)" />
						</div>
					</div>
				</div>
				<!-- <div v-for="(item,index) in reportlist" :key="index" :id="'listnode'+index" @click="insethtml(index)" style="					width:100%; margin:20px 0; padding:20px; box-sizing:border-box; border:1px solid #eaeaea; border-radius:10px; position:relative; overflow:hidden;">
					<p class="color_primary" style="text-align:center; font-size:16px; margin-bottom:10px;">{{item.element__title}}</p>
					<img :src="item.image" style="width:100%; height:auto;" />
				</div> -->
			</div>
		</div>
	</div>
</template>

<script>
import { autosave,reportdetail,reportedit,classifylist,reportpublish,reportauthor,classifyIdDetail } from 'api/api.js';
import VueFroala  from 'vue-froala-wysiwyg';
import urlSlug from 'url-slug';
import http from '@/api/http.js';
import mixinMsg from './mixins/messagePush'

export default {
	mixins:[mixinMsg],
	data(){
		var that = this;
		return{
			report_id:this.$route.query.id,
			tabsactive:'基础信息',
			optionsArr:[],
			key_word:'',
			originreportlist:[],
			newreportlist:[],
			authorlist:[],
			aeForm:{
				add_type:1,
				classify_name:1,
				classifynameArr:[],
				title:'',
				abstract:'',
				author:['FICC团队'],
				frequency:'日度',
				create_time:http.dateFormatter(new Date(),false),
				content:''
			},
			aerules:{
				add_type:[{
					required:true,
					message:'',
					trigger:'blur'
				}],
				classifynameArr:[{
					required:true,
					message:'',
					trigger:'blur'
				}],
				title:[{
					required:true,
					message:'请输入',
					trigger:'blur'
				}],
			},
			editor:null,
			lastEditRange:null,
			froalaConfig:{  //More -> https://www.froala.com/wysiwyg-editor/docs/options
				// toolbarButtons: ['undo', 'redo', 'clearFormatting', '|', 'bold', 'italic', 'underline','strikeThrough','|', 'fontFamily', 'fontSize', 'color', '|','paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', '-', 'insertLink', 'insertImage', 'insertVideo', 'embedly', 'insertFile', 'insertTable', '|', 'emoticons', 'specialCharacters', 'insertHR', 'selectAll', '|', 'print', 'spellChecker', 'help', '|', 'fullscreen'],//['fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', '|', 'fontFamily', 'fontSize', 'color', 'inlineStyle', 'paragraphStyle', '|', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', '-', 'insertLink', 'insertImage', 'insertVideo', 'embedly', 'insertFile', 'insertTable', '|', 'emoticons', 'specialCharacters', 'insertHR', 'selectAll', 'clearFormatting', '|', 'print', 'spellChecker', 'help', 'html', '|', 'undo', 'redo'],//显示可操作项
				toolbarButtons: ['insertImage', 'insertVideo', 'embedly', 'insertFile','textColor','bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize','color', 'inlineClass', 'inlineStyle', 'paragraphStyle', 'lineHeight','paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', 'insertTable', 'emoticons', 'fontAwesome', 'specialCharacters', 'insertHR', 'selectAll', 'clearFormatting', 'html', 'undo', 'redo'],
				// attribution: false,
			//     quickInsertTags: [],
			    imageDefaultWidth:false,
				// imageResizeWithPercent:true,
			//     imageMaxSize: 10 * 1024 * 1024,
			//     imageAllowedTypes: ['jpeg', 'jpg', 'png', 'gif'],
				imageInsertButtons:['imageUpload','imageByURL'],
				height:screen.height-390,
				fontSizeDefaultSelection:'16',
				fontSize:['12','14','16','18','20','24','28','32','36','40'],
				theme:"dark",//主题
				placeholderText:'请输入内容',
				language:"zh_cn",//国际化
				imageUploadURL:process.env.API_ROOT+'/report/uploadImg',//上传url
				imagePaste: true,
				imagePasteProcess: true,
				imageResize: true,
				videoUploadURL:process.env.API_ROOT+'/report/uploadImg',//上传url
				fileUploadURL:process.env.API_ROOT+'/report/uploadImg',//上传url 更多上传介绍 请访问https://www.froala.com/wysiwyg-editor/docs/options
				toolbarSticky:false,//操作栏是否自动吸顶
				imageEditButtons:[ 'imageLink',"imageAlign","imageInfo","imageRemove",],
				quickInsertButtons:['image','table','ul','ol','hr'], //快速插入项
				toolbarVisibleWithoutSelection:true,//是否开启 不选中模式
				saveInterval:0,
				/* saveParam: 'Content',
				saveURL: process.env.API_ROOT+'/report/saveReportContent',
				saveMethod: 'POST',
				saveParams: {}, */
				events:{
					initialized:function(){  //this.editor 定义在vue data 中
						that.editor = this;
					},
					keyup:function(e,editor){  //添加事件，在每次按键按下时，都记录一下最后停留位置
						that.lastEditRange = getSelection().getRangeAt(0) || 0;
					},
					click:function(e,editor){  //添加事件，在每次鼠标点击时，都记录一下最后停留位置
						that.lastEditRange = getSelection().getRangeAt(0) || 0;
					},
					//内容改变事件
					contentChanged: function() {
						console.log('cont-change');
						that.ischange = true;
						that.lastEditRange = getSelection().getRangeAt(0) || 0;
					},
					/* 'save.before': function () {
						that.froalaConfig.saveParams.ReportId=that.report_id;
						
						// $('iframe').each(function(k,i){
						// 	var h = '',elementID;
						// 	try {
						// 		h = $(i)[0].contentWindow.location.href;
						// 		console.log("start get location_href")
						// 		console.log(h)
						// 		console.log("end get location_href")
						// 	} catch (err) {
						// 		h = $(i).attr('src');
						// 		console.log("start get location_href fail ");
						// 		console.log(h);
						// 		console.log("end get location_href fail ");
						// 	}
						// 	elementID = h.split('/')[4];
						// 	if($(i).attr('src') !== h && h!==''){
						// 		$(i).unbind('load');
						// 		$(i).on('load', function(e){
						// 			console.log(1);
						// 		});
						// 		let newSrc=$(i)[0].contentWindow.location.href;
						// 		console.log("start newSrc ");
						// 		console.log(newSrc);
						// 		console.log("end newSrc ");
						// 		$(i).attr('src', newSrc);
						// 	}
						// });
						
					},
					'save.after': function (res) {
						res=JSON.parse(res);
						if( res.Ret==200 ){
							that.report_id=res.Data.ReportId;
							that.lastsavetime=http.dateFormatter(new Date(),true);
						}
					} */
				},
				charCounterCount:false,
			},
			reportloadding:false,
			lastsavetime:'',
			timer:null,
			ischange:false,
			isPublishloading:false,
			ThsMsgIsSend:'',//是否推送过客群
		}
	},
	mounted(){
		this.getreportdetail();
		this.getclassifylist();
		this.getreportlist('');
		this.getreportauthor();
		// $("#rightitems").css({minHeight:screen.height});
		this.timer = setInterval(() => {
			this.autoSave();
		},6000)
	},
	updated(){
	  $('#leftfroala').find('p').css({fontSize:"16px"});
	},
	destroyed() {
		if(this.timer) {
			clearInterval(this.timer)
		}
	},
	methods:{
		// 每十秒自动保存
		autoSave() {
			console.log(this.ischange);
			// if(this.ischange) {
				$('iframe').each(function(k,i){
					var h = '',elementID;
					try {
						h = $(i)[0].contentWindow.location.href;
						// console.log("start get location_href")
						console.log(h)
						// console.log("end get location_href")
					} catch (err) {
						h = $(i).attr('src');
						// console.log("start get location_href fail ");
						console.log(h);
						// console.log("end get location_href fail ");
					}
					elementID = h.split('/')[4];
					if($(i).attr('src') !== h && elementID){
						$(i).unbind('load');
						$(i).on('load', function(e){
							console.log(1);
						});
						let newSrc=$(i)[0].contentWindow.location.href;
						// console.log("start newSrc ");
						// console.log(newSrc);
						// console.log("end newSrc ");
						$(i).attr('src', newSrc);
					}
				});
				autosave({
					ReportId:Number(this.$route.query.id),
					Content:$('.fr-element').html(),
					NoChange:this.ischange?0:1
				}).then(res => {
					if(res.Ret === 200) {
						this.report_id=res.Data.ReportId;
						this.lastsavetime=http.dateFormatter(new Date(),true);
					}
				})
				this.ischange = false;
			// }
		},
		userclassidreportdetail(){
			if( this.aeForm.add_type==1 ){
				if( this.aeForm.classifynameArr.length==2 ){
					this.aeForm.title=JSON.parse(this.aeForm.classifynameArr[1]).l;
				}
				return false;
			}
			if( this.aeForm.classifynameArr.length==0 ){
				return false;
			}
			console.log(this.aeForm.classifynameArr);
			let params={ClassifyIdFirst:JSON.parse(this.aeForm.classifynameArr[0]).v};
			if( this.aeForm.classifynameArr.length==2 ){
				params.ClassifyIdSecond=JSON.parse(this.aeForm.classifynameArr[1]).v;
			}else{
				params.ClassifyIdSecond=0;
			}
			classifyIdDetail(params).then((res) => {
				if( res.Ret==200 ){
					if( res.Data==null ){
						this.$message.error('此分类暂无报告');
						return false;
					}
					this.aeForm={
						add_type:2,
						classify_name:1,
						classifynameArr:(res.Data.ClassifyIdSecond&&res.Data.ClassifyNameSecond)?[JSON.stringify({l:res.Data.ClassifyNameFirst,v:res.Data.ClassifyIdFirst}),JSON.stringify({l:res.Data.ClassifyNameSecond,v:res.Data.ClassifyIdSecond})]:[JSON.stringify({l:res.Data.ClassifyNameFirst,v:res.Data.ClassifyIdFirst})],
						title:res.Data.Title,
						abstract:res.Data.Abstract,
						author:res.Data.Author?res.Data.Author.split(','):'',
						frequency:res.Data.Frequency,
						create_time:res.Data.CreateTime,
						content:res.Data.Content
					};
				}
			});
		},
		getreportauthor(){
			reportauthor({}).then((res) => {
				if( res.Ret==200 ){
					this.authorlist=res.Data.List || [];
				}
			});
		},
		getreportdetail(){
			reportdetail({ReportId:parseInt(this.report_id)}).then((res) => {
				if( res.Ret==200 ){
					let data=res.Data;
					this.aeForm={
						add_type:parseInt(data.AddType),
						classify_name:1,
						classifynameArr:(data.ClassifyIdSecond&&data.ClassifyNameSecond)?[JSON.stringify({l:data.ClassifyNameFirst,v:parseInt(data.ClassifyIdFirst)}),JSON.stringify({l:data.ClassifyNameSecond,v:parseInt(data.ClassifyIdSecond)})]:[JSON.stringify({l:data.ClassifyNameFirst,v:parseInt(data.ClassifyIdFirst)})],
						title:data.Title,
						abstract:data.Abstract,
						author:data.Author?data.Author.split(','):'',
						frequency:data.Frequency,
						create_time:data.CreateTime,
						content:data.Content
					};
					this.ThsMsgIsSend=data.ThsMsgIsSend
				}
			});
		},
		clickreportadd(tp){
			console.log(this.aeForm.classifynameArr);
			if( (!this.aeForm.classifynameArr)||this.aeForm.classifynameArr.length==0 ){
				this.$message.error('请选择分类');
				return false;
			}
			if( !this.aeForm.title ){
				this.$message.error('请输入标题');
				return false;
			}
			console.log("content start");
			$('iframe').each(function(k,i){
				var h = '',elementID;
				try {
					h = $(i)[0].contentWindow.location.href;
					// console.log("start get location_href")
					console.log(h)
					// console.log("end get location_href")
				} catch (err) {
					h = $(i).attr('src');
					// console.log("start get location_href fail ");
					console.log(h);
					// console.log("end get location_href fail ");
				}
				elementID = h.split('/')[4];
				if($(i).attr('src') !== h && elementID){
					$(i).unbind('load');
					$(i).on('load', function(e){
						console.log(1);
					});
					let newSrc=$(i)[0].contentWindow.location.href;
					// console.log("start newSrc ");
					// console.log(newSrc);
					// console.log("end newSrc ");
					$(i).attr('src', newSrc);
				}
			});
			console.log("content end");

			let params={
				ReportId:parseInt(this.report_id),
				AddType:this.aeForm.add_type,
				ClassifyIdFirst:JSON.parse(this.aeForm.classifynameArr[0]).v,
				ClassifyNameFirst:JSON.parse(this.aeForm.classifynameArr[0]).l,
				Title:this.aeForm.title,
				Abstract:this.aeForm.abstract,
				Author:this.aeForm.author.length>0?this.aeForm.author.join(','):'',
				Frequency:this.aeForm.frequency,
			// content:this.aeForm.content,create_time:this.aeForm.create_time
				Content:$('.fr-element').html(),
				CreateTime:this.aeForm.create_time
			};
			if( this.aeForm.classifynameArr.length==2 ){
				params.ClassifyIdSecond=JSON.parse(this.aeForm.classifynameArr[1]).v;
				params.ClassifyNameSecond=JSON.parse(this.aeForm.classifynameArr[1]).l;
			}
			params.State=1;
			if( tp=='yl' ){
				sessionStorage.setItem('reportdtl',JSON.stringify(params));
				let {href} = this.$router.resolve({name:'预览报告'});
				window.open(href,'_blank');
				return false;
			}
			if( tp == 'fb') {
				this.isPublishloading = true;
				//判断是否要推送客群（含电话会的不推送）
				let hasTel=0
				if(this.aeForm.classifynameArr.length == 2){
					this.optionsArr.forEach(item=>{
						item.children&&item.children.forEach(childItem=>{
							if(JSON.parse(item.value).v==params.ClassifyIdSecond){
								hasTel=childItem.HasTeleconference
							}
						})
					})
				}else{
					this.optionsArr.forEach(item=>{
						if(JSON.parse(item.value).v==params.ClassifyIdFirst){
							hasTel=item.HasTeleconference
						}
					})
				}
				console.log(hasTel);
				if(hasTel==1||this.ThsMsgIsSend==1){
					this.isMessagePost = false; 
					this.reporteditMsg(params,tp)
				}else{
					this.$confirm('发布后，是否推送客户群？', '发布提示', {
						    confirmButtonText: '推送',
						    cancelButtonText: '不推送',
						    type: 'warning',
						    distinguishCancelAndClose:true,
						    beforeClose:(action, instance,done)=>{
						        if(action==='close') {
						            //右上角
									this.isPublishloading = false;
						        } else if(action==='cancel') {
						            //cancelButton
									this.isMessagePost = false; 
									this.reporteditMsg(params,tp)
						        }else {
						           //confirmButton
								   	this.isMessagePost = true; 
									this.reporteditMsg(params,tp)
						        }
						        done()
						    }
					})
				}
					
			}else {
				this.reporteditMsg(params,tp)
			}
			// reportedit(params).then((res) => {
			// 	if( res.Ret==200 ){
			// 		this.$message.success( res.Msg );
			// 		if( tp=='yl' ){	
			// 			// this.$router.push({name:'预览报告',query:{id:res.report_id}});
			// 			let {href} = this.$router.resolve({name:'预览报告',query:{id:res.Data.ReportId}});
			// 			window.open(href,'_blank');
			// 		}else if( tp=='fb' ){
			// 			this.publishreport(res.Data.ReportId);
			// 		}else{
			// 			// this.$router.push({path:'/reportlist'});
			// 		}
			// 	}
			// });
		},
		publishreport(id){  //发布报告
			reportpublish({ReportIds:String(id)}).then((res) => {
				if( res.Ret==200 ){
					this.isPublishloading = false;
					this.$router.push({path:'/reportlist'});
				}
			});
		},
		insertHtml(item){
		  //设置编辑器获取焦点
		  this.editor.events.focus();
		  // 获取选定对象
		  const selection = getSelection();
		  // 判断是否有最后光标对象存在
		  if (this.lastEditRange) {
		    // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
		    selection.removeAllRanges()
		    selection.addRange(this.lastEditRange)
		  }
		  //插入内容
		  // this.editor.html.insert( `<img src=${emoji} >` );
		  this.$nextTick(function(){
		  	// this.editor.html.insert( `<p><iframe src="http://vmp.hzinsights.com/element/${item.element_id}/${urlSlug(item.element__title_en, { separator: '_' })}/|||||/" key="${item.element_id}" width="100%" display="initial" position="relative" style="border-width:0px;height:400px;"></iframe></p>` );
			let url=`https://vmp.hzinsights.com/element/${item.element_id}/${urlSlug(item.element__title_en, { separator: '_' })}/|||||/`;
			this.editor.html.insert( "<p style='text-align:left; margin-top:10px;'><iframe src='"+url+"' key='"+item.element_id+"' width='100%' height='350' display='initial' position='relative' border='none' style='border-width:0px; min-height:350px;'></iframe></p>" );
			// this.editor.html.insert( "<iframe src='"+url+"' key='"+item.element_id+"' width='100%' height='300' display='initial' position='relative' border='none' style='border-width:0px; height:400px;'></iframe>" );
		  });
		  this.lastEditRange = selection.getRangeAt(0)
		},
		getreportlist(word){
			let that=this;
			if( that.reportloadding ){
				return false;
			}
			that.reportloadding=true;
			that.newreportlist=[];
			$.ajax({
			    url:'https://vmp.hzinsights.com/api/v1/flow/images',
			    type:'get',
				data:{search_keywords:word,size:100},
			    dataType:'json',
			    xhrFields:{withCredentials:false},
			    success:function(res){
					that.newreportlist=res.results || [];
					that.reportloadding=false;
			    },error:function(error){}
			});
		},
		getclassifylist(){  //获取分类列表
			let params={CurrentIndex:0,PageSize:1000,KeyWord:'',HideDayWeek:1,/*不显示晨报/周报*/};
			classifylist(params).then((res) => {
				if( res.Ret==200&&Array.isArray(res.Data.List) ){
					this.optionsArr = [];
					res.Data.List.forEach((item,index)=>{
						let newitem={label:item.ClassifyName,value:JSON.stringify({l:item.ClassifyName,v:parseInt(item.Id)}),HasTeleconference:item.HasTeleconference};
						if(item.Child && item.Child.length>0 ){
							let childnode=[];
							item.Child.forEach((itemchild,i)=>{
								childnode.push({label:itemchild.ClassifyName,value:JSON.stringify({l:itemchild.ClassifyName,v:parseInt(itemchild.Id)}),HasTeleconference:itemchild.HasTeleconference });
							});
							newitem.children=childnode;
						}else{
							newitem.children=undefined;
						}
						this.optionsArr.push(newitem);
					});
					console.log( this.optionsArr );
				}
			});
		},
		
	},
	components:{}
}
</script>

<style scoped lang="scss">
	#editreport{ display:flex; overflow:hidden;
		#leftfroala{ flex:1; }
		#rightitems{ width:500px; flex:500px 0 0; overflow:hidden; 
			#tabs{ padding:0px 40px; box-sizing:border-box; margin-bottom:15px; overflow:hidden;
				>p{ display:inline-block; float:left; width:50%; font-size:18px; cursor:pointer; color:#1F2E4D; padding:10px 0; text-align:center; }
				>p.active{ border-bottom:2px solid #3464E0; color:#3464E0; }
			}
			.liststy{ width:100%; margin:20px 0; padding:20px; box-sizing:border-box; border:1px solid #eaeaea; border-radius:10px; position:relative; overflow:hidden;
				>p{ text-align:center; font-size:16px; margin-bottom:10px; }
				>img{ width:100%; height:auto; }
			}
		}
	}
</style>