
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 auditNoticePermission = $("#auditNoticePermission").val();
	var tpl = {
		"detailTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-wx-con">\
					<div class="title-wp">\
						<span>消息详情</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-wx-wp clearfloat">\
						<div class="dialog-temp-wp clearfloat">\
							<span class="temp-part">公众号：<span><%=data3.name%></span></span>\
							<span class="temp-part">消息模板：<span><%=data4.name%></span></span>\
							\
						</div>\
						<ul class="dialog-wx-list">\
							<% for(var i=0;i<data2.length;i++){%>\
							<li class="dialog-wx-item clearfloat">\
								<span class="w-i-tips"><%=data2[i].name%></span>\
								<input type="text" class="w-i-input" readonly value="<%=data2[i].value%>"/>\
							</li>\
							<%}%>\
						</ul>\
						<div class="persons-wp clearfloat" >\
							<div class="p-tip" >发送对象</div>\
							<div class="p-list">\
								<%if(data1.receive_type==1){%>\
									<div class="p-item">校区所有用户</div>\
								<%}else{%>\
									<% for(var i=0;i<data5.length;i++){%>\
										<span class="p-item"><%=data5[i].name%><%if(i!=data5.length-1){%>、<%}%></span>\
									<%}%>\
								<%}%>\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>	'
	};
	var contextPath = $("#contextPath").val()
	var appSend = {
		init: function () {
			this.render();
			this.bindEvent();
		},
		render: function () {
			this.rendertable();
			//				$("body").append(template.render(tpl.detailTpl));
		},
		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("");
				}    
			})
      // // 模糊搜索
			// _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 () {
				var table = layui.table;

				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: contextPath + "/notice/wxtemplateMessage/getList",
					skin: 'nob' //行边框风格
			    		  ,even: true //开启隔行背景
			    		  ,size: 'lg' //小尺寸的表格
					,cols: [
						[ {
                            title: '序号',
                            templet: '#indexTpl',
                            width: 80
                        } ,{
							field: 'createTime',
							title: '时间',
							minWidth: 200
						}, {
							field: 'title',
							title: '标题',
							minWidth: 200
						}, {
							field: 'name',
							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: '详情',
							width: 120,
							templet: function (data) {
								return "<div data-id=" + data.id + "  class='check-blue-btn'>查看详情</div>"
							}
						}, {
							field: 'id',
							title: '可操作',
							fixed: 'right',
							width: 260,
							align: 'center',
							templet: function (data) {
								var str = '';

                                if (data.state == 0) {
                                    if (permApprove == 1) {
                                        str += '<button class="t-btn t-red-btn t-publish-btn" data-id=' + data.id + ' data-type="1">发布</button>';
                                        str += '<button class="t-btn t-white-btn t-reject-btn" data-id=' + data.id + ' data-type="2">驳回</button>';
                                    }
                                    if (permEdit == 1) {
                                        str += '<button class="t-btn t-red-btn t-edit-btn" data-id=' + data.id + ' data-type="2">编辑</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) {
						//如果是异步请求数据方式，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 + "/notice/wxtemplateMessage/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 + "/notice/wxtemplateMessage/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 + "/notice/wxtemplateMessage/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/wxPublish?id='+id;
						})
					}
				});
				//查询
				$('#conditionform  .search-btn').on('click', function () {
					table.reload('testReload', {
						url: contextPath + "/notice/wxtemplateMessage/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 页开始
						}
					});
				});
				//状态筛选
//				$(".filter-btn-item").on("click", function () {
//					$(this).addClass("active").siblings().removeClass("active");
//					table.reload('testReload', {
//						where: { //设定异步数据接口的额外参数，任意设
//							"c_beginTime": $("#c_startTime").val(),
//							"c_endTime": $("#c_endTime").val(),
//							"a_beginTime": $("#a_startTime").val(),
//							"a_endTime": $("#a_endTime").val(),
//							"state": $(".filter-btn-item.active").data("type")
//						},
//						page: {
//							curr: 1 //重新从第 1 页开始
//						}
//					});
//				})
			});
		},
		/**
		 * 显示详情弹窗
		 * @param id 
		 */
		showDetailDialog: function (id) {
			var _this = this;
			_this.ajaxDetail(id, function (data) {
				$("body").append(template.render(tpl.detailTpl)(data));
				//关闭弹窗
				$(".close-btn").on("click", function () {
					$(".dialog-wp").remove();
				})
			})
		},
		ajaxDetail: function (id, callback) {
			var _this = this;
			$.ajax({
				type: "post",
				url: contextPath + "/notice/wxtemplateMessage/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 1为发布 2为驳回
		 * @param id 数据id
		 */
		ajaxPublish: function (type, id, callback) {
			$.ajax({
				type: "post",
				url: contextPath + "/notice/wxtemplateMessage/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 {
						if (type == 1) callback && callback();
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
        /**
         * 删除
         * @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 + "/notice/wxtemplateMessage/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')
                }
            });
        },
	};
	appSend.init();
})