<template>
	<div>
		<el-row>
		  <!-- 模板树 -->
		  <el-col :span="6" >
			<div style="height: 100vh;overflow: scroll;">
				<el-tree :data="diagrams" :props="{children: 'children', label: nodeLabel, value: 'id'}"
					@node-click="open"
					default-expand-all
					:expand-on-click-node="false">
					<span class="custom-tree-node" slot-scope="{ node, data }">
						<span>{{ node.label}}</span>
						<span style="padding-left: 10px;">
							<el-button type="text" size="mini" icon="el-icon-plus" @click="() => newDiagram(node)"
								v-if="data.objType == 'folder' && data.type == 'type'">
								创建系统图
							</el-button>
							<el-popconfirm title="确定删除？" v-if="data.objType != 'folder'" @confirm="() => delDiagram(node)">
							  <el-button slot="reference" type="text" size="mini" icon="el-icon-remove">删除</el-button>
							</el-popconfirm>
						</span>
					</span>
				</el-tree>
			</div>
		  </el-col>
		  
		  <!-- 编辑区 -->
		  <el-col :span="18" style="border-left: 1px solid #f4f4f4">
			<!-- 工具条 -->
			<div ref="header" style="padding: 2px;border-bottom: 1px solid #f4f4f4">
				<span class="editor-title">{{currentDiagram.name}}</span>
				
				<el-button-group>
					<el-button size="mini" @click="() => prjEnv()">项目环境</el-button>
				</el-button-group>
				
				<el-button-group>
					<el-button size="mini" @click="() => chooseTemplate()" :disabled="state == -1">选择模板</el-button>
					<el-button size="mini" @click="() => loadData()" :disabled="state == -1">加载数据</el-button>
					&nbsp;
					<el-button size="mini" @click="() => reset()" :disabled="state == -1">重置</el-button>
				</el-button-group>
				
				<el-button-group>
					<el-button size="mini" @click="() => {}" :disabled="state != 1">上移/左移</el-button>
					<el-button size="mini" @click="() => {}" :disabled="state != 1">下移/右移</el-button>
				</el-button-group>
				
				&nbsp;
				<el-button-group>
					<el-button size="mini" @click="() => changeConState()" :disabled="state == -1">{{conButtonText}}</el-button>
				</el-button-group>
				
				&nbsp;
				<el-button-group>
					<el-button size="mini" @click="() => save()" :disabled="state == -1">保存</el-button>
				</el-button-group>
				
				<!--选中信息-->
				<div class="info">
					<span>{{selectionInfo}}</span>
					<span style="margin-left: 30px;color: #a3a3a3;">{{dynInfo}}</span>
				</div>
			</div>
			
			 <!-- 编辑界面 -->
			<div ref="editor" :style="editorStyle">
				
			</div>
		  </el-col>
		</el-row>

		<!-- 编辑项目环境对话框 -->
		<el-dialog title="项目环境" :visible.sync="dlgEnvVisible">
			<el-form :model="propsData" label-width="100px">
				<el-form-item label="项目Id">
					<el-autocomplete
					  class="inline-input"
					  v-model="propsData.projectId"
					  :fetch-suggestions="getPrjIds"></el-autocomplete>
				</el-form-item>				
				<el-form-item label="系统实例Id">
					<el-input v-model="propsData.systemId"></el-input>
				</el-form-item>
				<el-form-item label="集团编码">
					<el-input v-model="propsData.groupCode"></el-input>
				</el-form-item>
			</el-form>
			
			<div slot="footer" class="dialog-footer">
				<el-button @click="dlgEnvVisible = false">取 消</el-button>
				<el-button type="primary" @click='modifyEnv'>确 定</el-button>
			</div>
		</el-dialog>
		
		<!-- 选择模板对话框 -->
		<el-dialog title="系统图模板" :visible.sync="dlgTemplateVisible">
			<el-form :model="propsData" label-width="100px">
				<el-form-item label="选择模板">
					<el-select
					  v-model="propsData.templateId"
					  style="width: 600px;"
					  >
					  <el-option
						v-for="item in templateOptions"
						:key="item.id"
						:label="item.name"
						:value="item.id">
					  </el-option>
					</el-select>
				</el-form-item>
			</el-form>
			
			<div slot="footer" class="dialog-footer">
				<el-button @click="dlgTemplateVisible = false">取 消</el-button>
				<el-button type="primary" @click='modifyTemplate'>确 定</el-button>
			</div>
		</el-dialog>
	
	</div>
</template>

<script lang="ts">
	import {
		Component,
		Prop,
		Vue,
		Watch
	} from "vue-property-decorator";
	import {DiagramEditor} from '@/lib/DiagramEditor';
	import {Template} from '@/lib/DiagramModel';

	@Component({})
	export default class DiagramTemplate extends Vue {
		projectId = 'Pj1101080665';
		systemId = '';
		groupCode = '';
		
		editorStyle = {
			width: "100%",
			height: "",
			"overflow": "scroll"
		};
		
		diagrams = [];
		currentDiagram:any = {};
		
		editor:DiagramEditor = null;
		state = -1; //编辑状态(-1:关闭; 0:打开; 1:容器编辑中; 2:绘制干管)

		dlgEnvVisible = false;
		dlgTemplateVisible = false;
		
		propsData: any = {};
		templateOptions:any[] = [];
				
		selectionInfo = '~';
		dynInfo = '';		
		
		conButtonText = '隐藏容器';
				
		mounted() {
			this.onWindowresize();
			this.editor = new DiagramEditor(this.$refs.editor);
			this.editor.setEditorPart(this);
			
			this.loadDiagrams();
		}
		
		loadDiagrams(){
			this['$axios'].get(this['$common'].url + "diagram0/getDiagrams" + this.buildUrlParams())
				.then(res => {
					this.diagrams = res.data.data;
				})
				.catch(err => {
					//console.log(err);
				});
		}
		
		buildUrlParams(){
			var str = "?projectId=" + this.projectId;
			if(this.systemId)
				str += '&systemId=' + this.systemId;
			if(this.groupCode)
				str += '&groupCode=' + this.groupCode;
			return str;
		}
		
		//系统图模板树的节点显示
		nodeLabel(data, node) {
			if(data.objType == 'folder') //文件夹
				return data.name;
			else //图
				return '[系统图] ' + data.name;
		}

		prjEnv() {
			this.propsData = {projectId: this.projectId, systemId: this.systemId, groupCode: this.groupCode};
			this.dlgEnvVisible = true;
		}
		
		getPrjIds(queryString, cb){
			const list = [
				{ "value": "Pj1101080665", "code": "JDKJ" },
				{ "value": "Pj1101050036", "code": "JM" },
				{ "value": "Pj1101050031", "code": "YT" }
			];
			cb(list);
		}
		
		modifyEnv() {
			const reload = this.projectId != this.propsData.projectId;
			
			this.projectId = this.propsData.projectId;
			this.systemId = this.propsData.systemId;
			this.groupCode = this.propsData.groupCode;
			this.dlgEnvVisible = false;
			
			if(reload) {
				this.loadDiagrams();	
				this.open(new Object());
			}
		}
				
		//新建模板文件
		newDiagram(node){
			this.$prompt('请输入系统图名称', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'info',
						inputValidator: val => {return val != null}
			       }).then(instance => {
						const params:any = {name: instance['value'], type: node.data.id};
						this['$axios'].post(this['$common'].url + "diagram0/newDiagram" + this.buildUrlParams(), params)
							.then(res => {
								const root = res.data;
								if(root.result == 'success') {
									const newObj = root.data;
									node.data.children.push(newObj);
									
									this.$message({
										type: 'success',
										message: '操作成功!'
									});
									
									this.open(newObj);
								}
							})
							.catch(err => {
								console.log(err);
							});	
			       }).catch(() => {
								
			       });
		}
		
		//删除模板
		delDiagram(node){
			const params:any = {id: node.data.id};
			this['$axios'].post(this['$common'].url + "diagram0/delDiagram", params)
				.then(res => {
					const root = res.data;
					if(root.data == true) {
						const parent = node.parent;
						const children = parent.data.children || parent.data;
						const index = children.findIndex(d => d.id === node.data.id);
						children.splice(index, 1);
						
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
						this.open({});
					}
				})
				.catch(err => {
					console.log(err);
				});	
		}
		
		//在编辑器中打开模板文件
		open(data){
			if(data.objType == 'folder') //文件夹
				return;
				
			if(this.currentDiagram != data) {
				this.currentDiagram = data;
				this.selectionInfo = '~';
				this.dynInfo = '';
				
				this.editor.show(this.currentDiagram);
				
				if(!this.currentDiagram.id) //编辑对象为空
					this.state = -1;
				else {
					this.onSelectionChange();
				}
			}
		}

		chooseTemplate() {
			this.templateOptions = [];
			this['$axios'].get(this['$common'].url + "template/getTemplatesByType?diagramType=" + this.currentDiagram.type)
				.then(res => {
					this.templateOptions = res.data.data;
				})
				.catch(err => {
					//console.log(err);
				});
			
			const props:any = new Object();
			props.templateId = this.currentDiagram.templateId;
			
			this.propsData = props;
			
			this.dlgTemplateVisible = true;
		}
		
		modifyTemplate() {
			const tId = this.propsData.templateId;
			this.currentDiagram.templateId = tId;

			this.dlgTemplateVisible = false;
			this.editor.redraw();
			
			const params:any = {diagramId: this.currentDiagram.id, templateId: this.propsData.templateId};
			//this.propsData = {id: params.newCompId}; //方便后续选中操作
			this.callAction('setTemplate', params);
		}
		
		loadData() {
			const params:any = {diagramId: this.currentDiagram.id};
			//this.propsData = {id: params.newCompId}; //方便后续选中操作
			this.callAction('loadData', params);
		}
		
		created(){
			//window.addEventListener('resize', this.onWindowresize);
		}
		
		onWindowresize(){
			this.editorStyle.height = (window.innerHeight - this.$refs.header['offsetHeight']) + 'px';
		}
		
		//选中组件的事件触发
		onSelectionChange(){
			this.state = this.editor.getState();
			
			if(this.editor)
				this.selectionInfo = this.editor.buildSelInfo();
		}
		
		//调用服务端编辑操作，返回新的系统图对象，然后刷新
		callAction(action, params) {
			this['$axios'].post(this['$common'].url + 'diagram0/' + action, params)
				.then(res => {
					const root = res.data;
					if(root.result == 'success') {
						//记录之前的选中对象id
						// var selId = this.propsData.id;
						// if(!selId) {
						// 	const sel:any = this.editor.getSelComp();	
						// 	if(sel)
						// 		selId = sel.id;
						// }
						
						const newObj = root.data;
						if(newObj == null)
							return;
						
						for(const i in newObj) {
							this.currentDiagram[i] = newObj[i];
						}
						
						// this.$message({
						// 	type: 'success',
						// 	message: '操作成功!'
						// });
						
						if(this.dlgTemplateVisible)
							this.dlgTemplateVisible = false;

						this.propsData = {};
						
						this.editor.show(this.currentDiagram);
						//this.editor.setSelComp(this.editor.getCompById(selId));
					}
				})
				.catch(err => {
					console.log(err);
				});	
		}

		changeConState(){
			this.editor.showContainer = !this.editor.showContainer;
			this.editor.redraw();
			this.conButtonText = this.editor.showContainer ? '隐藏容器' : '显示容器';
		} 

		save(){
			Template.clearParent(this.currentDiagram.template);
			const params:any = {diagram: this.currentDiagram};
			this.callAction("saveDiagram", params);
		}
		
		reset(){
			const params:any = {diagramId: this.currentDiagram.id};
			this.callAction("resetDiagram", params);
		}

		//切换编辑状态
		changeState(state) {
			this.state = state;
			this.editor.setState(state);
		}
		
	}
</script>

<style>
	.panel {
		padding: 30px;
	}
	.custom-tree-node {
		/* 	flex: 1;
		display: flex; */
		align-items: center;
		justify-content: space-between;
		font-size: 14px;
		padding-right: 20px;
	}
	.editor-title {
		font-size: 14px;
		font-weight: bold;
		padding:0 10px;
	}
	.info {
		font-size: 12px;
		padding:0 10px;
	}
	.el-dialog-div{
		height: 60vh;
		overflow: auto;
	}
</style>
