(function () {
	CKEDITOR.dialog.add("linkeddoc", function (editor) {
		return {
			title: "Linked Doc",
			minWidth: 400,
			minHeight: 200,
			contents: [
				{
					id: "Linked Doc",
					label: "연결할 문서 선택",
					elements: [
						{
							type: "hbox",
							widths: ["30%", "70%"],
							children: [
								{
									type: "select",
									id: "Doc Selector",
									label: "연결할 문서 선택",
									items: [["로딩 중..."]],
									onChange: function () {
										var wikiId = "WIKI_" + $("#selected_pdService").val() + "_" + this.getValue();

										var dialog = this.getDialog();
										var $preview = $(dialog.getContentElement("Linked Doc", "Doc Preview").getElement().$).find(
											".ckeditor_preview"
										);

										$.ajax({
											type: "GET",
											url: "/auth-user/api/arms/wiki/" + wikiId + "/getWiki.do",
											contentType: "application/json;charset=UTF-8",
											dataType: "json",
											success: function (data) {
												console.log(data);

												$preview.empty().append(data.contents);
											}
										});
									}
								},
								{
									type: "html",
									id: "Doc Preview",
									html:
										"<div>미리보기" +
										"<div class='ckeditor_preview' style='height: 250px; border: 2px solid #d1d1d1; padding: 10px 20px'></div>" +
										"</div>"
								}
							]
						}
					]
				}
			],
			onShow: function () {
				var dialog = this;
				var $select = $(dialog.getContentElement("Linked Doc", "Doc Selector").getInputElement().$);

				$.ajax({
					url: "/auth-user/api/arms/wiki/T_ARMS_WIKI_" + $("#selected_pdService").val() + "/getNodesWithoutRoot.do",
					dataType: "json",
					type: "GET",
					success: function (data) {
						$select.empty();

						data.result.forEach(function (item) {
							if (item.c_type !== "default") return;

							$select.append($("<option />").val(item.c_id).text(item.c_title));
						});
					}
				});
			},
			onOk: function () {
				var dialog = this;
				var $preview = $(dialog.getContentElement("Linked Doc", "Doc Preview").getElement().$)
					.find(".ckeditor_preview")
					.children()
					.first();
				var $selectedOption = $(dialog.getContentElement("Linked Doc", "Doc Selector").getInputElement().$).find(
					"option:selected"
				);

				var widget = this.widget;
				var data = widget.data({
					url:
						"/arms/template.html?page=adms&pdServiceId=" +
						$("#selected_pdService").val() +
						"&wikiId=" +
						$selectedOption.val(),
					title: $selectedOption.text(),
					desc: $preview.text() || ""
				});

				editor.insertElement(data);
			},
			onHide: function () {
				var dialog = this;
				var $select = $(dialog.getContentElement("Linked Doc", "Doc Selector").getInputElement().$);
				var $preview = $(dialog.getContentElement("Linked Doc", "Doc Preview").getElement().$).find(
					".ckeditor_preview"
				);

				$select.empty();
				$preview.empty();
			}
		};
	});
})();
