//企业新闻
$(function() {

	var orgId = $.cookie("orgId");
	var newtitle = false;
	newslist(); //科研新闻列表

	/*弹框*/
	$("body").on("click", ".modelClosebtn", function() {
		BombBoxlClose();
	})

	$(".workarea").on("click", ".addworkbtn", function() {
		newsBombBox(); //插入弹框
		addDele(); //编辑学术领域和应用行业	
		$("#inputb").on("click", function() {
			if($("#newsName").val() != "") {
				newsAdd();
			} else {
				$(".msgLog1").text("发布文章名称不能为空");
			}

		});
	});

	$(".workarea").on("click", ".addworkbtn-list", function() {
		articleId = $(this).find(".showBlock").attr("data-title");
		newsBombBox(); //插入弹框
		addDele(); //编辑学术领域和应用行业
		modifyDisplay();
		$("#inputb").on("click", function() {
			if($("#newsName").val() != "") {
				$.MsgBox.Confirm("消息", "确定修改文章信息吗？", newsModify)
			} else {
				$(".workmsg1").text("发布文章名称不能为空");
			}
		});
	});

	/*失去焦点判断*/
	$("#newsName").blur(function() {
		newsName();
	});

	//判断文章标题不能为空
	function newsName() {
		var code = $("#newsName").val();
		if(code.length == 0 || code == " ") {
			$(".msgLog1 span").text("发布文章名称不能为空");
			newtitle = false;
		} else {
			$(".msgLog1 span").text("");
			newtitle = true;
		}
	}

	/*科研新闻列表*/
	function newslist() {
		$.ajax({
			"url": "/ajax/article/qaOrg",
			"type": "get",
			"async": true,
			"data": {
				"orgId": orgId
			},
			"beforeSend": function() {
				$("#newsbox").append('<img src="../images/loading.gif" class="loading" />');
			},
			"success": function(data) {
				console.log(data);
				if(data.success) {
					var add = '';
					$("#newsbox").html("");
					var addbut = ' <div class="addworkbtn" ></div>';
					$("#newsbox").append(addbut);
					for(var i = 0; i < data.data.length; i++) {
						var add = '<div class="addworkbtn-list"><div class="showBlock" data-title="">'
						add += '<div class="showImg"></div>'
						add += '<div class="showBasic"><h6 id="artical_topic" class="showTopic">' + data.data[i].articleTitle + '</h6></div>'
						add += '</div><div class="tagsBox"><span></span></div>'
						add += '</div>';
						$add = $(add);
						$("#newsbox").append($add);
						$add.find('.showBlock').attr("data-title", data.data[i].articleId);
						$add.find('.tagsBox span').text(data.data[i].industry);
						if(data.data[i].articleImg) {
							$add.find(".showImg").attr("style", "background-image: url(/data/article/" + data.data[i].articleImg + ");background-size:cover;");
						}
						$(".loading").remove();
					}

				} else {
					$.MsgBox.Alert('消息', '链接服务器超时')
				}
			},
			"error": function() {
				$.MsgBox.Alert('消息', '链接服务器超时')
			}
		});
	}

	/*科研新闻添加*/
	function newsAdd() {
		var $data = {};
		$data.orgId = orgId;
		$data.articleTitle = $("#newsName").val();
		$data.subject = captiureSubInd("SubjectList .deleteSubject");
		$data.industry = captiureSubInd("industryList .deleteIndustry");
		$data.articleContent = ue.getContent();
		if(cacheImageKey) {
			$data.articleImg = cacheImageKey;
		}
		$.ajax({
			"url": "/ajax/article",
			"type": "post",
			"dataType": "json",
			"data": $data,
			"success": function(data) {
				console.log(data);
				if(data.success) {
					newsname = data.data;
					console.log(newsname);
					$.MsgBox.Alert("消息", "文章发表成功！");
					newslist();
					UE.delEditor('editor');
					BombBoxlClose();
				} else {
					$.MsgBox.Alert("消息", "文章发表失败！");
				}
			},
			"error": function() {
				$.MsgBox.Alert('消息', '链接服务器超时')
			}
		});
	}

	/*科研新闻修改回显内容*/
	function modifyDisplay() {
		$.ajax({
			"url": "/ajax/article/query",
			"type": "GET",
			"dataType": "json",
			"data": {
				"articleId": articleId
			},
			"success": function($data) {
				console.log($data);
				if($data.success) {
					$("#newsName").val($data.data.articleTitle);
					industryShow($data.data.subject, "SubjectList", "deleteSubject");
					industryShow($data.data.industry, "industryList", "deleteIndustry");
					ue.ready(function() {
						if($data.data.articleContent == undefined) {
							var datadescp = "";
						} else {
							var datadescp = $data.data.articleContent;
						}
						ue.setContent(datadescp);
					});
					if($data.data.articleImg) {
						$("#imghos").attr("src", "/data/article/" + $data.data.articleImg);
					}

				}
			},
			"error": function() {
				$.MsgBox.Alert('消息', '链接服务器超时')
			}
		})

		$("#deletedResource").show();
		//$.MsgBox.Confirm("消息", "确定修改文章信息吗？", newsAdd())
		$("#deletedResource").on("click", function() {
			$.MsgBox.Confirm("消息", "执行删除后文章信息将无法恢复，确定继续吗？", newsDelet)
		});
	}

	/*科研新闻修改*/
	function newsModify() {
		var $data = {};
		$data.articleId = articleId;
		$data.articleTitle = $("#newsName").val();
		$data.subject = captiureSubInd("SubjectList .deleteSubject");
		$data.industry = captiureSubInd("industryList .deleteIndustry");
		$data.articleContent = ue.getContent();
		if(cacheImageKey) {
			$data.articleImg = cacheImageKey;
		}
		console.log($data);
		$.ajax({
			"url": "/ajax/article/updateArt",
			"type": "POST",
			"dataType": "json",
			"data": $data,
			"success": function($data) {
				console.log($data);
				if($data.success) {
					newslist();
					BombBoxlClose();
					UE.delEditor('editor');
				}
			},
			"error": function() {
				$.MsgBox.Alert('消息', '链接服务器超时')
			}
		})

		$("#deletedResource").show();
		//$.MsgBox.Confirm("消息", "确定修改文章信息吗？", newsAdd())
		$("#deletedResource").on("click", function() {
			$.MsgBox.Confirm("消息", "执行删除后文章信息将无法恢复，确定继续吗？", newsDelet)
		});
	}

	/*科研新闻删除*/
	function newsDelet() {
		$.ajax({
			"url": "/ajax/article/delete",
			"type": "POST",
			"dataType": "json",
			"data": {
				"articleId": articleId
			},
			"success": function($data) {
				if($data.success) {
					BombBoxlClose();
					UE.delEditor('editor');
					newslist();
				}
			},
			"error": function() {
				$.MsgBox.Alert('消息', '链接服务器超时')
			}
		})
	}

	//组合应用行业及学术领域
	function captiureSubInd(subIndu) {
		var industrys = $("#" + subIndu + "");
		var industryAll = "";
		if(industrys.size() > 0) {
			for(var i = 0; i < industrys.size(); i++) {
				industryAll += industrys[i].innerText;
				industryAll += ',';
			};
			industryAll = industryAll.substring(0, industryAll.length - 1);
		}
		return industryAll;
	}

	//拆解应用行业及学术领域
	function industryShow(data, industryList, deleteIndustry) {
		if(data != undefined && data.length != 0) {
			var subs = new Array();
			if(data.indexOf(',')) {
				subs = data.split(',');
			} else {
				subs[0] = data;
			}
			if(subs.length > 0) {
				for(var i = 0; i < subs.length; i++) {
					$("#" + industryList + "").append("<li class='" + deleteIndustry + "'><em>" + subs[i] + "</em><img src='images/con_icon_delete.png' class='removeNu'></li>");
				};
			}
		}
	}

	/*添加或者删除应用行业及学术领域*/
	function addDele() {
		$("#industryList").on("click", ".removeNu", function() {
			$(this).parent().remove();
		});
		$("#industryAdd").click(function() {
			var val = $("#industry").val();
			if(val == "") {
				$(".workmsg4").text("请填写应用行业");
				return;
			}
			var vallist = $("#industryList .deleteIndustry em");
			for(var i = 0; i < vallist.length; i++) {
				if(vallist[i].innerText == val) {
					$(".workmsg4").text("不能添加重复内容");
					return;
				}
			}
			$("#industryList").append("<li class='deleteIndustry'><em>" + val + "</em><img src='images/con_icon_delete.png' class='removeNu'></li>")
			$("#industry").val("");
			$(".workmsg4").text("");
		});

		$("#SubjectList").on("click", ".removeNu", function() {
			$(this).parent().remove();
		});

		$("#subjectAdd").click(function() {
			var val = $("#subject").val();
			if(val == "") {
				$(".workmsg3").text("请填写学术领域");
				return;
			}
			var vallist = $("#SubjectList .deleteSubject em");
			for(var i = 0; i < vallist.length; i++) {
				if(vallist[i].innerText == val) {
					$(".workmsg3").text("不能添加重复内容");
					return;
				}
			}
			$("#SubjectList").append("<li class='deleteSubject'> <em>" + val + "</em> <img src='images/con_icon_delete.png' class='removeNu'/></li>")
			$("#subject").val("");
			$(".workmsg3").text("");
		});
	}

	/*科研文章*/
	function newsBombBox() {
		var PopHtml = "";
		PopHtml += '<div class="blackcover" style="display:block">';
		PopHtml += '<div class="modelContain" style="width: 700px;display:block">';
		PopHtml += '<form name="cmpAllFrm" class="cmpArticalFrm">';
		PopHtml += '<div class="cmpMotit">文章</div>';
		PopHtml += '<ul class="cmpAllUl cmpArticalul">';
		PopHtml += '<li><div class="col-w-3">文章标题</div><div class="col-w-9 rightRequ"><input type="text" class="frmtype frmtypeW"  id="newsName"/><em class="requiredcon">*</em><div class="frmmsg msgLog1"><span></span></div></div></li>';
		PopHtml += '<li><div class="col-w-3">涉及学术领域</div><div class="col-w-9">';
		PopHtml += '<div class="col-w-9"><input type="text" class="frmtype frmtypeW" id="subject"/><div class="frmmsg msgLog workmsg3"><span></span></div></div>';
		PopHtml += '<div class="col-w-3"><button type="button" class="frmtype btnModel btnModel2 headRadius" id="subjectAdd">添加</button></div><ul class="ulspace editUlist clearfix" id="SubjectList"></ul>';
		PopHtml += '</div></li>';
		PopHtml += '<li><div class="col-w-3">涉及应用行业</div><div class="col-w-9">';
		PopHtml += '<div class="col-w-9"><input type="text" class="frmtype frmtypeW" id="industry"/><div class="frmmsg msgLog workmsg4"><span></span></div></div>'
		PopHtml += '<div class="col-w-3"><button type="button" class="frmtype btnModel btnModel2 headRadius" id="industryAdd">添加</button></div>';
		PopHtml += '<ul class="ulspace editUlist clearfix" id="industryList"></ul></div></li>';
		/////////////文章图片上传////////////////////
		PopHtml += '<div class="uploderArt"><div class="imgBlock" id="uploader">';
		PopHtml += '<div id="fileList" class="boxBlock uploader-list headRadius"><img class="boxBlockimg headRadius" id="imghos" src="../images/default-artical.jpg" /></div>';

		PopHtml += '<div id="filePicker" class="uploadInp uploadInpArt">上传文章封面图片</div>';
		PopHtml += '</div><p class="smalltip">尺寸建议640*640，大小在5M以内，JPG、PNG格式</p></div></ul>';
		/////////////文章图片上传 结束////////////////////
		PopHtml += '<ul class="cmpAllUl cmpArticalul cmpArticalul2">';
		PopHtml += '<li><div class="col-w-2">文章正文</div>';
		PopHtml += '<div class="col-w-10"><script id="editor" name="content" type="text/plain" style="width:520px; height:200px;float: left;"></script></div></li>';
		PopHtml += '<li class="alignCenter" style="position: relative;"><button type="button" class="frmtype btnModel headRadius save-block" id="inputb">发布</button><a class="deleteFont" style="display: none;" id="deletedResource">删除文章</a></li></ul>';
		PopHtml += '</form><span class="modelClosebtn"></span></div></div>';
		//必须先将html添加到body，再设置Css样式
		$("body").prepend(PopHtml);
		$("body").css("position", "fixed");
		ue = UE.getEditor('editor', {});
		// 初始化Web Uploader
		var uploader = WebUploader.create({
			// 选完文件后，是否自动上传。
			auto: true,
			// 添加的文件数量
			//fileNumLimit: 1,
			// swf文件路径
			swf: '../js/webuploader/Uploader.swf',
			// 文件接收服务端。
			server: '../ajax/cachedFileUpload',
			// 选择文件的按钮。可选。
			// 内部根据当前运行是创建，可能是input元素，也可能是flash.

			pick: {
				id: "#filePicker",
				multiple: false
			},
			// 只允许选择图片文件。
			accept: {
				title: 'Images',
				extensions: 'gif,jpg,jpeg,bmp,png',
				mimeTypes: 'image/*'
			}

		});

		// 当有文件添加进来的时候
		uploader.on('fileQueued', function(file) {
			var $li = $(
				'<img class="boxBlockimg headRadius" style="display: inline;" id="' + file.id + '" >'
			)

			// $list为容器jQuery实例
			var $list = $('#fileList');
			$list.empty("");
			$list.append($li);

			// 创建缩略图
			// 如果为非图片文件，可以不用调用此方法。
			// thumbnailWidth x thumbnailHeight 为 100 x 100
			uploader.makeThumb(file, function(error, src) {
				if(error) {
					$li.replaceWith('<span>不能预览</span>');
					return;
				}
				$li.attr('src', src);
			}, 1, 1);

		});

		// 文件上传成功，给item添加成功class, 用样式标记上传成功。
		cacheImageKey = null;
		uploader.on('uploadSuccess', function(file, data) {
			cacheImageKey = data.data[0].cacheKey;
			console.log(cacheImageKey);
		});
	}
	/*科研文章 end*/

	function BombBoxlClose() {
		$(".blackcover").remove();
		$("body").css("position", "");
		UE.delEditor('editor');
	}

})