<template>
	<div class="sand-flow-container">
		<div class="left-wrapper" v-if="!isView">
			<tool-bar :graph="graph"/>
		</div>
		<div class="right-wrapper">
			<header class="sand-top">
				<ul class="form-ul">
					<li style="margin-right:30px;">
						沙盘名称：
						<el-input
							v-model="sandObj.name"
							placeholder="请输入沙盘名称"
							clearable
							style="width:300px">
						</el-input>
					</li>
					<li>
						品种：
						<el-cascader 
							:options="classifyArr"
							:props="classifyProps"
							v-model="sandObj.classify" 
							clearable 
							placeholder="选择品种" 
							size="medium"
							@change="changeClassify"
						/>
					</li>
				</ul>
				<div>
					<el-button type="primary" size="medium" @click="saveChart(null)" v-if="!isView">保存</el-button>
					<el-button type="primary" size="medium" @click="copySandHandle">复制图片</el-button>
				</div>
			</header>
			<div class="flow-wrapper">
				<div id="flow-container"></div>

				<div class="flow-source">来源：弘则研究</div>

				<!-- 右键菜单 -->
				<div class="contextMenu-wrapper" id="contextMenu-wrapper" @mouseleave="hideContextMenu">
					<el-dropdown-menu size="medium">
						<el-dropdown-item v-for="menu in contextMenuOption" :key="menu.key" @click.native="handleContext(menu.key)">
							<i :class="menu.icon" v-if="menu.icon"/> 
							{{menu.label}}
						</el-dropdown-item>
					</el-dropdown-menu>
				</div>

				<!-- 提示区 -->
				<div class="tip-wrapper" v-if="isShowTip">
					<i class="el-icon-d-arrow-left" style="font-size: 60px;"></i>拖拽图形开始绘制
				</div>
                <!-- 缩略图 -->
                <div id="minimap" class="minimap"></div>

			</div>
		</div>
	</div>
</template>

<script>
import { ElDropdownMenu } from 'element-ui';
import { sandInterface,customInterence,dataBaseInterface } from '@/api/api.js';
import { myGraph } from '../common/gragh';
import toolBar from './toolBar';
import { contextMenuOption } from '../common/options';
import { contextEvent } from '../common/events';
import { copyBlob,svgToBase64 } from '@/utils/svgToblob'
export default {
	name:'',
	components: { toolBar,ElDropdownMenu },
	data () {
		return {
			graph: null,
			sand_id: this.$route.query.id || '',
			contextMenuOption,
			sandObj: {
				name: '',
				classify: ''
			},
			editable_id: '',
			classifyArr:[],
			classifyProps: {
				children: 'Items',
				label: 'ClassifyName',
				value: 'ChartPermissionId'
			},
			initData: {},
			sandInfo:{},
			loopTimer: null,
			lockLoding: null,
			isShowTip: this.$route.query.id ? false : true,
		};
	},
	watch: {
		initData(newval) {
			console.log(newval)
			this.graph.fromJSON(newval);
		},
	},
	computed: {
		isView() {
			return this.$route.query.type === 'view';
		}
	},
	methods: {
		/* 获取品种 */
		getClassify() {
			customInterence.getvariety({
				CompanyType: 'ficc'
			}).then(res => {
				if(res.Ret !== 200)  return
					this.classifyArr = res.Data.List;
			})
		},

		/* 获取画布内容 */
		getGraphData() {
			const { id,type } = this.$route.query;

			// type === 'edit' && sandInterface.sandData({
			// 	SandboxId: id
			// }).then(res => {
			// 	if(res.Ret !== 200) return

			// 	const { Name,ChartPermissionId,Content } = res.Data;
			// 	this.sandObj = {
			// 		name: Name,
			// 		classify: ChartPermissionId
			// 	}
			// 	this.initData = JSON.parse(Content);
			// 	this.sandInfo = res.Data;
			// 	// 轮询
			// 	this.$route.query.type === 'edit' && this.autoSave();
			// })

			sandInterface.versionData({
				SandboxVersionCode: id
			}).then(res => {
				if(res.Ret !== 200) return

				const { Name,ChartPermissionId,Content } = res.Data;
				this.sandObj = {
					name: Name,
					classify: ChartPermissionId
				}
				this.initData = JSON.parse(Content);
                this.$nextTick(()=>{
                    this.graph.centerContent()
                })
				if(type === 'edit') {
					this.sandInfo = res.Data;
					// 轮询
					this.autoSave();
                    //this.graph.centerContent();
				}
			})
		},

		/* 保存 */
		saveChart: _.debounce( function(callback=null) {
			if(!this.sandObj.name || !this.sandObj.classify) return this.$message.warning(`${this.sandObj.classify ? '请填写沙盘名称' : this.sandObj.name ? '请选择沙盘品种' : '请填写沙盘名称和品种'}`);

			if(!this.graph.toJSON().cells.length) return this.$message.warning('请绘制画布内容');

			const { name, classify } = this.sandObj;

			this.lockLoding = this.$loading({
				lock: true,
				text: '保存中...',
				target: '.right-wrapper',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, 0.8)'
			});
			const { cells } = this.graph.toJSON();
			this.graph.toSVG(async (dataUri) => {
				const params = new FormData();
				params.append('Img',dataUri)
				const { Data } = await dataBaseInterface.uploadImgSvg(params);
				let SandboxVersionCode = (this.sand_id && classify === this.sandInfo.ChartPermissionId)  ? this.sand_id : '';
				
				const { Ret } =	await sandInterface.sandSave({
					SandboxVersionCode,
					Name: name,
					ChartPermissionId: classify,
					Content: JSON.stringify(this.graph.toJSON()),
					PicUrl: Data.ResourceUrl,
					SvgData: dataUri
				})

				if(Ret !== 200) return;
				this.$message.success(`${SandboxVersionCode ? '编辑成功' : '保存成功'}`);
				this.lockLoding.close();
				!SandboxVersionCode && window.close();
				
				callback && callback();
			},{
				preserveDimensions:true,//让svg为实际图片大小
				beforeSerialize:(svg)=>{
					const {x,y,width,height} = this.graph.getContentBBox(cells)
					let {tx,ty} = this.graph.translate() // 画布偏移量
					//给导出的svg增加一点宽高
					svg.setAttribute('width',width+50)
					svg.setAttribute('height',height+50) 
					//设置viewBox使图像居中
					svg.setAttribute('viewBox',`${x-25} ${y-25} ${width+50} ${height+50}`)
					// 在图表右下方 加上"来源：弘则研究"字样
					let gNode = svg.getElementsByClassName('x6-graph-svg-viewport')[0]
					let textNode = document.createElement('text')
					textNode.setAttribute('x',x-tx+width-90)
					textNode.setAttribute('y',y-ty+height+22)
					textNode.setAttribute('font-size','16px')
					textNode.setAttribute('font-style','italic')
					textNode.innerText = '来源：弘则研究'
					gNode.appendChild(textNode)
        		},
				copyStyles:false,
				stylesheet: `
    				svg{
      					background-color:white;
    				}
					.x6-port {
  						visibility: hidden;
					}
					` 
			})
				
		},500),

		/* 复制图片 */
		copySandHandle: _.debounce(function() {

			const { cells } = this.graph.toJSON();
			if(!cells.length) return this.$message.warning('当前画布无可复制内容');

			this.lockLoding = this.$loading({
				lock: true,
				text: '复制图片中...',
				target: '.right-wrapper',
				spinner: 'el-icon-loading',
				background: 'rgba(255, 255, 255, 0.8)'
			});
			this.graph.toSVG(async(dataUri) => {
				/* const params = new FormData();
				params.append('Img',dataUri)
				const { Data } = await dataBaseInterface.uploadImgSvg(params);
				const copyImg = document.createElement('img');
				$('.sand-flow-container')[0].appendChild(copyImg);
				copyImg.src = Data.ResourceUrl;
				this.getSelect(copyImg);
				setTimeout(() => {
					document.execCommand('copy');
					$('.sand-flow-container')[0].removeChild(copyImg);
					this.lockLoding && this.lockLoding.close();
					this.$message.success('复制成功');
				}); */
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");
                const img = new Image();
                img.crossOrigin = "Anonymous";
                img.src = svgToBase64(dataUri);
                img.onload = ()=>{
                canvas.width = img.width;
                canvas.height = img.height;
                console.log('width',img.width)
                console.log('height',img.height)
                ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
                ctx.fillStyle="#fff";
                ctx.fillRect(0, 0, img.width, img.height);
                ctx.drawImage(img, 0, 0);
                canvas.toBlob(async (blob) => {
                    const data = [new ClipboardItem({ [blob.type]: blob })]; 
                    await navigator.clipboard.write(data).then(
                    () => {
                        this.$message.success('复制成功！')
                    },
                    () => {
                        this.$message.success('复制失败,稍后再试')
                    }
                    ).finally(()=>{
                        this.lockLoding && this.lockLoding.close();
                    });
                });
                }
			},{
				preserveDimensions:true,//让svg为实际图片大小
				beforeSerialize:(svg)=>{
					const {x,y,width,height} = this.graph.getContentBBox(cells)
					let {tx,ty} = this.graph.translate()
					//给导出的svg增加一点宽高
					svg.setAttribute('width',width+50)
					svg.setAttribute('height',height+50) 
					//设置viewBox使图像居中
					svg.setAttribute('viewBox',`${x-25} ${y-25} ${width+50} ${height+50}`)
					let gNode = svg.getElementsByClassName('x6-graph-svg-viewport')[0]
					let textNode = document.createElement('text')
					textNode.setAttribute('x',x-tx+width-90)
					textNode.setAttribute('y',y-ty+height+22)
					textNode.setAttribute('font-size','16px')
					textNode.setAttribute('font-style','italic')
					textNode.innerText = '来源：弘则研究'
					gNode.appendChild(textNode)
        		},
				copyStyles:false,
				stylesheet: `
    				svg{
      					background-color:white;
    				}
					.x6-port {
  						visibility: hidden;
					}` 
					
			})
		},500),
		
		/* 右键事件 */
		handleContext(key) {
			contextEvent(this.graph, key);
			this.hideContextMenu();
		},

		/* 隐藏右键menu */
		hideContextMenu() {
			const dom = $('#contextMenu-wrapper')[0];
			dom.style.left = '-9999px';
			dom.style.top = '-9999px';
		},

			// 选择
    getSelect(targetNode) {
      if (window.getSelection) {
        //chrome等主流浏览器
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNode(targetNode);
        selection.removeAllRanges();
        selection.addRange(range);
      } else if (document.body.createTextRange) {
        //ie
        var range = document.body.createTextRange();
        range.moveToElementText(targetNode);
        range.select();
      }
    },

		changeClassify(e) {

			this.sandObj.classify = e.length ? e[1] : '';
		},

		/* 编辑页 自动保存 */
		autoSave() {
			this.loopTimer = setInterval(() => {

				if(!this.sandObj.name || !this.sandObj.classify) return;
				const { name, classify } = this.sandObj;

				sandInterface.draftSave({
					SandboxVersionCode: this.sand_id,
					Name: name,
					ChartPermissionId: classify,
					Content: JSON.stringify(this.graph.toJSON())
				}).then((res) => {

					if(res.Ret === 202) return clearInterval(this.loopTimer);
					// if (res.Ret !== 200) return;
				});
			}, 10000);
		},

		/* init画布 */
		init() {
			const graph = new myGraph('flow-container');

			//graph.centerContent();
			// graph.fromJSON(this.initData);
			this.graph = graph;
		}
	},
	
	beforeRouteLeave(to,from,next) {
		// 编辑页 添加页切换路由提示保存
		if(this.$route.query.type !== 'view') {
			this.$confirm("在离开页面之前，是否保存当前内容？", "保存提示", {
					type: "warning"
				}).then(() => {
					this.saveChart(() => {
						this.$route.query.type === 'edit' && sandInterface.mark({ SandboxId:this.sandInfo.SandboxId,Status:2 });
						next();
					});
				}).catch(() => {
					this.$route.query.type === 'edit' && sandInterface.mark({ SandboxId:this.sandInfo.SandboxId,Status:2 });
					this.$route.query.type === 'edit' && sandInterface.cancelSave({ SandboxId:this.sandInfo.SandboxId });
					next();
				})
		}else {
			next();
		}

	},

	mounted() {
		this.init();
		this.getClassify();

		this.$route.query.id && this.getGraphData();
		
	},
	destroyed() {
		if(this.loopTimer) clearInterval(this.loopTimer);
	}
}
</script>
<style lang='scss'>
.sand-flow-container {
	display: flex;
	height: calc(100vh - 120px);
	* { box-sizing: border-box;}
	.left-wrapper {
		width: 300px;
		min-width: 300px;
		height: 100%;
		margin-right: 20px;
		background-color: #fff;
		border: 1px solid #ececec;
		box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
	}
	.right-wrapper {
		flex: 1;
		height: 100%;
		border: 1px solid #ececec;
		position: relative;
		overflow: hidden;
		.sand-top {
			padding: 10px 20px;
			background: #fff;
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			display: flex;
			border-bottom: 1px solid #ECECEC;
			z-index: 1;
			.form-ul {
				flex: 1;
				display: flex;
			}
		}
		.flow-wrapper {
			position: relative;
			height: 100%;
			display: flex;
			/* overflow: auto; */
			padding-top: 60px;
			// padding-bottom:30px;
			.flow-source{
				position: absolute;
				right: 10px;
				bottom: 8px;
				font-size: 20px;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #666666;
			}
			#flow-container {
				flex: 1;
			}
			.x6-graph-scroller {
				flex: 1;
			}

			.x6-port-body {
				display: none;
			}

			/* reseize 框样式 */
			.x6-widget-transform {
				.x6-widget-transform-resize {
					border-radius: 0;
				}
			}
			
			.contextMenu-wrapper {
				position: fixed;
				z-index: 99;
				top: -9999px;
				left: -9999px;
				background: #fff;
				padding: 10px 0;
				/* border: 1px solid #999; */
				box-shadow: 0 1px 4px #999;
			}

			.editable-wrapper {
				position: fixed;
				top: -999px;
				left: -999px;
				outline: none;
				z-index: 99;
				padding: 5px;
			}

			.tip-wrapper {
				position: absolute;
				top: 50%;
				left: 10%;
				z-index: 99;
				font-size: 40px;
				color: #bbb;
				display: flex;
				align-items: center;
			}
			.minimap{
				position:absolute;
				right:6px;
				bottom:6px;
				box-sizing: border-box;
				.x6-widget-minimap-viewport{
					border-color: red;
					.x6-widget-minimap-viewport-zoom{
						border-color: red;
					}
				}
				.x6-widget-minimap{
					width: auto !important;
					height: auto !important;
				}
			}
		}
	}
}
</style>