function UrlEditCtrl($scope, Project, Url, TemplateUrlRoute) {
	$scope.current_template = null;
	$scope.current_page = {};
	$scope.current_fide = {};
	$scope.current_model = {};
	$scope.pages = [];

	function getUrlItem(back) {
		Url.getItem({ _id: $scope.current_url._id }, function (res) {
			if (typeof back == "function") {
				back(res);
			}
		});
	}
	function getCurrentUrlFlg() {
		Url.getRelaceFlg({ _id: $scope.current_url._id }, function (res) {
			$scope.current_url.relace_flg = res.relace_flg;
			$scope.current_url.relace_version = res.relace_version;
			$scope.current_url.last_version = res.last_version;
		})
	}
	let template_fun_str = `async function(){
	return ""
}`

	function resizeAce(item) {
		if (item != undefined) {
			var Parent = $(`#${item.id}`).parent();
			$(`#${item.id}`).height($(Parent).height());
			if (item.editor.resize != undefined) {
				//需要先显示对象，再resize.
				return item.editor.resize();
			}
		}
	};

	let fide_id = 0;
	var fide = function () {
		this.title = "";
		this.isDir = false;
		this.isOpen = false;
		this.resource = false;
		this.deep = 0;
		this.children = [];
		this.parent = null;
		this.data = null;
		this.page = null;
		this.id = fide_id++;
		return this
	}
	fide.prototype = {
		init: function (source, parent, title, isDir, deep, data) {
			this.resource = source;
			this.title = title;
			this.isDir = isDir;
			this.deep = deep;
			this.parent = parent;
			this.data = data;
			return this
		},
		delete: function () {
			var _this = this;
			TemplateUrlRoute.delete({
				_id: this.data._id
			}, function (res) {
				_.remove(_this.parent.children, { id: _this.id })
				_this.page.closePage();
				getCurrentUrlFlg();
				$("#deleteAlert").modal("hide");
			});
		},
		deleteCancel: function () {
			$("#deleteAlert").modal("hide");
		},
		judgeDelete: function () {
			if (!this.isDir && this.id != main_file.id) {
				$scope.current_model = this;
				$("#deleteAlert").modal("show");
			} else {
				alert("该文档禁止删除");
			}
		},
		reName: function () {
			var _this = this;
			modalShow("请输入需要修改的名称", "", function () {
				if (reg.test($scope.modal.value)) {
					toastr.warning("请不要输入中文")
				} else {
					TemplateUrlRoute.update({
						_id: _this.data._id,
						key: $scope.modal.value
					}, function (res) {
						_this.title = $scope.modal.value;
						$scope.modal.value = "";
						getCurrentUrlFlg();
						$('#myModal').modal("hide");
					}, function (res) {
						toastr.danger("创建失败")
					})
				}
			});
		},
		close: function () {
			this.isOpen = false;
			this.children.length = 0;
			return this
		},
		open: function () {
			this.isOpen = true;
			return this
		},
		setPage: function (page) {
			// $scope.pages.push(page);
			this.page = page;
		},
		showPage: function () {
			if (this.page != null) {
				$scope.current_page = this.page;
				$scope.current_fide = this;
				let inx = _.find($scope.pages, { id: this.page.id })
				if (inx == undefined) {
					$scope.pages.push(this.page);
				}
			}
		}
	}
	var page_index = 0;
	var page = function () {
		this.title = "";
		this.tree_fide = null;
		this.is_change = false;
		this.id = "ed_" + page_index++;
		this.editor = null;
	}
	page.prototype = {
		init: function (title, fide) {
			this.title = title;
			if (fide != undefined) {
				this.tree_fide = fide;
			}
		},
		showPage: function () {
			this.tree_fide.showPage();
		},
		closePage: function () {
			if ($scope.current_page.id == this.id) {
				$scope.pages[0].showPage();
			}
			this.is_change = false;
			_.remove($scope.pages, { id: this.id });
			$("#warningAlert").modal("hide");
		},
		judgePageIsChange: function () {
			if (this.tree_fide.data.fun != this.editor.getValue()) {
				$scope.current_model = this;
				$("#warningAlert").modal("show");
			} else {
				this.closePage();
			}
		},
		cancelClosePage: function () {
			$("#warningAlert").modal("hide");
		},
		saveValue: function (call_back) {
			if (this.editor != null) {
				let _this = this;
				this.tree_fide.data.fun = this.editor.getValue();
				if (this.is_change == true) {
					this.tree_fide.resource.update({
						_id: this.tree_fide.data._id,
						fun: this.tree_fide.data.fun
					}, function (res) {
						_this.tree_fide.data.relace_flg = res.relace_flg;
						_this.tree_fide.data.relace_version = res.relace_version;
						_this.tree_fide.data.last_version = res.last_version;
						_this.is_change = false;
						if (typeof call_back == "function") {
							call_back.call(_this);
						}
					})
				}
			}
		}
	}

	// var editor = {};
	var dblclick = 0;
	$scope.modal = {
		title: "",
		value: ""
	}
	$scope.element = {
		menus: {
			display: false,
			size: {
				left: 0,
				top: 0
			}
		}
	}

	function quickKey(e) {
		var ctrlKey = false;
		if (e.ctrlKey || e.metaKey) {
			ctrlKey = true
		}
		if (ctrlKey && e.keyCode == 83) {
			if (e.data.fun && typeof e.data.fun == "function") {
				e.data.fun(e);
			}
			return false; // 截取返回false就不会保存网页了
		}
	}

	// var js_mode = ace.require("ace/mode/javascript_worker").Mode

	$scope.finishenOn = function (item) {
		item.editor = ace.edit(item.id);
		item.editor.getSession().setMode("ace/mode/javascript");
		item.editor.setTheme("ace/theme/twilight");
		item.editor.setValue(item.tree_fide.data.fun);
		item.editor.gotoLine(1, 0, true);
		item.editor.on("change", function () {
			if (item.is_change == false) {
				$scope.$apply(function () {
					item.is_change = true;
				})
			}
		});

		resizeAce(item);
	}
	$(window).resize(resizeAce);
	$(window).unbind("keydown");
	$(window).bind("keydown", {
		fun: function () {
			//保存数据
			$scope.current_page.saveValue();
			// $scope.$broadcast("saveScript");
		}
	}, quickKey);
	$scope.$on("$destroy", function () {
		$(window).unbind("keydown", quickKey);
	});

	function getFideChild(_fide) {
		//打开一个TAP，
		//显示FUN的内容，
		if (_fide.parent == null) {
			_fide.children = [main_file, template_file]
			return
		}
		Url.findUrlTemplatesById({
			_id: $scope.current_url._id
		}, function (res) {
			res.templates.forEach(function (template) {
				let temp = new fide().init(TemplateUrlRoute, template_file, template.key, false, template_file.deep + 1, template)
				let temp_page = new page()
				temp_page.init(template.key, temp);
				temp.setPage(temp_page);
				template_file.children.push(temp);
			}, this);
		})
	}
	function setEditorValue(_fide) {
		//获取数据并保存
		if (_fide.data != null) {
			editor.setValue(_fide.data.fun)
		}
	}

	function hiddenMenus() {
		$scope.$apply(function () {
			$scope.element.menus.display = false;
		})
	}

	$scope.rightTargetClick = function (event, fide) {
		$scope.element.menus.size.top = event.pageY + 5;
		$scope.element.menus.size.left = event.pageX + 20;
		$scope.element.menus.display = true;
		$scope.current_fide = fide;
		$scope.current_template = fide;
		$(window).one("click", hiddenMenus);
	}

	function clickPageHeader(page) {

	}

	function clickTreeFide(fide) {
		$scope.current_fide = fide;
		// fide对应的page
		clickPageHeader()
		// $scope.pages
	}

	$scope.targetClick = function (fide) {
		$scope.current_fide = fide;
		if (fide.isOpen) {
			if (fide.isDir) {
				fide.close();
			} else {
				getFideChild(fide)
			}
		} else {
			if (fide.isDir) {
				//获取Function，templates
				getFideChild(fide);
				$scope.current_fide.open();
			} else {
				dblclick++;
				if (dblclick == 1) {
					//
					fide.showPage();
					// setEditorValue(fide)
					timer = setTimeout(function () {
						dblclick = 0;
					}, 200);
				} else {
					// openPage();
					clearTimeout(timer);
					dblclick = 0;
				}
			}
		}
	}


	function openPage(fide) {
		// $scope.pages.push({
		// 	isEdit: false,
		// 	fide: fide,
		// 	value: ""
		// });
	}


	let root_file, main_file, template_file
	let temp_page = new page();
	getUrlItem(function (res) {
		//初始化树
		$scope.current_url = res;
		root_file = new fide().init(null, null, "MOCK_URL", true, 1, null);
		main_file = new fide().init(Url, root_file, "main", false, root_file.deep + 1, $scope.current_url);
		template_file = new fide().init(null, root_file, "response模板", true, root_file.deep + 1, null);
		temp_page.init("main", main_file);
		main_file.setPage(temp_page);
		main_file.showPage();
		root_file.children = [main_file, template_file]
		root_file.open();
		$scope.treeNode = [root_file];
	});





	$scope.modalRender = function () {
		$('#myModal').on('shown.bs.modal', function () {
			$('#modalInput').focus();
		});
		$('#myModal').on('hide.bs.modal', function () {
			$('#modalInput').unbind("keydown", modalInputCallBack);
		});
	}

	function modalInputCallBack(event) {
		if (event.keyCode == 13) {
			//确认键
			event.data.do.call();
		} else if (event.keyCode == 27) {
			//ESC 按键
			$('#myModal').modal('hide');
		}
	}
	function modalShow(title, model, callback) {

		$scope.modal.title = title;
		$scope.modal.value = model;
		$('#myModal').modal('show');
		$('#modalInput').unbind("keydown");
		$('#modalInput').bind("keydown", { do: callback }, modalInputCallBack);
	}
	var reg = /^[\u4E00-\u9FA5]+$/;
	$scope.createNewTemplate = function () {
		modalShow("请输入新模板的Key(全英文，不要输入中文)", "", function () {
			if (reg.test($scope.modal.value)) {
				toastr.warning("请不要输入中文")
			} else {
				TemplateUrlRoute.save({
					key: $scope.modal.value,
					fun: template_fun_str,
					is_default: 0,
					url: $scope.current_url._id,
					devices: []
				}, function (res) {
					//tree,template_file中插入一个child
					let temp = new fide().init(TemplateUrlRoute, template_file, res.key, false, template_file.deep + 1, res);
					template_file.children.push(temp);
					let temp_page = new page()
					temp_page.init(temp.title, temp);
					temp.setPage(temp_page);
					$scope.modal.value = "";
					getCurrentUrlFlg();
					$('#myModal').modal("hide");
				}, function (res) {
					toastr.danger("创建失败")
				})

			}
		});
	}


}
UrlEditCtrl.$inject = ["$scope", "Project", "Url", "TemplateUrlRoute"];
BP.controller("UrlEditCtrl", UrlEditCtrl);