var permDelete = $("#perm-delete").val(); //删除权限
var permEdit = $("#perm-edit").val(); //编辑权限
var permApprove = $("#perm-approve").val(); //审核权限
var userType = $("#userType").val();
/**
 * 短信消息发布公告审核
 * 2018/4/20 by liufang
 */
$(function() {
	var table
	var auditNoticePermission = $("#auditNoticePermission").val();
	var tpl = {
		"detailTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-msg-con">\
					<div class="title-wp">\
						<span>消息详情</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-msg-wp clearfloat">\
						<div class="msg-left-wp clearfloat">\
							<span class="m-l-tips">目标号码<br><span class="m-l-t-kua">（每行一个）</span></span>\
							<div class="m-l-list">\
								<% for(var i=0;i<phones.length;i++){%>\
									<%= phones[i] %>\
								<%} %>\
							</div>\
						</div>\
						<div class="msg-right-wp clearfloat">\
							<span class="m-l-tips">短信内容</span>\
							<div class="m-r-con-wp">\
								<div class="m-r-con"><%= content %></div>\
								<span class="suffix-wp">短信后缀：<span class="suffix-name">【服务之窗】</span></span>\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>',
		shTpl: '<div class="mask">\
							<div class="pop_wrap">\
								<div class="pop_title">短信审核<span class="pop_close"></span></div>\
								<div class="pop_content">\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">目标用户</div>\
										<div class="part_content float-left">\
											<div class="target_wrap">\
												<%for(var i=0;i<personList.length;i++){%>\
													<label><input type="checkbox" name="account" value="<%=personList[i].id%>"  class="account_info" contactWay="<%=personList[i].contactWay%>"checked="checked"><span><%=personList[i].name%></span><span><%=personList[i].contactWay%></span><span class="dots_span"><%=personList[i].virName%></span></label>\
												<%}%>\
											</div>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">&nbsp</div>\
										<div class="part_content float-left">\
											共计: <span class="blue current_iofo_user_len txt_blue"><%=personLen%>人</span>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">短信内容</div>\
										<div class="part_content float-left">\
											<div class="part_content_wrap">\
												<textarea id="contnet_info" class="pop_textarea"><%=res.content%></textarea>\
											</div>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">&nbsp</div>\
										<div class="part_content float-left">\
												<span class="txt_blue float-left">建议字数不超过140个</span>\
												<span class="red txt_red float-right current_iofo_content_len"><%=res.content.length%>/140</span>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">编辑时间</div>\
										<div class="part_content float-left"><%=res.editTime%></div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">编辑人</div>\
										<div class="part_content float-left"><%=res.editUser%></div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">发布状态</div>\
										<div class="part_content float-left"><%=stateStr%></div>\
									</div>\
									<div class="part_ part_state clearfloat">\
										<div class="part_title float-left">审核结果</div>\
										<div class="part_content float-left">\
											<div class="radio-wp">\
											   <span class="radio-input">\
												 <input type="radio" id="status1" class="radio-item status" data-status="1" name="status" checked/>\
												  <span class="radio-inner"></span>\
											   </span>\
											   <label class="radio-con" for="status1">通过</label>\
											</div>\
											<div class="radio-wp">\
											   <span class="radio-input">\
												 <input type="radio" id="status2" class="radio-item status" data-status="0" name="status" />\
												  <span class="radio-inner"></span>\
											   </span>\
											   <label class="radio-con" for="status2">不通过</label>\
											</div>\
										</div>\
									</div>\
									<div class="part_ part_suggest clearfloat">\
										<div class="part_title float-left">审核意见</div>\
										<div class="part_content float-left">\
											<div class="part_content_wrap">\
												<textarea id="contnet_suggest" class="pop_textarea"></textarea>\
											</div>\
										</div>\
									</div>\
									<div class="part_ part_btn clearfloat">\
										<span class="btn-red pop_sure_btn">确定</span>\
									</div>\
								</div>\
							</div>\
						</div>',
		xqTpl: '<div class="mask">\
							<div class="pop_wrap">\
								<div class="pop_title">短信详情<span class="pop_close"></span></div>\
								<div class="pop_content">\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">目标用户</div>\
										<div class="part_content float-left">\
											<div class="target_wrap">\
												<%for(var i=0;i<personList.length;i++){%>\
													<label><span><%=personList[i].name%></span><span><%=personList[i].contactWay%></span><span class="dots_span"><%=personList[i].virName%></span></label>\
												<%}%>\
											</div>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">&nbsp</div>\
										<div class="part_content float-left">\
											共计: <span class="blue current_iofo_user_len txt_blue"><%=personLen%>人</span>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">短信内容</div>\
										<div class="part_content float-left">\
											<div class="part_content_wrap">\
												<textarea readonly id="contnet_info" class="pop_textarea"><%=res.content%></textarea>\
											</div>\
										</div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">编辑时间</div>\
										<div class="part_content float-left"><%=res.editTime%></div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">编辑人</div>\
										<div class="part_content float-left"><%=res.editUser%></div>\
									</div>\
									<div class="part_ clearfloat">\
										<div class="part_title float-left">发布状态</div>\
										<div class="part_content float-left"><%=stateStr%></div>\
									</div>\
									<% if(res.auditor){ %>\
										<div class="part_ clearfloat">\
											<div class="part_title float-left">审核人</div>\
											<div class="part_content float-left"><%=res.auditor%></div>\
										</div>\
									<%}%>\
									<% if(res.auditTime){ %>\
										<div class="part_ part_state clearfloat">\
											<div class="part_title float-left">审核时间</div>\
											<div class="part_content float-left">\
													<span><%=res.auditTime%></span>\
											</div>\
										</div>\
									<%}%>\
									<% if(res.isPass !== null){ %>\
										<div class="part_ part_state clearfloat">\
											<div class="part_title float-left">审核结果</div>\
											<div class="part_content float-left">\
												<% if(res.isPass === 0){ %>\
													<span>未通过</span>\
												<%}else if(res.isPass === 1){%>\
													<span>通过</span>\
												<%}%>\
											</div>\
										</div>\
									<%}%>\
									<div class="part_ part_suggest clearfloat">\
										<div class="part_title float-left">审核意见</div>\
										<div class="part_content float-left">\
											<% if(res.auditOpinion){ %>\
												<span><%=res.auditOpinion%></span>\
											<%}else{%>\
												<span>无</span>\
											<%}%>\
										</div>\
									</div>\
									<div class="part_ part_btn clearfloat">\
										<span class="btn-red pop_sure_btn">确定</span>\
									</div>\
								</div>\
							</div>\
						</div>',
	}
	var contextPath = $("#contextPath").val()
	var appSend = {
		init: function() {
			this.render();
			this.bindEvent();
		},
		render: function() {
			this.rendertable();

		},
		bindEvent: function() {
			var _this = this;
			layui.use('laydate', function() {
				var laydate = layui.laydate;

				//执行一个laydate实例
				laydate.render({
					elem: '#c_startTime' //提交开始时间

				});
				laydate.render({
					elem: '#c_endTime' //提交结束时间

				});
				laydate.render({
					elem: '#a_startTime' //审核开始时间

				});
				laydate.render({
					elem: '#a_endTime' //审核结束时间

				});
			});
			// //重置
			// $(".set-btn").on("click", function() {
			// 	$("#conditionform input").val("");
      //   $("#conditionform select").val("")
      //   $("#conditionform  #orgId").attr('org__id','')
			// })
			//重置
			$(".set-btn").on("click", function() {
				$("#conditionform select").val("")   
				if(userType != 6){
					$("#conditionform input").val("");
					$("#conditionform  #orgId").attr('org__id','');
				}else{
					$("#conditionform input:not('#orgId')").val("");
				}    
			})
			// 关闭公共弹层
			$('body').on('click', '.pop_close', function(event) {
				event.preventDefault();
				/* Act on the event */
				$('.mask').remove()
      });
       // 模糊搜索
			//  _this.search_fuzzy()
			if(userType == 6){
				cjqt.search_fuzzy.event_initial($('#orgId'),'org__id','org__span','/super_cloud','/api/organisation/organization/getselectlist');
				$('body').on("focus",'#orgId',function(event){
					cjqt.search_fuzzy.event_initial_focus($('#orgId'),'org__id','org__span','/super_cloud','/api/organisation/organization/getselectlist')
				});
				$('body').on('blur','#orgId',function(event) {
          var _this = $(this)
          cjqt.search_fuzzy.event_blur(_this,'org__id')
        });
        $('body').on('click','.select_wrap>.org__span', function(event) {
          event.preventDefault();
          event.stopPropagation();
          /* Act on the event */
          var _this = $(this)
          cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
				});
			}	else{
       // 模糊搜索
       _this.search_fuzzy()
			}
    },
    	// 模糊搜索事件
      search_fuzzy: function(){
        $('body').on("input",'#orgId',function(event){
          var _this = $(this)
          cjqt.search_fuzzy.event_input(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
        });
        $('body').on("focus",'#orgId',function(event){
          var _this = $(this)
          cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
        });
        $('body').on('blur','#orgId',function(event) {
          var _this = $(this)
          cjqt.search_fuzzy.event_blur(_this,'org__id')
        });
        $('body').on('click','.select_wrap>.org__span', function(event) {
          event.preventDefault();
          event.stopPropagation();
          /* Act on the event */
          var _this = $(this)
          cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
        });
      },
		rendertable: function() {
			var _this = this;
			layui.use('table', function() {
				table = layui.table;
				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					 url: $("#contextPath").val() + "/notice/phoneMessage/getList",
					skin: 'nob' //行边框风格
						,
					even: true //开启隔行背景
						,
					size: 'lg' //小尺寸的表格
						,
					cols: [
						[{
							title: '序号',
							templet: '#indexTpl',
							width: 80
						}, {
							field: 'createTime',
							title: '时间',
							minWidth: 200
						}, {
							field: 'content',
							title: '内容',
							minWidth: 200
						}, {
							field: 'fullName',
							title: '编辑人',
							width: 120
						}, {
							field: 'state',
							title: '发布状态',
							width: 100,
							templet: function(data) {
								if (data.state == 0) {
									return "<span class='red'>未审核<span>"
								} else if (data.state == 1) {
									return '已发布'
								} else if (data.state == 2) {
									return '已驳回'
								} else if (data.state == 3) {
									return '原文链接'
								}
							}
						}, {
							field: 'approval_user',
							title: '审核人',
							width: 120
						}, {
							field: 'approval_time',
							title: '审核时间',
							minWidth: 200
						}, {
							field: 'id',
							title: '可操作',
							fixed: 'right',
							width: 260,
							align: 'center',
							templet: function(data) {
								var str = '';
								if (data.state == 0) {
									str += '<button class="t-btn t-red-btn t-sh-btn" data-id=' + data.id + ' data-type="1">审核</button>';
								}
								str += '<button class="t-btn t-red-btn t-xq-btn" data-id=' + data.id + ' data-type="3">详情</button>';
								
								if (permDelete == 1) {
									str += '<button class="t-btn t-white-btn t-delete-btn" data-id=' + data.id + ' data-type="2">删除</button>';
								}

								return str;
							}
						}]
					],
					id: 'testReload',
					page: true,
					where: { //设定异步数据接口的额外参数，任意设
						"orgId": $("#conditionform #orgId").attr('org__id')
					},
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
					},
					done: function(res, curr, count) {
						// 详情
						$('.t-xq-btn').on('click', function(event) {
							event.preventDefault();
							var id = $(this).attr('data-id')
							$.ajax({
								type: "post",
								url: $("#contextPath").val() + "/notice/emailSend/getDetailInfo",
								data: {
									id: id,
									type:1,
								},
								success: function(data) {
									var userList = []
									var stateStr = ''
									res = data.data
									userList = res.userList
									if(res.state == '0'){
										stateStr = '未审核'
									}else if(res.state == '1'){
										stateStr = '已发布'
									}else if(res.state == '2'){
										stateStr = '已驳回'
									}
									$("body").append(template.render(tpl.xqTpl)({
										res: res,
		            		personList: userList,
		            		personLen: userList.length,
		            		stateStr: stateStr
									}));
									// 确定
									$('.pop_sure_btn').on('click', function(event) {
										event.preventDefault();
										/* Act on the event */
										$('.mask').remove()
									});
								},
								error: function(error) {
									layer.msg('error')
								}
							});
						});
						// 审核
						$('.t-sh-btn').on('click', function(event) {
							event.preventDefault();
							var id = $(this).attr('data-id')
							$.ajax({
								type: "post",
								url: $("#contextPath").val() + "/notice/emailSend/getDetailInfo",
								data: {
									id: id,
									type:1,
								},
								success: function(data) {
									var userList = []
									var stateStr = ''
									res = data.data

									userList = res.userList
									if(res.state == '0'){
										stateStr = '未审核'
									}else if(res.state == '1'){
										stateStr = '已发布'
									}else if(res.state == '2'){
										stateStr = '已驳回'
									}
									$("body").append(template.render(tpl.shTpl)({
										res: res,
		            		personList: userList,
		            		personLen: userList.length,
		            		stateStr: stateStr
									}));
									// 确定审核
									$('.pop_sure_btn').on('click', function(event) {
										event.preventDefault();
										/* Act on the event */
										_this.eve_sure_sh(res)
									});
									// 消息字数监听
									$('#contnet_info').on('input', function(event) {
										event.preventDefault();
										/* Act on the event */
										var num = $(this).val().length
										$('.current_iofo_content_len').text(num+'/140')
									});
									// 目标用户选中监听
									$('.account_info').on('change', function(event) {
										event.preventDefault();
										var domCheckedlen = $('.account_info:checked').length
										$('.current_iofo_user_len').text(domCheckedlen+'人')
									});
								},
								error: function(error) {
									layer.msg('error')
								}
							});
						});
						//如果是异步请求数据方式，res即为你接口返回的信息。
						//查看详情
						$(".check-blue-btn").on("click", function() {
							var id = $(this).data("id");
							//显示详情弹窗
							_this.showDetailDialog(id)
						});
						//发布
						$(".t-publish-btn").on("click", function() {
							var id = $(this).data("id");
							var type = $(this).data("type")
							_this.publish(type, id, function() {
								table.reload('testReload', {
									url: $("#contextPath").val() + "/notice/phoneMessage/getList",
									where: { //设定异步数据接口的额外参数，任意设
										"c_beginTime": $("#c_startTime").val(),
										"c_endTime": $("#c_endTime").val(),
										"a_beginTime": $("#a_startTime").val(),
										"a_endTime": $("#a_endTime").val(),
										"state": $("#state").val(),
										"orgId": $("#conditionform #orgId").attr('org__id')
									},
									page: {
										curr: 1 //重新从第 1 页开始
									}
								});
							});
						});
						//删除
						$(".t-delete-btn").on("click", function() {
							var id = $(this).data("id");
							_this.delete(id, function() {
								table.reload('testReload', {
									url: $("#contextPath").val() + "/notice/phoneMessage/getList",
									where: { //设定异步数据接口的额外参数，任意设
										"c_beginTime": $("#c_startTime").val(),
										"c_endTime": $("#c_endTime").val(),
										"a_beginTime": $("#a_startTime").val(),
										"a_endTime": $("#a_endTime").val(),
										"state": $("#state").val(),
										"noticeType": $("#noticeType").val(),
										"orgId": $("#conditionform #orgId").attr('org__id')
									},
									page: {
										curr: 1 //重新从第 1 页开始
									}
								});
							});
						});
						$(".t-reject-btn").on("click", function() {
							var id = $(this).data("id");
							var type = $(this).data("type")
							_this.publish(type, id, function() {
								table.reload('testReload', {
									url: $("#contextPath").val() + "/notice/phoneMessage/getList",
									where: { //设定异步数据接口的额外参数，任意设
										"c_beginTime": $("#c_startTime").val(),
										"c_endTime": $("#c_endTime").val(),
										"a_beginTime": $("#a_startTime").val(),
										"a_endTime": $("#a_endTime").val(),
										"state": $("#state").val(),
										"orgId": $("#conditionform #orgId").attr('org__id')
									},
									page: {
										curr: 1 //重新从第 1 页开始
									}
								});
							});
						});
						//编辑
						$(".t-edit-btn").on("click", function() {
							var id = $(this).data("id");
							window.location.href = contextPath + '/notice/msgPublish?id=' + id;
						})
					}
				});
				//查询
				$('#conditionform  .search-btn').on('click', function() {
					table.reload('testReload', {
						url: $("#contextPath").val() + "/notice/phoneMessage/getList",
						where: { //设定异步数据接口的额外参数，任意设
							"c_beginTime": $("#c_startTime").val(),
							"c_endTime": $("#c_endTime").val(),
							"a_beginTime": $("#a_startTime").val(),
							"a_endTime": $("#a_endTime").val(),
							"state": $("#state").val(),
							"orgId": $("#conditionform #orgId").attr('org__id')
						},
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				});
			});
		},
		// 确定审核事件
		eve_sure_sh: function(res){
			var userList = res.userList
			var contactwayArr = []
			var content =  $('#contnet_info').val()
			var isPass = $(".radio-item.status:checked").data("status")
			var auditOpinion = $('#contnet_suggest').val()
			var dom = $('.account_info')
			var domCheckedlen = $('.account_info:checked').length
			$.each(dom,function(index, el) {
				if($(el).is(':checked')){
					contactwayArr.push($(el).attr('contactway'))
				}
			});
			var realUserList = userList.filter(function(item, index, arr) {
				return (contactwayArr.indexOf(item.contactWay) >- 1)
			})
			
			if(domCheckedlen <= 0){
				layer.msg('请选择目标用户');
				return
			}
			if(!content){
				layer.msg('请输入短信内容');
				return
			}
			var formdata = new FormData();
			formdata.append("id", res.id)
			formdata.append("type", 1)
			formdata.append("content", content)
			formdata.append("isPass", isPass)
			formdata.append("auditOpinion", auditOpinion)
			formdata.append("usersList", JSON.stringify(realUserList))
			$.ajax({
        type: "post",
        url: $("#contextPath").val() + "/notice/emailSend/approvalSend",
        data: formdata,
        cache: false, // 不缓存
        processData: false, // 告诉jQuery不要去处理发送的数据
        contentType: false, // 告诉jQuery不要去设置Content-Type请求头	
        success: function (data) {
          if (data.code == 200) {
          	layer.msg('审核完成')
          	$('.mask').remove()
          	table.reload('testReload', {
							url: $("#contextPath").val() + "/notice/phoneMessage/getList",
							where: { //设定异步数据接口的额外参数，任意设
								"c_beginTime": $("#c_startTime").val(),
								"c_endTime": $("#c_endTime").val(),
								"a_beginTime": $("#a_startTime").val(),
								"a_endTime": $("#a_endTime").val(),
								"state": $("#state").val(),
								"orgId": $("#conditionform #orgId").attr('org__id')
							},
							page: {
								curr: 1 //重新从第 1 页开始
							}
						});

          } else {
            layer.msg(data.msg)
          }
        },
        error: function () {
          // layer.msg('系统繁忙.....')
        }
      });
		},
		/**
		 * 显示详情弹窗
		 * @param id 
		 */
		showDetailDialog: function(id) {
			var _this = this;
			_this.ajaxDetail(id, function(data) {
				var phones = data.phones.split(",");
				var content = data.content;
				$("body").append(template.render(tpl.detailTpl)({
					phones: phones,
					content: content
				}));
				//关闭弹窗
				$(".close-btn").on("click", function() {
					$(".dialog-wp").remove();
				})
			})
		},
		ajaxDetail: function(id, callback) {
			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) {
						callback(data.data);
					} else {
						layer.msg(data.msg)
					}
				},
				error: function(error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 发布弹窗
		 * @param type 1为发布 2为驳回
		 * @param id 数据id
		 */
		publish: function(type, id, callback) {

			var _this = this;
			if (type == 1) {
				layer.confirm('确定发布?', {
					btn: ['确定', '取消']
				}, function(index, layero) {
					layer.close(index); //如果设定了yes回调，需进行手工关闭
					_this.ajaxPublish(type, id, callback);
				}, function(index) {

				});
			} else {
				layer.confirm('确定驳回?', {
					btn: ['确定', '取消']
				}, function(index, layero) {
					layer.close(index); //如果设定了yes回调，需进行手工关闭
					_this.ajaxPublish(type, id, callback);

				}, function(index) {

				});
			}
		},
		/**
		 * 删除
		 * @param type
		 * @param id
		 * @param callback
		 */
		delete: function(id, callback) {
			var _this = this;
			layer.confirm('确定删除?', {
				btn: ['确定', '取消']
			}, function(index, layero) {
				layer.close(index); //如果设定了yes回调，需进行手工关闭
				_this.ajaxDelete(id, callback);
			}, function(index) {

			});

		},

		/**
		 * 删除公告
		 * @param id 数据id
		 */
		ajaxDelete: function(id, callback) {
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/phoneMessage/deleteNotice",
				data: {
					"id": id
				},
				success: function(data) {
					var data = JSON.parse(data);
					if (data.code == '200') {
						layer.msg('删除成功！')
						callback();
					} else {
						layer.msg(data.msg)
					}
				},
				error: function(error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 发布请求
		 * @param type 1为发布 2为驳回
		 * @param id 数据id
		 */
		ajaxPublish: function(type, id, callback) {
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/notice/phoneMessage/approval",
				data: {
					"id": id,
					"state": type
				},
				success: function(data) {
					var data = JSON.parse(data);
					if (data.code == '200') {
						if (type == 1) {
							layer.msg('发布成功！')
						} else {
							layer.msg('驳回成功！')
						}
						callback();
					} else {
						layer.msg(data.msg)
					}
				},
				error: function(error) {
					layer.msg('error')
				}
			});
		}
	};
	appSend.init();
})