$(function() {
	//底部调整
	var isChrome = navigator.userAgent.toLowerCase().match(/chrome/) != null; 
	if (!isChrome) {
		$(".tpl-page-container .tpl-content-wrapper").addClass("R-wra");
		$(".tpl-page-container .tpl-left-nav").addClass("L-tpl");
	}
	//动态给所属栏目添加必填图标
	$('.ng-add-span .am-selected').append($('<span> </span>').attr('class', 'ng-syte-span').addClass('am-back-input'));
	//必填提示 类名当作实参传进方法中
	//当输入框输入为空,失去焦点时,提示图标为交叉,
	//当输入框输入不为空,失去焦点时,提示图标为勾
	//文章标题
	ng_titian('ngco_Ojs_bitian');
	//发布日期         
	ng_titian('ngco_Ojs_bitian2');
	//设置必填标记的方法
	function ng_titian(leiming) {
		var BiTianParent = $('.' + leiming).parents('.am-form-group');
		var BiTianNext = $('.' + leiming).next('i');
		$(BiTianParent).addClass('am-form-error');
		$('.' + leiming).addClass('am-back-input');
		$('.' + leiming).blur(function() {
			if ($.trim($(this).val()) == '') {
				$(BiTianParent).removeClass('am-form-success');
				$(BiTianParent).addClass('am-form-error')
				$(BiTianNext).removeClass('am-icon-check');
				$(BiTianNext).addClass('am-icon-times');
				$('.' + leiming).removeClass('am-back-input');
			} else {
				$(BiTianParent).removeClass('am-form-error');
				$(BiTianParent).addClass('am-form-success')
				$(BiTianNext).removeClass('am-icon-times');
				$(BiTianNext).addClass('am-icon-check');
				$('.' + leiming).removeClass('am-back-input');
			}
		})
	}
	//页面中的input按钮事件
	$('.tpl-switch').find('.tpl-switch-btn-view').on('click', function() {
		$(this).prev('.tpl-switch-btn').prop("checked", function() {
			if ($(this).is(':checked')) {
				return false;
			} else {
				return true;
			}
		})
	})
	//必填
	var BiTianParent = $('.ngco-Ojs-bitian').parent().parent('.am-form-group');
	var BiTianNext = $('.ngco-Ojs-bitian').next('.ngar-Kjs-biaoji');
	$(BiTianParent).addClass('am-form-error');
	$(BiTianNext).addClass('am-icon-asterisk');
	// 必填项图标提示
	var old_val = '请选择栏目';
	$('.am-selected-content li').click(function() {
		var new_val = $('.posi_box2 .am-dropdown-toggle .am-fl').text();
		if (old_val != new_val) {
			$(BiTianParent).removeClass('am-form-error');
			$(BiTianParent).addClass('am-form-success')
			$(BiTianNext).removeClass('am-icon-times');
			$(BiTianNext).addClass('am-icon-check');
		} else {
			$(BiTianParent).removeClass('am-form-success');
			$(BiTianParent).addClass('am-form-error')
			$(BiTianNext).removeClass('am-icon-check');
			$(BiTianNext).addClass('am-icon-times');
			$(BiTianNext).removeClass('am-icon-asterisk');
		}
	})
	//必选判断(弹窗效果)  检测表单
	var reg = /^\d+(\.\d+)?$/;
	$('#am-regSubmit,#regbaocun').on('click', function() {
		if ($.trim($('.posi_box2 .am-dropdown-toggle .am-fl').text()) == '请选择栏目') {
			confirm('请选择栏目');
			return false;
		}
		if ($.trim($('#Title').val()) == '') {
			confirm('请输入文章标题');
			return false;
		}
		if ($('#Sort').val() != '') {
			if (!reg.test($.trim($('#Sort').val()))) {
				confirm('你输入的自定义排序不合法，必须是一个数字');
				return false;
			}
		}
		if ($('#Commenttotal').val() != '') {
			if (!reg.test($.trim($('#Commenttotal').val()))) {
				confirm('你输入的评论人数不合法，必须是一个数字');
				return false;
			}
		}
		if ($('#Click').val() != '') {
			if (!reg.test($.trim($('#Click').val()))) {
				confirm('你输入的浏览次数不合法，必须是一个数字');
				return false;
			}
		}
		if ($.trim($('#ngre-Ainput').val()) == '') {
			confirm('请选择发布日期');
			return false;
		}
		$('#form-sublime').submit();
		return true;
	});
	$('input[type=file]').change(function() {
		$filePath = URL.createObjectURL(this.files[0]);
		$(this).siblings('div').find('img').attr('src', $filePath);
	})
	$('.submin_but').click(function() {
		$('.form').submit();
	});
	//日期插件
	$(function() {
		$('.select_ch').change(function() {
			var input_val = $('.select_ch ').find("option:selected").text();
			$('.input_class').val(input_val);
		});
		var now = new Date();
		var time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" : "") + now.getDate();
		$('#add-time').val(time);
		$.fn.datetimepicker.dates['zh-CN'] = {
			days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
			daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
			daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
			months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			today: "今日",
			suffix: [],
			meridiem: ["上午", "下午"]
		};
		var $dpInput = $('.form-datetime-lang').datetimepicker({
			container: '#dateBox2',
			language: 'zh-CN',
			format: 'yyyy-mm-dd hh:ii'
		});
	});
	//日期插件结束
	// 模态框  右上角的图标叉的添加和事件
	$("body").on("click", function() {
		var a_2 = "<a class='am-icon-close ngjs-a2' href='javascript: void(0)'  onclick='$(this).prev().click();'></a>";
		$(".am-pureview-actions").append(a_2);
		$(".ngjs-a2").addClass("ngph-a1");
		$(".ngjs-a2").prev().addClass("ngph-a2");
	})
	// 图片上传js============================================================
	//鼠标移入事件  图片 
	$('.am-no-layout').on('mouseover', 'li', function() {
		$(this).find('.ty-button').show();
	})
	//鼠标移出事件  图片 
	$('.am-no-layout').on('mouseout', 'li', function() {
		$(this).find('.ty-button').hide();
	});
	//查看图片按钮
	$('body').on('click', '.btn-search', function() {
		$(this).parents('li').find('img').click();
	})
	//  图片上传js============================================================
	var picture_path = ''
	var pic_ul = ''
	var picture_li = ''
	var btn = ''
	var thumbnail = 0
	//模态框点击事件
	$('body').on('click', '.btn-add,.btn-update,.btn-remove', function() {
		picture_li = $(this).parents('li')
		pic_ul = $(this).prev()
		btn = $(this).data('btn');
		switch (btn) {
			case 'remove':
				var parents = $(this).parents('li');
				var bool = confirm('确定要删除该图片吗？');
				if (bool) {
					parents.remove();
					if (btn == 'remove2') {
						pic_ul.next().show();
					}
				}
				break;
			case 'remove2':
				var parents = $(this).parents('li');
				var bool = confirm('确定要删除该图片吗？');
				if (bool) {
					parents.remove();
					$('#thumbnail').show();
				}
				break;
			default:
				$('#imgInFo')[0].reset();
				switch (btn) {
					case 'update':
						$('.modal .am-modal-hd').text('更新图片信息');
						thumbnail = 0;
						break;
					case 'add':
						$('.modal .am-modal-hd').text('图片上传管理');
						thumbnail = 0;
						break;
					case 'add2':
                        $('.modal .am-modal-hd').text('图片上传管理');
                        thumbnail = 1;
                        break;
                    case 'update2':
                        $('.modal .am-modal-hd').text('更新图片信息');
                        thumbnail = 1;
                        break;
				}
				if (btn == 'update' || btn == 'update2') {
					var values = $(this).parents('li').find('input')
					picture_path = values.eq(0).val()
					$('#finalImg').attr('src', values.eq(0).val())
				}
				$('.modal').modal({
					relatedElement: this,
					onConfirm: function() {
						if (btn == 'add2') {
							var name = 'thumbnail'
							var data_btn = '2'
							if($("#finalImg").attr("src") != ""){
								pic_ul.next().hide();
                            }
						} else {
							var name = 'picture[]'
							var data_btn = ''
						}
						var picture = '<li style="float: left; position: relative">' + '<div class="tpl-table-images-content-i-info absolute-middle">\n' + '<button type="button" class="other-btn1 btn1 btnsty am-btn-circle am-btn am-btn-success am-margin-horizontal btn-update ty-button" data-btn="update' + data_btn + '"><span class="square1"><i class="am-icon-pencil-square-o"></i>&nbsp;修改</span></button>' + '<button type="button" class="other-btn2 btnsty am-btn-circle am-btn am-btn-danger am-margin-horizontal btn-remove ty-button" data-btn="remove' + data_btn + '"><span class="remoe1"><i class="am-icon-remove ngsty-rem"></i>&nbsp;删除</span></button>' + '<button type="button" class="other-btn2 btnsty am-btn-circle am-btn am-btn-secondary am-margin-horizontal btn-search ty-button" data-btn="search"><span class="search1"><i class="am-icon-search ngsty-rem"></i>&nbsp;查看</span></button>' + '</div>' + '<img src="' + picture_path + '" height="120px" alt="">' + '<input type="hidden" name="' + name + '" value="' + picture_path + '"/>' + '</li>'
						if (btn == 'update') {
							picture_li.replaceWith(picture);
						} else {
							if($("#finalImg").attr("src") != ""){
									pic_ul.append(picture);
	                            }else{
	                                confirm("请选择图片");
	                            }
						}
					}
				})
				break;
		}
	})
	//===========================
	//  在上传图片的弹出窗口,点击非图片区域,就隐藏窗口
	// ==========================
	$(".ngad-Jsj-click").on("click", function() {
		closeTailor(this);
	});
	$(".ngad-Ksj-change").on("change", function() {
		selectImg(this);
	});
	$(".ngad-Usj-click").on("click", function() {
		closeTailor(this);
	});
	// 图片上传
	function imgChange(e1, e2) {
		e1.change(function() {
			$filePath = URL.createObjectURL(this.files[0]);
			$('#ngac_Nfu_box').find('img').attr('src', $filePath); //给此img元素的src重新赋值
			$("#ngac_Nfu_box").show(); // 选中图片后， 显示此box
			var reader = new FileReader();
			reader.readAsDataURL(this.files[0]); //读取文件
			// var fileName=this.files[0]['name']; //获取图片的名称
			reader.onload = function(e) { //读取完成回调
				imgBase = e.target.result;
				e2.val(imgBase);
			}
		})
	}
	//原始上传
	$('#originalImg').click(function() {
		$("#originalChoose").trigger('click');
		// imgChange($('#originalChoose'),$('#originalUpdate'));
	})
		// 上传进度
		function progressHandlingFunction(e) {
			var curr = e.loaded;
			var total = e.total;
			var process = Math.floor(curr / total * 100);
			$("#loading").show().text((process - 1) + '%');
			$("#true.am-modal-btn").addClass("true_active");
			$.AMUI.progress.set((process - 1) / 100);
		}
	$("#originalChoose").change(function() {
		$(this)[0].files[0]
		var formData = new FormData();
		formData.append("file", $(this)[0].files[0]);
		formData.append("action", 'upload');
		formData.append("dir", 'download');
		if(thumbnail == 1){
            formData.append("type", 'thumbnail');
            if($('#data_id').val() != 0){
                formData.append("filename", 'download_thumbnail_' + $('#data_id').val());
            }
        }
		$.ajax({
			scriptCharset: 'UTF-8',
			type: 'post',
			url: '/api/admin_process',
			data: formData,
			cache: false,
			processData: false,
			contentType: false,
			dataType: 'json',
			xhr: function () {
				var myXhr = $.ajaxSettings.xhr();
				if (myXhr.upload) { //检查upload属性是否存在
					//绑定progress事件的回调函数
					myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
				}
				return myXhr; //xhr对象返回给jQuery使用
			},
		}).success(function(data) {
			if(data.state == "FAILURE"){
				alert(data.msg)
			}else{
				$('#finalImg').attr('src', data.url)
				picture_path = data.url;
				$("#loading").text("100%").hide();
				        $.AMUI.progress.set(1);
				        $("#true.am-modal-btn").removeClass("true_active");
			}
		}).error(function() {
			alert("上传失败");
		});
	})
	// 剪切时的问题
	 if($("#picture_view li img").attr("src")!==""){
        $("#replaceImg").on("click",function(){
            $("#tailoringImg").addClass("cropper-hidden");
        })
    }else{
        $("#tailoringImg").removeClass("cropper-hidden");
    }
	//图片裁切
	function selectImg(file) {
		if (!file.files || !file.files[0]) {
			return;
		}
		var reader = new FileReader();
		reader.onload = function(evt) {
			var replaceSrc = evt.target.result;
			//更换cropper的图片
			$('#tailoringImg').cropper('replace', replaceSrc, false); //默认false，适应高度，不失真
		}
		reader.readAsDataURL(file.files[0]);
	}
	//关闭裁剪框
	function closeTailor() {
		$(".tailoring-container").toggle();
	}
	//弹出框水平垂直居中
	(window.onresize = function() {
		var win_height = $(window).height();
		var win_width = $(window).width();
		if (win_width <= 768) {
			$(".tailoring-content").css({
				"top": (win_height - $(".tailoring-content").outerHeight()) / 2,
				"left": 0
			});
		} else {
			$(".tailoring-content").css({
				"top": (win_height - $(".tailoring-content").outerHeight()) / 2,
				"left": (win_width - $(".tailoring-content").outerWidth()) / 2
			});
		}
	})();
	//弹出图片裁剪框
	$("#replaceImg").on("click", function() {
		$(".tailoring-container").toggle();
	});
	//图像上传
	//cropper图片裁剪
	$('#tailoringImg').cropper({
		aspectRatio: 1 / 1, //默认比例
		preview: '.previewImg', //预览视图
		guides: false, //裁剪框的虚线(九宫格)
		autoCropArea: 0.5, //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
		movable: false, //是否允许移动图片
		dragCrop: true, //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
		movable: true, //是否允许移动剪裁框
		resizable: true, //是否允许改变裁剪框的大小
		zoomable: false, //是否允许缩放图片大小
		mouseWheelZoom: false, //是否允许通过鼠标滚轮来缩放图片
		touchDragZoom: true, //是否允许通过触摸移动来缩放图片
		rotatable: true, //是否允许旋转图片
		crop: function(e) {
			// 输出结果数据裁剪图像。
		}
	});
	//旋转
	$(".cropper-rotate-btn").on("click", function() {
		$('#tailoringImg').cropper("rotate", 45);
	});
	//复位
	$(".cropper-reset-btn").on("click", function() {
		$('#tailoringImg').cropper("reset");
	});
	//换向
	var flagX = true;
	$(".cropper-scaleX-btn").on("click", function() {
		if (flagX) {
			$('#tailoringImg').cropper("scaleX", -1);
			flagX = false;
		} else {
			$('#tailoringImg').cropper("scaleX", 1);
			flagX = true;
		}
		flagX != flagX;
	});
	//裁剪后的处理
	$("#sureCut").on("click", function() {
		if ($("#tailoringImg").attr("src") == null) {
			return false;
		} else {
			var cas = $('#tailoringImg').cropper('getCroppedCanvas'); //获取被裁剪后的canvas
			cas.toBlob(function(blob_url) {
				blob_url.lastModifiedDate = new Date();
				blob_url.name = 'picture.png';
				var formData = new FormData();
				formData.append("file", blob_url, 'picture.png');
				formData.append("action", 'upload');
				formData.append("dir", 'download');
				if(thumbnail == 1){
					formData.append("type", 'thumbnail');
					if($('#data_id').val() != 0){
						formData.append("filename", 'download_thumbnail_' + $('#data_id').val());
					}
				}
				$.ajax({
					// scriptCharset: 'UTF-8',
					type: 'post',
					url: '/api/admin_process',
					data: formData,
					cache: false,
					processData: false,
					contentType: false,
					dataType: 'json',
					dataType: 'json',xhr: function () {
						var myXhr = $.ajaxSettings.xhr();
						if (myXhr.upload) { //检查upload属性是否存在
							//绑定progress事件的回调函数
							myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
						}
						return myXhr; //xhr对象返回给jQuery使用
					},
				}).success(function(data) {
					if(data.state == "FAILURE"){
						alert(data.msg)
					}else{
						$('#finalImg').attr('src', data.url)
						picture_path = data.url;
						$("#loading").text("100%").hide();
				        $.AMUI.progress.set(1);
				        $("#true.am-modal-btn").removeClass("true_active");
					}
				}).error(function() {
					alert("上传失败");
				});
			}); //转换为base64地址形式
			//关闭裁剪框
			closeTailor();
		}
	});
	// 插入多行
	$('.am-icon-plus-circle').click(function() {
		var input_div = '<div class="am-plus-box am-form-group">' + '<input type="text" placeholder="请输入镜像名称" class="tpl-form-input ngco_Ojs_email ty-download mirror-name" id="email" value="" name="mirror_name">' + ' <input type="text" placeholder="请输入下载地址"class="tpl-form-input ngco_Ojs_email ty-download" id="email" value="" name="mirror_url">' + '<span class="am-icon-minus-circle"></span>' + '</div>'
		$('#mirror').append(input_div)
		var sum = $('#default-download').find('option').length
		$('#default-download').append('<option value="' + sum + '"></option>')
	})
	// 移除
	$('#mirror').on('click', '.am-icon-minus-circle', function() {
		// 移除对应的下拉框选项
		var index = $('.am-icon-minus-circle').index(this)
		$('#default-download').find('option').eq(index + 2).remove()
		// 修改value值
		for (var i = 0; i < $('#default-download').find('option').length; i++) {
			$('#default-download').find('option').eq(i).attr('value', i)
		}
		// 移除输入框
		$(this).parent().remove()
	})
	// 值改变
	$("#mirror").on('change', '.mirror-name', function() {
		var change_index = $('.mirror-name').index(this)
		$('#default-download').find('option').eq(change_index + 1).html($(this).val())
	})
	$('body').on('change','#file-input',function() {
		$(this)[0].files[0]
		var formData = new FormData();
		formData.append("file", $(this)[0].files[0]);
		formData.append("action", 'file');
		console.log(window.location.pathname + window.location.search)
		$.ajax({
			scriptCharset: 'UTF-8',
			type: 'post',
			dataType: 'json',
			url: window.location.pathname + window.location.search,
			data: formData,
			cache: false,
			processData: false,
			contentType: false,
		}).done(function(data) {
			console.log(data.status)
			if (data.status == 1) {
				$('#file-path').attr('value', data.path)
				alert('上传成功')

				$('#file_view').append(`<li style="float: left;position: relative">
					`+data.path+`<span class="am-btn-circle am-btn am-btn-danger am-margin-horizontal remove_file_btn">删除</span>
				</li>`)
				$('#qrcodeUpload').addClass('hidden')
				$('#qrcodeUpload span input').remove()
				$('#qrcodeUpload span').append(`<input type="file" class="input-file" id="file-input">`) 	
			} else {
				alert(data.msg)
			}
		}).fail(function() {
			alert('服务器超时，请重试！');
		});
	}) 
	 	// 点击上传图片按钮时，初始化模态框中的img
		$("#qrcodeUpload,#thumbnail,.addimg-js").on("click",function(){
			$("#finalImg").attr("src","");
			$("#true.am-modal-btn").addClass("true_active");
		})
	    // 浏览权限
		$('#button-all-read').click(function(){
			if($(this).prev().prop('checked')){
				$('#authority').hide()
			}else{
				$('#authority').show()
			}
		})
		if($('#all-read').prop('checked')){
				$('#authority').hide()
			}else{
				$('#authority').show()
			}
		// 下载权限
		$('#button-all-download').click(function(){
			if($(this).prev().prop('checked')){
				$('#permission').hide()
			}else{
				$('#permission').show()
			}
		})
		if($('#all-download').prop('checked')){
				$('#permission').hide()
			}else{
				$('#permission').show()
			}

	// 详情内容有无

	$("body").on("click",".tpl-switch-btn-view",function () {
		if ($("#content").attr("checked")){
			$("#content").removeAttr("checked");
			$(".ue-have").hide();
			ue.setContent('');
		}else{
			$("#content").attr("checked","checked");
			$(".ue-have").show();
		}
	})

	$('body').on('click','.remove_file_btn',function(){
		$('#file_view  li').remove()
		$('#qrcodeUpload').removeClass('hidden')
		$('#file-path').val('')
	})
})