<template>
	<div id="editreport">
		<div 
			id="leftfroala"
			v-loading="importChartNum>0" 
			element-loading-text="图表批量插入中..."
			element-loading-spinner="el-icon-loading"
			element-loading-background="rgba(0, 0, 0, 0.8)"
		>
			<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="refreshReport"
				>
					一键刷新
				</el-button>
				<el-button
					type="primary"
					size="medium"
					plain
					@click.native="handlePreviewReport"
					>预览</el-button
				>
				<el-button
					type="primary"
					size="medium"
					plain
					@click.native="autoSave('cg')"
					>存草稿</el-button
				>
				<el-button
					type="primary"
					size="medium"
					@click.native="handlePublishReport"
					: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>
					<p
						@click="tabsactive = 'MyETA批量插入'"
						:class="{ active: tabsactive == 'MyETA批量插入' ? true : false }"
					>
						MyETA插入
					</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="type" label="品种">
							<el-input v-model="aeForm.type" size="medium" disabled></el-input>
						</el-form-item>
						<el-form-item prop="title" label="标题">
							<el-input v-model="aeForm.title" size="medium" placeholder="请输入标题"></el-input>
						</el-form-item>
						<el-form-item prop="addType" label="新增方式">
							<el-select
								v-model="aeForm.addType"
								placeholder="请选择"
								@change="handleAddTypeChange"
								size="medium"
								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="ticket" label="显示指标" v-if="$route.query.type=='day'">
							<el-select
								v-model="aeForm.ticket"
								placeholder="请选择"
								multiple
								collapse-tags
								size="medium"
								style="width: 270px"
							>
								<el-option 
									v-for="item in ticketList" 
									:key="item.BaseColumnTicker"
									:label="item.BaseColumnName" 
									:value="item.BaseColumnTicker"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item prop="author" label="创建人">
							<el-input placeholder="请输入" v-model="aeForm.author"></el-input>
						</el-form-item>
						<el-form-item label="创建时间">
							<el-date-picker
								v-model="aeForm.createTime"
								type="date"
								value-format="yyyy-MM-dd"
								placeholder="选择日期"
								size="medium"
								:clearable="false"
								style="width: 270px"
							></el-date-picker>
						</el-form-item>
						<el-form-item label="录音" v-if="$route.query.type=='week'">
							<el-input v-model="aeForm.audioUrl" readonly style="width:65%" placeholder="请上传录音文件"></el-input>
							<el-upload
								style="display: inline-block;margin-left:10px"
								action=""
								accept=".mp3,.m4a"
								:http-request="handleUpload"
								:before-upload="handelBeforeUploadAudio"
								:show-file-list="false"
								:disabled="startUploadAudio"
							>
								<el-button type="primary" :loading="startUploadAudio">上传录音</el-button>
							</el-upload>
							
							<p style="color:#999;font-size:12px">*注：要求音频格式为mp3、m4a，音频时长不超过15分钟</p>
						</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="() => {search_page=1;$refs.chartListRef.scrollTop = 0;getChartList(key_word)}"
					>
					</el-input>
					<el-radio-group v-model="chart_source" @change="() => {search_page=1;$refs.chartListRef.scrollTop = 0;getChartList('')}" style="margin-top: 10px;">
						<el-radio :label="1">ETA图库</el-radio>
						<el-radio :label="2">商品价格曲线</el-radio> 
						<el-radio :label="3">相关性图表</el-radio>
						<el-radio :label="6">拟合方程曲线</el-radio>
						<el-radio :label="7">统计特征</el-radio>
					</el-radio-group>
					<div style="margin: 10px 0">
						<el-checkbox v-model="isShowMe" @change="() => {search_page=1;$refs.chartListRef.scrollTop = 0;getChartList(key_word)}">只看我的</el-checkbox>
					</div>
					<div
						ref="chartListRef"
						style="
							height: calc(100vh - 320px);
							overflow-x: hidden;
							overflow-y: auto;
						"
						v-infinite-scroll="loadReportHandle"
						:infinite-scroll-immediate="false"
					>
						<div
							v-for="(item, index) in chartlist"
							:key="item.ChartInfoId"
							class="liststy"
							:style="item.Disabled && 'cursor: not-allowed;'"
						>
							<p class="color_primary">{{ item.ChartName }}</p>
							<img
								:src="item.ChartImage"
								:id="'listnode' + index"
								@click="insertHtml(item)"
							/>
						</div>
					</div>
				</div>
				<div v-if="tabsactive == '沙盘插入'">
					<el-input
						placeholder="沙盘名称/品种"
						v-model="sandTabelQuery.Keyword"
						size="medium"
						prefix-icon="el-icon-search"
					>
					</el-input>
					<div
						id="sandTable-container"
						ref="sandTable"
						style="
							height: calc(100vh - 320px);
							overflow-x: hidden;
							overflow-y: auto;
						"
						@scroll="sandTableHandleScroll"
					>
						<div
							v-for="(item, index) in sandTableList"
							:key="item.SandboxId"
							class="liststy"
						>
							<p class="color_primary">{{ item.Name }}</p>
							<img
								:src="item.PicUrl"
								:id="'sandTable' + index"
								@click="insertHtml(item,'image')"
							/>
							<p class="source-identification">来源：弘则研究</p>
						</div>
						<div v-loading = "sandTableLoading" class="loaded-text">{{loadedText}}</div>
					</div>
				</div>
				<div v-if="tabsactive == 'MyETA批量插入'">
					<importMyChart @handleImportMyChart="handleImportMyChart"/>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import {
	autosave,
	chapterDetail,
	reportedit,
	dayTicketList,
	dataBaseInterface,
	saveChapterReport,
	getChapterReportBefore,
	getChapterReportIsLast,
	publishChapterReport,
	sandInterface,
	getOSSSign
} from 'api/api.js';
import MD5 from 'js-md5'
import futuresInterface from '@/api/modules/futuresBaseApi';
import chartRelevanceApi from '@/api/modules/chartRelevanceApi';
import { fittingEquationInterface,statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';
import VueFroala from 'vue-froala-wysiwyg';
import urlSlug from 'url-slug';
import http from '@/api/http.js';
import mixinMsg from './mixins/messagePush'
import moment from 'moment';
import importMyChart from './components/importMyChart.vue'
let ALOSSINS=null //阿里云上传实例
export default {
	beforeRouteEnter(to,from,next){
		// 设置面包屑
		to.matched[1].meta.pathName=`编辑${to.query.type=='day'?'晨报':'周报'}`
		to.matched[1].name=to.query.typename
		next()
	},
	mixins:[mixinMsg],
	data() {
		var that = this;
		return {
			//批量导入图表
			importChartNum:0,//批量导入图表的数量 如果大于0则说明在加载
			
			report_id: this.$route.query.id,
			tabsactive: '基础信息',
			ticketList:[],//指标列表
			key_word: '',
			// 沙盘插入 ----------start
			sandTabelQuery:{
				PageSize: 13,
				CurrentIndex: 1,
				Keyword: '',
			}, // 沙盘图查询参数
			sandTableLoading:false,
			sandTableTotal:0,//沙盘总共条数
			sandTableList:[],
			isRequesting:false,
			loadedText:'', // 全部加载完的文字提示
			// 沙盘插入 ------------- end
			chartlist: [],
			aeForm: {
				type:'',//品种
				title:'',//标题
				addType:2,//新增方式
				ticket:[],//指标
				author:localStorage.getItem('userName')||'',
				createTime:http.dateFormatter(new Date(), false),
				content: '',
				audioUrl:'',
				audioDuration:0,
				audioSize:0,
			},
			aerules: {
				title: [
					{
						required: true,
						message: '请输入',
						trigger: 'blur',
					},
				],
				addType:[{required: true,message:'请选择',trigger:'change'}]
			},
			editor: null,
			lastEditRange: null,
			froalaConfig: {
				toolbarButtons: [
					'insertImage',
					'insertVideo',
					'insertLink',
					'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',
				],
				imageDefaultWidth: false,
				imageInsertButtons: ['imageUpload', 'imageByURL'],
				height: 800,
				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) {
						//添加事件，在每次鼠标点击时，都记录一下最后停留位置
						if(getSelection().type==='None') return 
						that.lastEditRange = getSelection().getRangeAt(0) || 0;
					},
					//内容改变事件
					contentChanged: function () {
						console.log('cont-change');
						that.ischange = true;
						if(getSelection().type!=='None') {
							that.lastEditRange = getSelection().getRangeAt(0) || 0;
						} 
					},
					//粘贴图片上传事件
					'image.beforePasteUpload':function(img){
						//console.log('image.beforePasteUpload',img)
						//暂停自动保存
						that.autoSaveFlag = false
						
					},
					//点击toolbar上传图片事件
					'image.beforeUpload':function(imgs){
						//console.log('image.beforeUpload',imgs)
						//暂停自动保存
						that.autoSaveFlag = false
						
					},
					'image.inserted':function($img,response){
						//console.log('img-inserted',$img)
						//开启自动保存
						that.autoSaveFlag = true
					},
					//如果上传图片出错,重置autoSaveFlag
					'image.error':function(error,response){
						that.autoSaveFlag = true
					}
				},
				charCounterCount: false,
			},
			reportloadding: false,
			lastsavetime: '',
			timer: null,
			ischange: false,
			isPublishloading: false,

			chapterTypeId:0,//章节类型id 

			chart_source: 1,
			search_page: 1,
			search_page_sizes: 20,
			search_have_more: true,


			startUploadAudio:false,

			autoSaveFlag:true,//是否开启自动保存
		};
	},
	mounted() {
		this.getreportdetail();
		this.getChartList('');
		// // $("#rightitems").css({minHeight:screen.height});
		this.getSandTable()
		this.timer = setInterval(() => {
			this.autoSave();
		}, 6000);
	},
	updated() {
		$('#leftfroala').find('p').css({ fontSize: '16px' });
	},
	destroyed() {
		if (this.timer) {
			clearInterval(this.timer);
		}
	},
	watch: {
		'sandTabelQuery.Keyword'(newval,oldval){
			this.$refs.sandTable.scrollTop=0
			this.sandTabelQuery.CurrentIndex = 1
			this.getSandTable()
		}
	},
	methods: {
		handelBeforeUploadAudio(e){
			console.log(e);
			if(e.name.indexOf('.mp3')==-1 && e.name.indexOf('.wav')==-1 && e.name.indexOf('.wma')==-1&&e.name.indexOf('.m4a')==-1){
                this.$message.warning('上传失败，上传音频格式不正确')
                return false
            }
		},
		async handleUpload(e){
			console.log(e.file.size);
			const duration=await this.handleGetDuration(e.file)
            if(duration>60*15){
                this.$message.warning('音频时长不得超过15分钟')
                return 
            }
			this.aeForm.audioDuration=duration
			this.aeForm.audioSize=e.file.size/1024/1024 //单位MB
			const res=await getOSSSign()
            if(res.Ret===200){
                let accessKeyId=res.Data.AccessKeyId
                let accessKeySecret=res.Data.AccessKeySecret
                let stsToken=res.Data.SecurityToken
                this.handleUploadToOSS(e.file,accessKeyId,accessKeySecret,stsToken)
            }

		},
		//上传到阿里云
        async handleUploadToOSS(file,accessKeyId,accessKeySecret,stsToken){
            this.startUploadAudio=true
            ALOSSINS=new OSS({
                // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                region: "oss-cn-shanghai",
                // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
                accessKeyId: accessKeyId,
                accessKeySecret: accessKeySecret,
                // 从STS服务获取的安全令牌（SecurityToken）。
                stsToken: stsToken,
                // 填写Bucket名称，例如examplebucket。
                bucket: "hzchart",
                endpoint:'hzstatic.hzinsights.com',
                cname:true,
                timeout:600000000000
            });
            // 生成文件名
            const t=new Date().getTime().toString()
            const temName=`static/yb/audio/${process.env.NODE_ENV}/${MD5(t)}.${file.type.split('/')[1]}`
            console.log(temName);
			
            try {
                const res=await ALOSSINS.put(temName,file)
                console.log('上传结果',res);
                if(res.res.status===200){
                    this.aeForm.audioUrl='https://hzstatic.hzinsights.com/'+res.name
                    this.startUploadAudio=false
                }
            } catch (error) {
                console.log('上传到阿里云失败',error);
                if(error.name!=="cancel"){//不是取消上传的则给错误提示
                    this.$message.warning('上传失败，请刷新重试')
                }
                this.startUploadAudio=false
            }
        },


		//获取音频时长的promise
        handleGetDuration(file){
            return new Promise((resolve,reject)=>{
                const fileUrl=URL.createObjectURL(file)
                const audioEl=new Audio(fileUrl)
                audioEl.addEventListener('loadedmetadata',(e)=>{
                    console.log('e.path',e.path)
                    console.log('e.composedPath',e.composedPath())
                    console.log('获取视频时长',e.composedPath()[0].duration);
                    console.log(audioEl.duration);
                    const t=e.composedPath()[0].duration
                    resolve(t)
                })
            })
        },

		// 每十秒自动保存
		autoSave(e) {
			// if(!this.aeForm.title&&e=='cg'){
			// 	this.$message.warning('请填写标题')
			// 	return
			// }
			// if(!e){//自动保存情况
			// 	if(!this.ischange||!this.aeForm.title) return
			// }
			// if(e!='cg'||!this.ischange||!this.aeForm.title) return

			//去除校验title等必填项
			if(!e&&!this.ischange) return

			if(!this.autoSaveFlag){
				e==='cg'&&this.$message.error('有图片未上传完成,请稍等')
				return 
			}
			
				let arr=[]
				this.ticketList.forEach(item => {
					let obj={
						ticker:'',
						sort:1,
						lable:''
					}
					if(this.aeForm.ticket.includes(item.BaseColumnTicker)){
						obj.ticker=item.BaseColumnTicker
						obj.sort=arr.length+1
						obj.lable=item.BaseColumnName
						arr.push(obj)
					}
				});
				//如果富文本中有未上传完成的图片,去除这个dom
				$('.fr-element').find('img.fr-uploading').length&&$('.fr-element').find('img.fr-uploading').remove()

				saveChapterReport({
					ReportChapterId: Number(this.$route.query.id),
					Title:this.aeForm.title,
					AddType:this.aeForm.addType,
					Author:this.aeForm.author,
					CreateTime:this.aeForm.createTime,
					TickerList:arr,
					Content: $('.fr-element').html(),
					VideoUrl:this.aeForm.audioUrl,
					VideoName:`${this.aeForm.title}(${moment().format('MMDD')})`,
					VideoPlaySeconds:Number(this.aeForm.audioDuration).toFixed(2).toString(),
					VideoSize:Number(this.aeForm.audioSize).toFixed(2).toString()
				}).then((res) => {
					if (res.Ret === 200) {
						// this.report_id = res.Data.ReportId;
						this.lastsavetime = http.dateFormatter(new Date(), true);
						if(e=='cg'){
							this.$message.success('保存成功')
						}
					}
					this.ischange = false;
				});
				
			
		},
		//章节详情
		getreportdetail() {
			chapterDetail({ ReportChapterId: parseInt(this.report_id) }).then((res) => {
				if (res.Ret == 200) {
					let data = res.Data;
					this.aeForm.type=data.TypeName
					this.aeForm.title=data.Title
					this.aeForm.addType=data.AddType
					this.aeForm.author=data.Author||localStorage.getItem('userName')
					this.aeForm.createTime=moment(data.CreateTime).format('YYYY-MM-DD')
					this.aeForm.content=data.Content
					if(data.VideoKind==1){
						this.aeForm.audioUrl=data.VideoUrl
						this.aeForm.audioDuration=data.VideoPlaySeconds
						this.aeForm.audioSize=data.VideoSize
					}
					this.chapterTypeId=data.TypeId

					// 晨报获取指标数据
					if(data.ReportType=='day'){
						this.getDayTicketList()
					}
					
				}
			});
		},

		//预览
		handlePreviewReport() {
			if (!this.aeForm.title) {
				this.$message.error('请输入标题');
				return false;
			}
            if(!this.autoSaveFlag){
				this.$message.error('有图片未上传完成,请稍等')
				return 
			}
            //如果富文本中有未上传完成的图片,去除这个dom
			$('.fr-element').find('img.fr-uploading').length&&$('.fr-element').find('img.fr-uploading').remove()
			let params = {
				ReportId: parseInt(this.report_id),
				AddType: this.aeForm.addType,
				Title: this.aeForm.title,
				Author:this.aeForm.author,
				Content: $('.fr-element').html(),
				CreateTime: this.aeForm.createTime,
			};

				sessionStorage.setItem('reportdtl', JSON.stringify(params));
				let { href } = this.$router.resolve({ name: '预览报告' });
				window.open(href, '_blank');
		},

		//点击发布 首先判断是否为最后一篇
		async handlePublishReport(){
			if(this.$route.query.type=='week'&&!this.aeForm.audioUrl){
				const validRes=await this.handleWeekValidAudio()
				if(!validRes) return
			}
			if(!this.autoSaveFlag){
				this.$message.error('有图片未上传完成,请稍等')
				return 
			}
			this.isPublishloading=true
			const res=await getChapterReportIsLast({ReportChapterId:Number(this.report_id)})
			if(res.Ret===200){
				if(res.Data){
					this.$confirm('本期报告品种已全部更新，点击发布将同时发布周报，确认同时发布吗？','发布提示',{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
						distinguishCancelAndClose:true,
						beforeClose:(action, instance,done)=>{
							if(action=='cancel'){
								this.publishReport(0)
							}else if(action=='confirm'){
								this.publishReport(1)
							}else{
								this.isPublishloading=false
							}
							done()
						}
					})
				}else{
					this.publishReport(0)
				}
			}
		},

		// 周报校验是否上传了音频
		handleWeekValidAudio(){
			return new Promise((resovle,reject)=>{
				this.$confirm('您还未上传录音文件，确定发布报告吗？','发布提示',{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					beforeClose:(action, instance,done)=>{
						if(action=='confirm'){
							resovle(true)
						}else{
							resovle(false)
						}
						done()
					}
				})
			})
		},

		async publishReport(PublishReport){
			let arr=[]
			this.ticketList.forEach(item => {
				let obj={
					ticker:'',
					sort:1,
					lable:''
				}
				if(this.aeForm.ticket.includes(item.BaseColumnTicker)){
					obj.ticker=item.BaseColumnTicker
					obj.sort=arr.length+1
					obj.lable=item.BaseColumnName
					arr.push(obj)
				}
			});
            //如果富文本中有未上传完成的图片,去除这个dom
			$('.fr-element').find('img.fr-uploading').length&&$('.fr-element').find('img.fr-uploading').remove()
			const res=await publishChapterReport({
				ReportChapterId: Number(this.$route.query.id),
				Title:this.aeForm.title,
				AddType:this.aeForm.addType,
				Author:this.aeForm.author,
				CreateTime:this.aeForm.createTime,
				TickerList:arr,
				Content: $('.fr-element').html(),
				PublishReport:PublishReport,
				VideoUrl:this.aeForm.audioUrl,
				VideoName:`${this.aeForm.title}(${moment().format('MMDD')})`,
				VideoPlaySeconds:Number(this.aeForm.audioDuration).toFixed(2).toString(),
				VideoSize:Number(this.aeForm.audioSize).toFixed(2).toString()
			})
			if(res.Ret===200){
				this.$message.success('发布成功')
				setTimeout(() => {
					this.$router.go(-1)
				}, 1000);
			}
			this.isPublishloading=false
		},
		
		insertHtml(item,type='html') {
			//设置编辑器获取焦点
			this.editor.events.focus();
			// 获取选定对象
			const selection = getSelection();
			// 判断是否有最后光标对象存在
			if (this.lastEditRange) {
				// 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
				selection.removeAllRanges();
				selection.addRange(this.lastEditRange);
			}
			//插入内容
			if(type==='image'){
				this.$nextTick(() => {
					this.editor.html.insert(
					`<img style='width:100%' src='${item.PicUrl}' />`)
				})
			}else{
				if(item.Disabled) return this.$message.warning('内部图表，不允许插入报告') 

				const LINK_CHART_URL = process.env.NODE_ENV === "production" ? 'https://chartlib.hzinsights.com/chartshow' : 'https://charttest.hzinsights.com/chartshow';
				this.$nextTick(() => {
						this.editor.html.insert(
						`<p style='text-align:left; margin-top:10px;'>
							<iframe src='${LINK_CHART_URL}?code=${item.UniqueCode}' width='100%' height='350' style='border-width:0px; min-height:350px;'></iframe>
						</p>`)
				})
			}
			this.lastEditRange = selection.getRangeAt(0);
		},
		//批量插入我的图表
		handleImportMyChart(data){
			//设置编辑器获取焦点
			this.editor.events.focus();
			// 获取选定对象
			const selection = getSelection();
			// 判断是否有最后光标对象存在
			if (this.lastEditRange) {
				// 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
				selection.removeAllRanges();
				selection.addRange(this.lastEditRange);
			}
			//插入内容
			let htmlStr=''
			const LINK_CHART_URL = process.env.NODE_ENV === "production" ? 'https://chartlib.hzinsights.com/chartshow' : 'https://charttest.hzinsights.com/chartshow';
			
			data.forEach(item=>{
				const t=new Date().getTime()
				item.domId=item.UniqueCode+t //避免多次添加同一图表 id相同
				htmlStr=htmlStr+`<p style='text-align:left; margin-top:10px;'>
							<iframe id='${item.domId}' src='${LINK_CHART_URL}?code=${item.UniqueCode}' width='100%' height='350' style='border-width:0px; min-height:350px;'></iframe>
						</p>`
			})
			this.$nextTick(()=>{
				console.log('import start',data);
				this.importChartNum=data.length
				this.editor.html.insert(htmlStr)
				this.handleListenIframeLoad(data)
			})
			
			this.lastEditRange = selection.getRangeAt(0);
		},
		// 监听批量导入的iframe是否加载完
		handleListenIframeLoad(list){
			list.forEach(item=>{
				let ifm=document.getElementById(item.domId)
				ifm.onload=(e)=>{
					this.importChartNum--
					console.log('一个iframe加载了',e.path[0]);
				}
			})
		},

		async getChartList(word) {
			let params = {
				Keyword: word || '',
				CurrentIndex: this.search_page,
				PageSize: this.search_page_sizes,
				IsShowMe: this.isShowMe
			}

			let res=null
			if(this.chart_source===1){
				res=await dataBaseInterface.chartSearchByEs(params)
			}else if(this.chart_source===2){
				res=await futuresInterface.searchChart(params)
			}else if(this.chart_source===3){
				res=await chartRelevanceApi.searchChart(params)
			}else if(this.chart_source===6){
				res=await fittingEquationInterface.searchChart(params)
			}else if(this.chart_source===7){
				res=await statisticFeatureInterface.searchChart(params)
			}

			if (res.Ret !== 200) return;
				res.Data.List = res.Data.List || [];
				this.chartlist = this.search_page === 1 ? res.Data.List : [...this.chartlist,...res.Data.List];
				this.search_have_more = this.search_page < res.Data.Paging.Pages;
		},

		loadReportHandle() {
			if(!this.search_have_more) return
			this.search_page++;
			this.getChartList(this.key_word);
		},

		// 获取沙盘图列表 分页
		getSandTable(){
			this.sandTableLoading = true
			this.isRequesting = true
			sandInterface.sandlistByQuote(this.sandTabelQuery).then(({Data:{List,Paging}})=>{
				if(this.sandTabelQuery.CurrentIndex>1){
					this.sandTableList = [...this.sandTableList,...List]
				}else{
					this.sandTableList = List
					this.sandTableTotal = Paging.Totals
					if(this.sandTableList.length ==0){
						this.loadedText = '暂无数据'
					}else if(this.sandTableList.length>=this.sandTableTotal){
						this.loadedText='已全部加载完'
					}else{

					}
				}		
			})
			.finally(()=>{
				this.sandTableLoading = false
				this.isRequesting = false
			})
		},
		// 沙盘列表滚动事件，触底加载下一页数据 防抖
		sandTableHandleScroll:_.debounce(function (e) {
			if(this.sandTableList.length>=this.sandTableTotal){
				this.loadedText = '已全部加载完'
				return
			}
			if(e.target.scrollHeight-e.target.clientHeight-e.target.scrollTop<10 && !this.isRequesting){
				this.sandTabelQuery.CurrentIndex++
				this.getSandTable()
			}
		},100),
		// 获取指标数据
		async getDayTicketList(){
			const res=await dayTicketList({ReportChapterId:Number(this.report_id)})
			if(res.Ret===200){
				this.ticketList=res.Data||[]
				this.ticketList.forEach(item=>{
					if(item.Selected){
						this.aeForm.ticket.push(item.BaseColumnTicker)
					}
				})
			}
		},

		//选择继承报告时 获取上篇报告内容
		async handleAddTypeChange(){
			if(this.aeForm.addType==2){
				const res=await getChapterReportBefore({
					TypeId:Number(this.chapterTypeId),
					ReportType:this.$route.query.type
				})
				if(res.Ret===200){
					let data=res.Data
					this.aeForm.type=data.TypeName
					this.aeForm.title=data.Title
					this.aeForm.author=data.Author||localStorage.getItem('userName')
					this.aeForm.createTime=moment(data.CreateTime).format('YYYY-MM-DD')
					this.aeForm.content=data.Content
					// 晨报获取指标数据
					if(data.ReportType=='day'){
						this.getDayTicketList()
					}
				}
			}
			if(this.aeForm.addType==1){
				this.aeForm.content=''
			}
		},
	},
	components: {importMyChart},
};
</script>

<style scoped lang="scss">
#editreport {
	display: flex;
	overflow: hidden;
	#leftfroala {
		flex: 1;
		max-width: calc(100vw - 750px);
	}
	#rightitems {
		width: 500px;
		flex: 500px 0 0;
		overflow: hidden;
		#tabs {
			padding: 0px 20px;
			box-sizing: border-box;
			margin-bottom: 15px;
			overflow: hidden;
			> p {
				/* display: inline-block; */
				float: left;
				width: 25%;
				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;
			}
			.source-identification{
				text-align: left;
			}
		}
		.loaded-text{
			height: 20px;
			text-align: center;
			color: #666;
			font-size: 14px;
		}
	}
}
</style>
