/**
 * 短信消息 发布
 * 2018/4/20 by liufang
 */
$(function () {
	var layer;
	var orgId = $("#orgId").val();

	layui.use('layer', function () {
		layer = layui.layer;

	});
	var isOpenApprove;//判断是否开启了多级审核 1.开启了多级审核 2，没有开启多级审核
	var validatePhones = true; //短信是否合法
	var showContentCount = 1; //短信数量
	var tpl = {
		"groupTpl": '<div class="dialog-wp">\
			<div class="mask"></div>\
			<div class="dialog dialog-group-con">\
				<div class="title-wp">\
					<span>选择群组</span>\
					<span class="close-btn"></button>\
				</div>\
				<div class="dialog-group-wp">\
					<div class="group-list clearfloat">\
						<div class="group-item">\
							<div class="checkbox-wp">\
							   <span class="checkbox-input">\
								 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
								  <span class="checkbox-inner"></span>\
							   </span>		\
							   <label class="checkbox-con" for="wx">微信</label>\
							</div>\
						</div>\
						<div class="group-item">\
							<div class="checkbox-wp">\
							   <span class="checkbox-input">\
								 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
								  <span class="checkbox-inner"></span>\
							   </span>		\
							   <label class="checkbox-con" for="wx">微信</label>\
							</div>\
						</div>\
			<div class="group-item">\
			<div class="checkbox-wp">\
			   <span class="checkbox-input">\
				 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
				  <span class="checkbox-inner"></span>\
			   </span>		\
			   <label class="checkbox-con" for="wx">微信</label>\
			</div>\
		</div>\<div class="group-item">\
			<div class="checkbox-wp">\
			   <span class="checkbox-input">\
				 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
				  <span class="checkbox-inner"></span>\
			   </span>		\
			   <label class="checkbox-con" for="wx">微信</label>\
			</div>\
		</div>\<div class="group-item">\
			<div class="checkbox-wp">\
			   <span class="checkbox-input">\
				 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
				  <span class="checkbox-inner"></span>\
			   </span>		\
			   <label class="checkbox-con" for="wx">微信</label>\
			</div>\
		</div>\<div class="group-item">\
			<div class="checkbox-wp">\
			   <span class="checkbox-input">\
				 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
				  <span class="checkbox-inner"></span>\
			   </span>		\
			   <label class="checkbox-con" for="wx">微信</label>\
			</div>\
		</div>\
			<div class="group-item">\
			<div class="checkbox-wp">\
			   <span class="checkbox-input">\
				 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
				  <span class="checkbox-inner"></span>\
			   </span>		\
			   <label class="checkbox-con" for="wx">微信</label>\
			</div>\
		</div>\
			<div class="group-item">\
			<div class="checkbox-wp">\
			   <span class="checkbox-input">\
				 <input type="checkbox" id="wx" class="check-item enterprise-wx" />\
				  <span class="checkbox-inner"></span>\
			   </span>		\
			   <label class="checkbox-con" for="wx">微信</label>\
			</div>\
		</div>\
					</div>\
				<div class="dialog-group-btns">\
					<button class="group-sure-btn btn-big-red">确认修改</button>\
					<button class="group-cancel-btn btn-big-black">取消</button>\
				</div>\
				</div>\
			</div>\
		</div>	',
		"exportTpl": '<div class="dialog-wp">\
			<div class="mask"></div>\
			<div class="dialog dialog-export-con">\
				<div class="title-wp">\
					<span>txt导入</span>\
					<span class="close-btn"></button>\
				</div>\
				<div class="dialog-export-wp">\
					<div class="d-export-top">\
						<input type="text" class="e-name" placeholder="未选择文件" readonly/>\
						<div class="e-file-wp">\
							<input class="file-input" id="txtFile" type="file" name="uploadfile"/>\
							<button class="file-btn">选择文件</button>\
						</div>\
					</div>\
					<div class="export-tips"><span class="red">*</span>TXT文档自定义导入，每行一个号码，换行显示</div>\
					<button class="btn-big-red export-sure-btn">导入</button>\
				</div>\
			</div>\
		</div>	',
		"typeTpl": '<option value="">选择审核类型</option>\
		<% for(i=0;i<data.length;i++){%> \
			<option value="<%=data[i].id%>"><%=data[i].name%></option>\
			<%}%>'	

	};
	//	layer.msg(1)
	var contextPath = $("#contextPath").val()
	var appSend = {
		judge: function (id) {
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/templ/checkHasMobileAccount",
				data: {
					"orgId": id,
				},
				success: function (data) {
					if (data.code == '200') {
						if (data.data == "true") {
							$(".message-mask").css("display", "none")
						} else {
							$(".message-mask").css("display", "block");
							return false
						}
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		init: function () {
			this.render();
			this.bindEvent();
			this.getProjectList();
		},
		render: function () {
			var id = this.getQueryString("id")
			if (!!id) {
				this.ajaxDetail(id)
			}


		},
		bindEvent: function () {
			var _this = this;
			//输入号码输入触发事件
			$(".mobile-list").on("input propertychange", function () {
				_this.changePhonesCount();
			});
			//重号过滤
			$(".filter-btn").on("click", function () {
				var content = $('.mobile-list').val();
				var phones = new Array();
				phones = content.split('\n');

				var f_phones = _this.unique(phones);
				var str = "";
				for (var i = 0; i < f_phones.length; i++) {
					var element = f_phones[i];
					if (element != "" && i < f_phones.length - 1) {
						str += element + "\n"
					} else {
						str += element;
					}
				}

				$('.mobile-list').val(str);
				_this.changePhonesCount();
			});
			//号码清空
			$(".clear-btn").on("click", function () {
				$('.mobile-list').val("");
			});
			//输入短信内容触发事件
			$(".message-con").on("input propertychange", function () {
				_this.contentOnchange();
			});
			//清空短信内容
			$(".con-clear-btn").on("click", function () {
				$(".message-con").val("")
			});
			//提交短信
			$(".con-sure-btn").on("click", function () {
				// _this.submitMsg();
			});
			//选择群组
			$(".choose-btn").on("click", function () {
				$("body").append(template.render(tpl.groupTpl));
				$(".close-btn,.group-cancel-btn").on("click", function () {
					$(".dialog-wp").remove();
				})
			});
			//导入
			$(".export-btn").on("click", function () {
				$("body").append(template.render(tpl.exportTpl));
				$(".close-btn").on("click", function () {
					$(".dialog-wp").remove();
				});
				//选择文件
				$(".file-input").on("change", function () {
					_this.chooseFile($(this));
				});
				$(".export-sure-btn").on("click", function () {
					if (!$(".d-export-top .e-name").val()) {
						layer.alert("请先选择导入的文件")
					} else {
						_this.submitFile();
					}

				})
			})

		},
		/**
		 * 号码去重
		 *  @param str 电话号码
		 */
		unique: function (arr) {
			var result = [],
				hash = {};
			for (var i = 0, elem;
				(elem = arr[i]) != null; i++) {
				if (!hash[elem]) {
					result.push(elem);
					hash[elem] = true;
				}
			}
			return result;
		},
		getApprovalTypeList(orgId){
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/approval/getApprovalType",
				data: {
					"orgId": orgId
				},
				success: function (data) {
					if (data.code == 200) {
						$("#approvalType").html(template.render(tpl.typeTpl)(data));
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
   //调用项目列表接口，如果是1个的话就显示审核
		getProjectList(){
			let	_this = this
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/templ/getOrgList",
				success: function (data) {
					if (data.code == 200) {
						if(data.data.length==1){
							console.log("getProjectList",data.data[0].id)
							_this.getIfCanApproval(data.data[0].id)
						}
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
			//判断是否开启了审核
			getApproveTypeIsOpen(orgId){
				var _this=this
				$.ajax({
					type: "post",
					url: contextPath+ "/notice/approval/getApprovalSetDto",
					data: {
						"orgId": orgId
					},
					success: function (data) {
						if (data.code == 200) {
							if(data.data.isOpen==1){
								_this.isOpenApprove=1
								$(".approvalStyle").show();
								_this.getApprovalTypeList(orgId)
							}else {
								_this.isOpenApprove=2
								$(".approvalStyle").hide();
							}
						} else {
							layer.msg(data.msg)
						}
					},
					error: function (error) {
						layer.msg('error')
					}
				});
			},
		getIfCanApproval(orgId){
        var _this=this
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/approval/getSetByOrgId",
				data: {
					"orgId":  orgId
				},
				success: function (data) {
					if (data.code == 200) {
						if(data.data.isOpen==1){//显示审核下拉列表
							_this.getApproveTypeIsOpen(orgId)
						}else{////不显示审核下拉列表
							$(".approvalStyle").hide();
						}
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 号码输入发生变化
		 */
		changePhonesCount: function () {
			var _this = this;
			var content = $('.mobile-list').val();
			var phones = new Array();
			phones = content.split('\n');
			var phonesCount = 0;
			if (phones.length > 0) {
				validatePhones = true;
				for (var i = 0; i < phones.length; i++) {
					if (phones[i] != "") {
						if (_this.isPoneAvailable(phones[i]) == false) {
							validatePhones = false;

						} else {
							phonesCount++;
						}
					}
				}
				if (validatePhones) {
					$('.mobile-list').css("border-color", "#ddd");
				} else {
					$('.mobile-list').css("border-color", "red");
				}
			}
		},
		/**
		 * 判断 是否是电话号码
		 *  @param str 电话号码
		 */
		isPoneAvailable: function (str) {
			var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
			if (!myreg.test(str)) {
				return false;
			} else {
				return true;
			}
		},
		/**
		 * 短信内容触发事件
		 */
		contentOnchange: function () {
			var _this = this;
			var sig = $('.suffix-name').html().length;
			var size = $('.message-con').val().length + sig;
			_this.computerAndShowMsgCount(size);
		},
		/**
		 * 判断输入短信条数
		 * @param size 短信字数
		 */
		computerAndShowMsgCount: function (size) {
			$(".msg-num-wp .num").text(size);
			if (size > 70) {
				var temp = parseInt((size - 70) / 67);
				if ((size - 70) % 67 > 0) {
					temp += 1;
				}
				temp = 1 + temp;
				$('.msg-num').text(temp);
				if (temp > 1 && temp != showContentCount) {
					layer.msg('当前内容达到' + temp + '条短信数量！')
					//						
					showContentCount = temp;
				}

			} else {
				$('.msg-num').text(1);
				if (1 != showContentCount) {
					layer.msg('当前内容达到' + 1 + '条短信数量！');
					//						
					showContentCount = 1;
				}
			}
		},
		/**
		 * 提交短信
		 */
		submitMsg: function () {
			//短信id
			var id = $(".con-sure-btn").data("id");
			//项目id
			var orgId = $("#orgId").val();
			if (!orgId) {
				layer.msg("请选择项目");
				return false;
			};
			var mobiles = $('.mobile-list').val();

			re = new RegExp("\n", "g"); //定义正则表达式
			//第一个参数是要替换掉的内容，第二个参数"g"表示替换全部（global）。
			var Newstr = mobiles.replace(re, ","); //第一个参数是正则表达式。
			if (Newstr == "") {
				layer.alert('请输入目标号码！');
				return;
			}
			if ($('.message-con').val() == "") {
				layer.alert('请输入短信内容！');
				return;
			}
			if (!validatePhones) {
				layer.alert('请输入正确的手机号码！');
				return;
			}
			var approvedata= $("#approvalType").val()
			if (this.isOpenApprove==1 && !approvedata) {
				layer.alert('请选择审核类型！');
				return;
			}
			$(".con-sure-btn").attr("disabled", true)
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/phoneMessage/saveOrUpdate",
				data: {
					"orgId": orgId,
					"phones": Newstr,
					"approvalType" : $("#approvalType").val()?$("#approvalType").val():'',
					"content": $('.message-con').val(),
					"id": !!id ? id : ''
				},
				success: function (data) {
					var data = JSON.parse(data);
					if (data.code == '200') {

						if (!!$(".con-sure-btn").data("id")) {
							layer.msg('编辑成功！');
							window.location.href = contextPath + '/notice/audit/noticeMsgVerify';
						} else {
							layer.msg('发送成功！');
							$('.mobile-list').val("")
							$('.message-con').val("");
						}
					} else {
						layer.msg(data.msg)
					}
					$(".con-sure-btn").attr("disabled", false)
				},
				error: function (error) {
					$(".con-sure-btn").attr("disabled", false)
					layer.msg('error')
				}
			});

		},
		chooseFile: function ($this) {
			var fileName = $(".file-input").val();
			var name = $this[0].files[0].name;
			var extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
			if (extension == "txt") {
				if (fileName == null || fileName == "") {
					layer.alert("导入数据为空!");
					return;
				} else {
					$(".d-export-top .e-name").val(name);
				}
			} else {
				alert("请上传txt格式的文件");
			}
		},
		submitFile: function () {
			var _this = this;
			$.ajaxFileUpload({
                url: $("#contextPath").val()+ "/notice/phoneMessage/txtToPhone", //用于文件上传的服务器端请求地址
                secureuri: false, //是否需要安全协议，一般设置为false
                fileElementId: 'txtFile', //文件上传域的ID
                dataType: 'String', //返回值类型 一般设置为json
                success: function (data, status)  //服务器成功响应处理函数
                {
                    var data = JSON.parse(data);
                    //选择文件
                    $(".file-input").on("change",function(){
                        _this.chooseFile($(this));
                    });
                    if (data.code == '200') {
                        for(var i = 0;i<data.data.length;i++){
                            $(".mobile-list").val($(".mobile-list").val()+'\n'+data.data[i]);
                        };
                        $(".filter-btn").click();
                        $(".dialog-wp").remove();
                    } else {
                        alert(data.msg);

                    }
                }
            })
		},
		/**
		 * 获取url的参数
		 * @paran name 参数名称
		 */
		getQueryString: function (name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return unescape(r[2]);
			return null;
		},
		/**
		 * 获取详情
		 * @param id
		 */
		ajaxDetail: function (id) {
			var _this = this;
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/phoneMessage/getDetail",
				data: {
					"id": id
				},
				success: function (data) {
					var data = JSON.parse(data);
					if (data.code == 200) {
						$(".con-sure-btn").data("id", data.data.id);
						$("#orgId").val(data.data.orgId);
						$(".message-con").val(data.data.content);
						var re = new RegExp(",", "g"); //定义正则表达式
						//第一个参数是要替换掉的内容，第二个参数"g"表示替换全部（global）。
						var Newstr = data.data.phones.replace(re, "\n"); //第一个参数是正则表达式。
						$('.mobile-list').val(Newstr)

					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		}

	};
	appSend.judge(orgId);
	appSend.init();
})