/**
 * 配置流程说明
 * 2018/4/20 by liufang
 */
$(function () {
	var contextPath =  $("#contextPath").val()
	var orgId = $('#orgId').attr('org__id');
	var layer;
	var contentA = '',
		contentB = ''
	layui.use('layer', function () {
		layer = layui.layer;
	});
	var appPublish = {
		init: function () {
			this.render();
			this.bindEvent();
		},
		render: function () {
			var _this = this;
			var editor = new UE.ui.Editor({
				imageActionName: 'ueAction',
				imageFieldName: "uploadfile",
				fileActionName: "ueAction",
				fileFieldName: "uploadfile",
				fileAllowFiles: [
					".png", ".jpg", ".jpeg", ".gif", ".bmp",
					".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
					".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
					".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
					".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
				],
				imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
				/* 上传图片格式显示 */
				imageUrlPrefix: $("#contextPath").val() //$("#contextPath").val()
			});
			editor.render("myeditorA");
			editor.ready(function () {
				editor.setHeight(450);
				//					editor.addListener("afterUpfile",_this._afterUpfile);	
			});
			var editorb = new UE.ui.Editor({
				imageActionName: 'ueAction',
				imageFieldName: "uploadfile",
				fileActionName: "ueAction",
				fileFieldName: "uploadfile",
				fileAllowFiles: [
					".png", ".jpg", ".jpeg", ".gif", ".bmp",
					".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
					".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
					".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
					".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
				],
				imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
				/* 上传图片格式显示 */
				imageUrlPrefix: $("#contextPath").val() //$("#contextPath").val()
			});
			editorb.render("myeditorB");
			editorb.ready(function () {
				editorb.setHeight(450);
				//					editor.addListener("afterUpfile",_this._afterUpfile);	
			});
			UE.getEditor('myeditorB').addListener("ready", function () {
				
			});
			UE.getEditor('myeditorA').addListener("ready", function () {
				_this.ajaxSettingInfor();
			});
			// _this.ajaxSettingInfor();

			// 文件列表

			_this.get_file_list();
			// 文件上传
			layui.use('upload', function () {
				var $ = layui.jquery,
					upload = layui.upload;
				var demoListView = $('#demoList'),
					uploadListIns = upload.render({
						elem: '#testList',
						url: $("#contextPath").val() + '/admin/enter/uploadFile',
						data: {
							type: '15',
							'orgId': orgId
						},
						accept: 'file',
						multiple: true,
						auto: false,
						bindAction: '#testListAction',
						choose: function (obj) {
							var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
							//读取本地文件
							obj.preview(function (index, file, result) {
								var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name + '</td>', '<td>等待上传</td>', '<td>', '<button class=" layui-btn-xs demo-reload layui-hide">重传</button>', '<button class=" layui-btn-xs layui-btn-danger demo-delete">删除</button>', '</td>', '</tr>'].join(''));

								// 单个重传
								tr.find('.demo-reload').on('click', function () {
									obj.upload(index, file);
								});

								//删除
								tr.find('.demo-delete').on('click', function () {
									delete files[index]; //删除对应的文件
									tr.remove();
									uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
								});
								demoListView.append(tr);
							});
						},
						done: function (res, index, upload) {
							// console.log(res, 111);
							if (res.code == "200") { //上传成功
								// $("#demoList").html(' ');
								var tr = demoListView.find('tr#upload-' + index),
									tds = tr.children();
								tds.eq(1).html('<span style="color: #5FB878;">已上传</span>');
								delete this.files[index];
								if(JSON.stringify(this.files) == "{}"){
									_this.get_file_list();
								}
								// tds.eq(2).html(''); //清空操作
								// if(	_this.delete_success_file(id)){
								// return delete this.files[index]; //删除文件队列已经上传成功的文件
								// }
							}
							this.error(index, upload);
						},
						error: function (index, upload) {
							var tr = demoListView.find('tr#upload-' + index),
								tds = tr.children();
							tds.eq(1).html('<span style="color: #FF5722;">上传失败</span>');
							tds.eq(2).find('.demo-reload').removeClass('layui-hide'); //显示重传
						}
					});

			})


		},
		bindEvent: function () {
			var _this = this;
			//切换三级菜单
			$(".third-tab").each(function (index, ele) {
				$(ele).on("click", function () {
					var name = $(this).data("name");
					$(".third-bread").html(name);
					$(ele).addClass("active").siblings().removeClass("active");
					$(".third-con").eq(index).show().siblings().hide();
				})
			})
			//确认修改
			$(".submit-btn").on("click", function () {
				var type = $(this).data("type")
				_this.ajaxSubmit(type);
			});
			//取消修改
			$(".cancel-btn").on("click", function () {
				var type = $(this).data("type");
				if (type == 1) {
					UE.getEditor('myeditorA').setContent(contentA);
					//						 UE.getEditor('myeditorA').addListener("ready", function () {
					//								// editor准备好之后才可以使用
					//								   UE.getEditor('myeditorA').setContent(contentA);
					//								});
				} else if (type == 2) {
					UE.getEditor('myeditorB').setContent(contentB);
					//						 UE.getEditor('myeditorB').addListener("ready", function () {
					//								// editor准备好之后才可以使用
					//								   UE.getEditor('myeditorB').setContent(contentB);
					//								});
				}
			})
		},
		// 模糊搜索事件
		search_fuzzy: function(){
			var _this = this
			var default_option = {
				org_attrName:'org__id',
				com_attrName:'com__id',
				dep_attrName:'dep__id',
				org_spanName:'org__span',
				com_spanName:'com__span',
				dep_spanName:'dep__span',
				org_path:'/admin/templ/getOrgListByName',
				com_path:'/admin/templ/getVirList',
				dep_path:'/admin/templ/getDept',
				contextPath:$("#contextPath").val()
			}
			var option_1 = $.extend(true,{},default_option,{
				org_target:'#orgId'
			});
				
			
			function eve(option_,otherOption){
				var obj = $.extend(true, {}, option_, otherOption);
				// console.log(obj,999)
				var type = obj.type
				var _path, _target, _attrName, _spanName
				if(type == 1){
					_path = obj.org_path
					_target = obj.org_target
					_attrName = obj.org_attrName
					_spanName = obj.org_spanName
				}else if(type == 2){
					_path = obj.com_path
					_target = obj.com_target
					_attrName = obj.com_attrName
					_spanName = obj.com_spanName
				}else if(type == 3){
					_path = obj.dep_path
					_target = obj.dep_target
					_attrName = obj.dep_attrName
					_spanName = obj.dep_spanName
				}
				$('body').on("input",_target,function(event){
					var _this = $(this)
					var obj_input = $.extend(true,{}, obj,{"_this":_this});
					cjqt.search_fuzzy.event_input(_this,_attrName,_spanName,contextPath,_path,obj_input)
				});
				$('body').on("focus",_target,function(event){
					var _this = $(this)
					var obj_focus = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_focus(_this,_attrName,_spanName,contextPath,_path,obj_focus)
				});
				$('body').on('blur',_target,function(event) {
					var _this = $(this)
					var obj_blur = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_blur(_this,_attrName,obj_blur)
				});
				$('body').on('click',_target+'~.select_wrap>.'+_spanName, function(event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _this = $(this)
					var obj_click = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_click(_this,_attrName,_target,obj_click)
				});
			}
			// 搜索绑定
			eve(option_1,{
				type:1,
				blur_callback:function(){
					console.log("失去焦点")
					orgId = $('.default-select#orgId').attr('org__id')
					$("#myeditorA").html('');
					$("#myeditorB").html('');
					$("#demoList").html('');
					appPublish.init();
				},
				click_callback:function(){
					console.log("切换校区")
					orgId = $('.default-select#orgId').attr('org__id')
					$("#myeditorA").html('');
					$("#myeditorB").html('');
					$("#demoList").html('');
					appPublish.init();
				}
			})
		},
		/**
		 * 获取模板配置接口
		 * 
		 */
		ajaxSettingInfor: function () {
			var _this = this;
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/enter/getVirModel",
				data: {
					"type": 0,
					'orgId': orgId
				},
				success: function (data) {
					//						   var data = JSON.parse(data);
					if (data.code == '200') {
						if (data.data.length > 0) {
							var list = data.data;
							for (var i = 0; i < list.length; i++) {
								if (list[i].type == 11) {
									$("#myeditorA").data("id", list[i].id);
									contentA = list[i].content
									UE.getEditor('myeditorA').setContent(contentA);
									// UE.getEditor('myeditorA').addListener("ready", function () {
									// 	// editor准备好之后才可以使用
									// 	UE.getEditor('myeditorA').setContent(contentA);
									// });
									//										   ue.setContent(list[i].content) ;
									//										   contentA = list[i].content
								} else if (list[i].type == 12) {

									$("#myeditorB").data("id", list[i].id);
									var ue = UE.getEditor('myeditorB');
									contentB = list[i].content
									UE.getEditor('myeditorB').setContent(contentB);
									// UE.getEditor('myeditorB').addListener("ready", function () {
									// 	// editor准备好之后才可以使用
									// 	UE.getEditor('myeditorB').setContent(contentB);
									// });

								}
							}
						}

					}
				},
				error: function () {}
			});
		},
		/**
		 * 提交发送
		 * @param type
		 */
		ajaxSubmit: function (type) {
			var ue, content, id;
			if (type == 11) {
				id = $("#myeditorA").data("id");
				ue = UE.getEditor('myeditorA');
				content = ue.getContent(); //发件主题
			} else if (type = 12) {
				id = $("#myeditorB").data("id");
				ue = UE.getEditor('myeditorB');
				content = ue.getContent(); //发件主题
			}
			if (!content) {
				layer.alert('请输入内容');
				return false;
			}
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/enter/saveVirModel",
				data: {
					"type": type,
					"content": content,
					"id": id,
					'orgId': orgId

				},
				success: function (data) {
					//						   var data = JSON.parse(data);
					if (data.code == '200') {
						//							   ue.setContent('') ;
						if (type == 11) {
							contentA = content;
							$("#myeditorA").data("id", data.data.id)
						} else {
							contentB = content;
							$("#myeditorB").data("id", data.data.id);
						}
						layer.msg('修改成功！');
					}
				},
				error: function () {}
			});
		},
		/**
		 * 获取已上传的文件列表
		 * 
		 */
		get_file_list: function () {
			$("#demoList").html('');
			var orderIn = "";
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/enter/getFileList",
				data: {
					"type": '15',
					'orgId': orgId
				},
				success: function (data) {
					console.log(data, 666);
					if (data.code == "200") {
						let fileList = data.data;
						$.each(fileList, function (index, value) {
							var trs = "";
							trs += "<tr id=''><td>" + value.fileName + "</td><td>已上传</td><td><button class=' layui-btn-xs layui-btn-danger demo-delete deleteBtn' onclick='editPosition(" + value.id + ");'>删除</button></td></tr>";
							orderIn += trs;
						});
						$("#demoList").append(orderIn);
					}
				},
				error: function () {
					return false
				}
			});
		},

	};
	editPosition = function (id) {
		$.ajax({
			type: "post",
			url: $("#contextPath").val() + "/admin/enter/deleteFile",
			data: {
				"id": id,
				'orgId': orgId
			},
			success: function (data) {
				// console.log(data, 555);
				if (data.code == '200') {
					appPublish.get_file_list();
				}
			},
			error: function () {

			}
		});
	}
	appPublish.init();
	appPublish.search_fuzzy();
})