<template>
	<div class="addppt-container">
		<div class="addppt-left-cont">
			<div class="first-page" @click="openDialog">
				<img :src="firstPage.bg" alt="" class="first-bg" v-if="firstPage.bg">
				<div class="shade_first" v-if="!firstPage.title">
					<img src="~@/assets/img/ppt_m/add_first.png" alt="">
					<span>选择封面页</span>
				</div>
				<div v-else style="width:70%;textAlign:center;font-size:12px;line-height:1.6; color:#fff; position:absolute; right:10px; top:50%;">
					<p>{{firstPage.title}}</p>
					<p>{{firstPage.date}}</p>
				</div>
			</div>
			<template v-if="pptList.length">
				<div style="color:#409EFF;fontSize:15px;paddingLeft:10px;marginBottom:4px;">已添加{{pptList.length}}页</div>
				<transition-group name="flip-list">
					<div 
					v-for="(item,index) in pptList" 
					:key="item" 
					draggable="true" 
					:class="['drag-item',{'choose':item.timestamp===default_ppt}]"
					@click="choosePPtItem(item,index,0)"
					@dragstart="dragstart(item)" 
					@dragenter="dragenter(item)" 
					@dragend="dragend(item)">
						<img src="~@/assets/img/ppt_m/pppage_ico.png" class="drag-left">
						<div class="drag-right text_twoLine">
							{{item.title}}
						</div>
						<el-popconfirm
						@onConfirm="delPage(index)"
						confirmButtonText='删除'
						cancelButtonText='取消'
						confirmButtonType="text"
						icon="el-icon-info"
						iconColor="red"
						title="确定删除该页ppt吗"
						>
							<img src="~@/assets/img/ppt_m/close.png" class="close_ico" slot="reference">
						</el-popconfirm>
						<img src="~@/assets/img/ppt_m/move_ico.png" alt="" class="move_ico">
						<span style="position:absolute;right:10px;bottom:5px;color:#888;fontSize:12px;">第{{index+1}}页</span>
					</div>
				</transition-group>
			</template>
			<div style="color:#A3AFBB;fontSize:14px;textAlign:center;marginTop:124px;" v-else>
				<img src="~@/assets/img/ppt_m/noppt.png" alt="" style="width:60px;height:33px;display:block;margin:0 auto 10px;">	
				<span>添加正文后，会在这里生成</span>
			</div>
		</div>
		<!-- ppt正文 -->
		<div class="addppt-mid-cont" ref="pptmid">
			<template v-if="pptList.length">
				<transition-group name="flip-list">
					<div class="ppt-list" v-for="(item,index) in pptList" :key="item">
						<div style="display:flex;alignItems:center;justifyContent:space-between;">
							<img src="~@/assets/img/ppt_m/add.png" alt="" class="add_ico" @click="addPage(index)">
							<el-popconfirm
							@onConfirm="delPage(index)"
							confirmButtonText='删除'
							cancelButtonText='取消'
							confirmButtonType="text"
							icon="el-icon-info"
							iconColor="red"
							title="确定删除该页ppt吗"
							>
								<img src="~@/assets/img/ppt_m/close.png" alt="" style="width:18px;height:18px;marginBottom:20px;" slot="reference">
							</el-popconfirm>
						</div>
						<div :class="['ppt-item',{'choose':item.timestamp===default_ppt}]" @click="choosePPtItem(item,index,1)" :id="'pptItem'+index">
							<input type="text" placeholder="请输入页面标题" class="item_tit" v-model="item.title"> 
							<div class="container" :id="'container'+item.resource_id" v-if="item.resource_id"></div>
							<div class="container" v-if="item.noSource">
								<img src="https://hzstatic.hzinsights.com/static/ppt_default.png" alt="" style="width:400px;height:300px;margin:0 auto;display:block;">
							</div>
						</div>
						<span style="position:absolute; bottom:3%; right:20px; color:#666;">第{{index+1}}页</span>
					</div>
				</transition-group>
			</template>
			<div v-else class="ppt-list" style="display:flex;alignItems:center;" @click="addPage('last')">
				<img src="~@/assets/img/ppt_m/add.png" alt="" class="add_ico" style="display:inline-block;marginBottom:0">
				<span style="display:inline;color:#999;fontSize:20px;">点击添加正文</span>
			</div>
			<div class="ppt-list" v-if="pptList.length">
				<img src="~@/assets/img/ppt_m/add.png" alt="" class="add_ico" @click="addPage('last')">
			</div>
		</div>
		<!-- 右侧图表 -->
		<div class="addppt-right-cont">
			<!-- <span style="marginRight:43%"></span> -->
			<el-button type="primary" @click="previewHandle" style="marginRight:15px;">去发布</el-button>
			<el-button type="primary" @click="savePPt" plain>保存</el-button>
			<el-input placeholder="关键字查找" v-model="key_word" size="medium" prefix-icon="el-icon-search" @input="getreportlist(key_word)" style="margin:20px 0;maxWidth:100%;"></el-input>
			<div id="chartList" style="height:calc(100vh - 250px); overflow-x:hidden; overflow-y:auto; border:1px solid #B2B9C3; position:relative;padding:30px 20px;" v-loading="reportloadding">
				<template v-if="chartList.length">
					<div v-for="(item,index) in chartList" :key="index" class="chart-item" @click="gething(item,index)" >
						<p class="chart_tit">{{item.ChartName}}</p>
						<img :src="item.ChartImage" ref="insert_img" style="width:100%;height:263px"/>
					</div>
				</template>
				<img v-else src="../../assets/img/ppt_m/nodata.png" alt="" style="max-width:186px;height:195px;position:absolute;left:30%;top:30%;">
			</div>
		</div>
		<!-- 封面选择弹窗 -->
		<div class="first_dialog" v-if="isShowdialog">
			<div class="dialog-min">
				<header class="dialog-top">
					<span>选择封面</span>
					<img src="~@/assets/img/ppt_m/close.png" alt="" class="close_ico" @click="closeDialog">
				</header>
				<div class="dialog-bg" :style="'backgroundImage:url('+firstPage.bg+');backgroundPosition:center;backgroundRepeat:no-repeat;backgroundSize:cover;'">
					<div style="width:62%; font-size:16px; text-align:center; line-height:1.6; color:#fff; position:absolute; right:20px; top:50%;">
						<p style="height:5px; border-top:1px solid #fff;marginBottom:21px;"></p>
						<!-- <p style="max-width:90%; font-size:28px; line-height:1.4; font-weight:bolder; margin:0 auto;">{{firstPage.title}}</p> -->
						<input 
						type="text" 
						style="max-width:90%; font-size:28px; line-height:1.4; font-weight:bolder; margin:0 auto;background:transparent;color:#fff;border:none;textAlign:center;" 
						v-model="firstPage.title" 
						placeholder="请输入标题">
						<p style="display:flex; align-items:center; justify-content:center;margin:10px 0;">
							<span style="display:inline-block; width:15px; margin-right:5px; border-top:1px solid #fff;"></span>
							<span>弘则弥道（上海）投资咨询有限公司</span>
							<span style="display:inline-block; width:14px; height:14px; background:#fff; border-radius:100%; margin:0 5px;"></span>
							<input 
							type="text" 
							style="max-width:80px;background:transparent;color:#fff;border:none;textAlign:center;display:inline-block" 
							v-model="firstPage.type" 
							placeholder="请输入类型">
							<span style="display:inline-block; width:15px; margin-left:5px; border-top:1px solid #fff;"></span>
						</p>
						<p>FICC研究部</p>
						<el-date-picker
							v-model="firstPage.date"
							type="month"
							ref="date_pic"
							format="yyyy年M月"
							value-format="yyyy年M月"
							placeholder="请选择日期">
						</el-date-picker>
						<p style="width:80%; height:1px; border-bottom:1px solid #fff; margin:21px auto 0;"></p>
					</div>
					<!-- <img src="~@/assets/img/ppt_m/bg_select.png" alt="" class="select_ico"> -->
				</div>
				<div class="dialog-bot">
					<span></span>
					<div>
						<el-button  type="primary" style="width:120px" @click="saveFirstPage">保存</el-button>
						<el-button style="width:120px" @click="changeBg">换一个模板</el-button>
					</div>
				</div>
			</div>
		</div>
		<el-dialog
		title="提示" 
		:visible.sync="isSave"
		:close-on-click-modal="false"
		:modal-append-to-body='false'
		:show-close="false"
		@close="cancelHandle"
		center
		width="30%">
			<div slot="title" style="display:flex;alignItems:center;">
				<img :src="$icons.warn" style="color:#fff;width:16px;height:16px;marginRight:5px;">
				<span style="fontSize:16px;">提示</span>
			</div>
			<div style="color:#3377FF;fontSize:24px;paddingTop:54px;text-align:center;">编辑成功</div>
			<div style="display:flex;justifyContent:center;margin:45px 0 47px;">
				<el-button type="primary" style="width:120px;marginRight:60px;" @click="previewHandle">预览发布</el-button>
				<el-button type="primary" plain style="width:120px;" @click="back">返回列表</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { pptedit,pptdetail,dataBaseInterface } from '@/api/api.js';
import html2canvas from 'html2canvas';
import Highcharts from 'highcharts/highstock';
import HighchartszhCN  from '@/utils/highcahrts-zh_CN'
HighchartszhCN(Highcharts)
import { defaultOpts, seasonOptions,getTerminal,browser } from '@/utils/defaultOptions';
import chartMixin from './mixins/mixins'

export default {
	name:'',
	mixins: [ chartMixin ],
	components: {
		html2canvas
	},
	data () {
		return {
			chartList:[],//图表列表
			reportloadding:false,//图表loading
			key_word:'',//搜索关键字
			default_bg:0,//默认封面背景
			firstPage:{
				title:'',
				bg:'',
				type:'',
				date:''
			},//ppt首页
			isSave:false,
			isShowdialog:false,
			pptList:[],//内容页
			default_ppt:'',//默认选中ppt的时间戳
			oldNum:0,//拖拽前的位置
			newNum:0,//拖拽后的位置
			zchart:null,//图表配置
			axisOption:{
				gridLineWidth: 0,
				minorGridLineWidth: 0,
				opposite: false,
				lineWidth: 1,
				lineColor: '#bfbfbf',
				tickColor: '#bfbfbf',
				tickLength: 5,
				tickWidth: 1,
				title: {
					text: ""
				},
				endOnTick: false,
				startOnTick: false,
				labels: {x: -5,},
				visible: false,
			},
			hcredits:'',
			datasource:'',
			ppt_id:this.$route.query.id,
			loading:null,
			/* new source */
			chartInfo: {},//图表信息
			dataList: [],//图表关联指标
			options:{}
		};
	},
	methods: {
		// 获取图表列表
		getreportlist(word){
			$('#chartList').animate({scrollTop:0},100);
			if( this.reportloadding ) return false;
			this.reportloadding=true;
			dataBaseInterface
				.chartSearch({
					KeyWord: word || '',
				})
				.then((res) => {
					if (res.Ret !== 200) return;
					this.chartList = res.Data || [];
					this.reportloadding=false;
				});
		},
		// 获取ppt详情
		getpptdtl(){
			this.loading = this.$loading({
				target:'.addppt-container',
				lock: true,
				text: '拼命加载中...',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.6)'
			});
			pptdetail({PptId:this.ppt_id}).then(res =>{
				if( res.Ret === 200 ){
					let pptpage=res.Data.PptPages || [];
					this.firstPage={
						title:res.Data.Ppt.Title,
						type:res.Data.Ppt.ReportType,
						date:res.Data.Ppt.PptDate,
						bg:this.bgList[parseInt(pptpage[0].BackIndex)].image_url,
						ppt_pages_id:parseInt(pptpage[0].PptPagesId),
					}
					this.pageitem=[];
					pptpage.forEach((item,i)=>{
						if( i!=0 ){
							this.pptList.push({
								title:item.Title,
								ppt_pages_id:parseInt(item.PptPagesId),
								resource_id:item.ResourceId,
								timestamp:parseInt(item.Timestamp)
							});
						}
					});
					this.default_ppt = this.pptList[0].timestamp;//默认选中第一个
					this.listHandle()
				}
			});
		},
		async listHandle() {
			// this.pptList.forEach((item,index) => {
			// 	await this.getChart(item,index)
			// })
			for(let i=0;i<this.pptList.length;i++) {
				await this.getChart(this.pptList[i],i)
			}
		},
		// 加载图表
		async getChart(item,index) {

			const { Data } = await dataBaseInterface.getChartByCode({
				UniqueCode: item.resource_id
			})
			this.chartInfo = Data.ChartInfo;
			this.dataList = Data.EdbInfoList;

			Data.Status && this.setOptions();

			this.$nextTick(()=> {
				if(	Data.Status) {
					const new_options = { ...defaultOpts, ...this.options };
					new_options.chart = {
						backgroundColor: 'transparent'
					}
					let is_scatter = this.options.series ? this.options.series.every(_ => _.type === 'scatter') : false ;
					is_scatter ? Highcharts.chart('container'+item.resource_id, new_options) : Highcharts.stockChart('container'+item.resource_id, new_options);
				}else {
					this.$set(item,'noSource',true);
				}
				if(index === this.pptList.length-1)  {
					this.loading.close();
				}
			})
		},
		// 删除页
		delPage(index) {
			this.pptList.splice(index,1)
		},
		// 打开弹窗
		openDialog() {
			this.isShowdialog = true
		},
		// 点击x关闭弹窗不保存填写的信息
		closeDialog() {
			this.isShowdialog = false
		},
		// 换一个模板
		changeBg() {
			this.default_bg++;
			if(this.default_bg > this.bgList.length-1) {
				this.default_bg = 0;
			}
			this.$set(this.firstPage,'bg',this.bgList[this.default_bg].image_url)
		},
		// 保存首页
		saveFirstPage() {
			if(!this.firstPage.title) {
				this.$message.warning('请输入标题！')
			}else if(!this.firstPage.type) {
				this.$message.warning('请输入类型！')
			}else if(!this.firstPage.date) {
				this.$message.warning('请选择时间！')
			}else {
				this.isShowdialog = false
			}
		},
		shuffle() {
       	this.pptList = _.shuffle(this.pptList);
      },
      // 开始位置
      dragstart(value) {
       	this.oldNum = value;
      },
      // 拖动完成
      dragend(value) {
			if (this.oldNum != this.newNum) {
				let oldIndex = this.pptList.indexOf(this.oldNum);
				let newIndex = this.pptList.indexOf(this.newNum);
				let newItems = [...this.pptList];
				// 删除老的节点
				newItems.splice(oldIndex, 1); 
				// 在列表中目标位置增加新的节点
				newItems.splice(newIndex, 0, this.oldNum);
				this.pptList = [...newItems];
				console.log(this.pptList)
			}
      },
      // 目标位置
      dragenter(value) {
        this.newNum = value;
		},
		// 添加页
		addPage(index) {
			let obj ={
				title:'',
				resource_id:'',
				timestamp:new Date().getTime()
			}
			if(index == 'last') {
				this.pptList.push(obj);
				this.default_ppt = this.pptList[this.pptList.length-1].timestamp;
			}else {
				this.pptList.splice(index,0,obj);
				this.default_ppt = this.pptList[index].timestamp;
			}
		},
		// 获取图表
		async gething(item,index) {

			let have_bool = this.pptList.some(x => x.resource_id === item.UniqueCode);
			if(have_bool) return this.$message.warning('该图表已被使用');

			const { Data } = await dataBaseInterface.getChartByCode({
				UniqueCode: item.UniqueCode
			})
			this.chartInfo = Data.ChartInfo;
			this.dataList = Data.EdbInfoList;

			// 定位指定的图表
			this.pptList.forEach(pptItem => {
				if(pptItem.timestamp === this.default_ppt) {
					this.$set(pptItem,'resource_id',item.UniqueCode)
					this.$set(pptItem,'noSource',false)
				}
			})

			this.setOptions();

			this.$nextTick(()=> {
				const new_options = { ...defaultOpts, ...this.options };
				new_options.chart = {
					backgroundColor: 'transparent'
				}
				
				let is_scatter = this.options.series ? this.options.series.every(_ => _.type === 'scatter') : false ;
				is_scatter ? Highcharts.chart('container'+item.UniqueCode, new_options) : Highcharts.stockChart('container'+item.UniqueCode, new_options);
				
			})
		},
		// 切换选中的ppt页
		choosePPtItem(item,index,type) {
			this.default_ppt = item.timestamp;
			if(type == 0) {
				let h_item = $('#pptItem'+index)[0].offsetHeight+80;
				this.$refs.pptmid.scrollTo(0,parseInt(h_item*index),100)
			}
		},
		// 保存为草稿
		savePPt() {
			console.log(this.firstPage,this.pptList)
			if(!this.firstPage.title) {
				this.$message.warning('请填写封面标题！')
			}else if(!this.firstPage.type) {
				this.$message.warning('请填写封面类型！')
			}else if(!this.firstPage.date) {
				this.$message.warning('请填写封面日期！')
			}else if(!this.pptList.length) {
				this.$message.warning('请添加ppt！')
			}else {
				// 校验ppt每一页必须有标题和内容
				let B_check =  this.pptList.every(item => {
					return item.title
				})
				let B_check2 =  this.pptList.every(item => {
					return item.resource_id
				})
				if(!B_check) {
					this.$message.warning('请填写ppt标题！')
				}else if(!B_check2) {
					this.$message.warning('请插入ppt内容！')
				}else {
					let content_page = []
					this.pptList.forEach(item => {
						content_page.push({
							ResourceId:item.resource_id,
							Title:item.title,
							Timestamp:item.timestamp,
							PptPagesId:item.ppt_pages_id
						})
					})
					let params = {
						FirstPage:{
							Title:this.firstPage.title,
							ReportType:this.firstPage.type,
							PptDate:this.firstPage.date,
							ImgUrl:this.firstPage.bg,
							PptPagesId:this.firstPage.ppt_pages_id,
							BackIndex:parseInt(this.default_bg)
						},
						ContentPage:content_page,
						PptId:parseInt(this.ppt_id),
					}
					// console.log(params)
					pptedit(params).then(res => {
						if(res.Ret === 200) {
							// this.ppt_id = res.ppt_id;
							// this.isSave = true;
							this.$message.success('保存成功!')
						}
					})
				}
			}
		},
		cancelHandle() {
			this.isSave = false
		},
		// 预览发布
		previewHandle() {
			sessionStorage.setItem('ppt_id',this.ppt_id);
			this.$router.push({path:'/pptdtl'});
			// let {href} = this.$router.resolve({name:'预览ppt'});
			// window.open(href,'_blank');
		},
		// 返回列表
		back() {
			this.$router.push({path:'/pptlist'});
		},
		init() {
			this.key_word = ''//搜索关键字
			this.default_bg = 0//默认封面背景
			this.firstPage = {
				title:'',
				type:'',
				date:'',
				bg:this.bgList[0].image_url
			}//ppt首页
			this.pptList = []//内容页
			this.ppt_id = ''
		},
	},
	created() {
		
	},
	updated() {
		// reset
		$('.el-date-editor .el-input__inner').css({backgroundColor: 'transparent',border:'none',color:'#fff',textAlign:'center',fontSize:'16px'});
		$('.el-date-editor .el-icon-date' ).css({display:'none'});
		$('.ppt-item').css('height',$('.ppt-item').width()*0.7);
	},
	mounted() {
		this.getpptdtl();
		this.getreportlist();
		// this.firstPage.bg = this.bgList[0].image_url;
	},
}
</script>
<style lang='scss' scoped>
* {
	box-sizing: border-box;
}
/* 控制文字显示两行 */
.text_twoLine {
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  -webkit-line-clamp:2;
}
/*修改滚动条样式*/
	div::-webkit-scrollbar{
		width:5px;
		height:5px;
	}
	div::-webkit-scrollbar-track{
		background: rgb(239, 239, 239);
		border-radius:2px;
	}
	div::-webkit-scrollbar-thumb{
		background: #ccc;
		border-radius:10px;
	}
	div::-webkit-scrollbar-thumb:hover{
		background: #888;
	}
	div::-webkit-scrollbar-corner{
		background: #179a16;
	}
/**/
// reset
.addppt-container {
	background: #fff;
	padding: 20px;
	display: flex;
	position: relative;
	// justify-content: space-between;
	.flip-list-move {
    	transition: transform 0.5s;
   }
	.addppt-left-cont {
		// max-width: 260px;
		max-width: 15%;
		min-width: 190px;
		border: 1px solid #B2B9C3;
		max-height: calc(100vh - 125px);
		padding-bottom: 12px;
		overflow-y: auto;
		overflow-x: hidden;
		.first-page {
			width: 100%;
			height: 180px;
			margin-bottom: 30px;
			padding: 5px 7px;
			position: relative;
			.shade_first {
				position: absolute;
				left: 50%;
				top: 50%;
				transform: translate(-50%,-50%);
				color: #fff;
				img {
					width: 44px;
					height: 44px;
					display: block;
					margin: 0 auto 11px;
				}
			}
			.first-bg {
				// min-width: 267px;
				max-width:100%;
				height: 180px;
			}
		}
		.drag-item {
			height: 80px;
			padding: 20px 56px 20px 7px;
			border: 1px solid #ccc;
			position: relative;
			display: flex;
			align-items: center;
			&.choose {
				border-color: rgba($color: #4B8DFF, $alpha: 1);
			}
			.drag-left {
				width: 40px;
				height: 34px;
				margin-right: 10px;
			}
			.drag-right {
				width: 168px;
				word-break: break-all;
				color: #666;
				font-size: 14px;
			}
			.close_ico {
				width: 12px;
				height: 12px;
				position: absolute;
				right: 10px;
				top: 10px;
			}
			.move_ico {
				width: 12px;
				height: 12px;
				position: absolute;
				right: 10px;
				top: 38px;
			}
		}
	}
	.addppt-mid-cont {
		max-width: 850px;
		min-width: 700px;
		flex: 1;
		max-height: calc(100vh - 125px);
		overflow: auto;
		// overflow-x: hidden;
		padding: 30px 14px;
		border:1px solid #B2B9C3;
		margin: 0 5px;
		.ppt-list {
			position: relative;
			.add_ico {
				width: 28px;
				height: 28px;
				display: block;
				margin-bottom: 20px;
			}
			.ppt-item {
				width: 100%;
				height: 580px;
				background: url('~@/assets/img/pptnextimg.png') no-repeat center;
				background-size: cover;
				margin-bottom: 30px;
				position: relative;
				border: 4px solid transparent;
				&.choose {
					// box-shadow: 1px 1px 2px rgba($color: #409eff, $alpha: 0.6);
					border: 4px solid rgba($color: #4B8DFF, $alpha: 0.7);
				}
				.item_tit {
					width: 65%;
					position: absolute;
					left: 90px;
					top: 40px;
					font-size: 24px;
					border: none;
					color: #666;
					background: transparent;
				}
			}
			.last-page {
				max-width: 850px;
				height: 580px;
			}
			.container {
				width: 80%;
				position: absolute;
				left: 50%;
				top: 55%;
				transform: translate(-50%,-50%);
			}
		}
	}
	.addppt-right-cont {
		width: 26%;
		.chart-item {
			text-align: center;
			color: #74818D;
			font-size: 18px;
			margin-bottom: 12px;
		}
	}
	.first_dialog {
		position: fixed;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		background:rgba($color: #000000, $alpha: 0.4);
		z-index: 999;
		.dialog-min {
			width: 50%;
			padding: 30px 54px 26px;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);
			background: #fff;
			.dialog-top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 24px;
				color: #1F2E4D;
				margin-bottom: 22px;
				.close_ico {
					width: 28px;
					height: 28px;
				}
			}
			.dialog-bg {
				width: 100%;
				height: 645px;
				position: relative;
				.select_ico {
					width: 48px;
					height: 48px;
					position: absolute;
					right: 15px;
					top: 15px;
				}
			}
			.dialog-bot {
				margin-top: 22px;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
		}
	}
}
</style>