
var permDelete = $("#perm-delete").val();//删除权限
var permEdit = $("#perm-edit").val();//编辑权限
var permApprove = $("#perm-approve").val();//审核权限
var userType = $("#userType").val();
var companyArr = []; // 运营中心列表
var companyId = '';
var orgArr = []; // 项目列表
/**
 * 短信消息发布公告审核
 * 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>\
						<div class="dialog-temp-wp clearfloat">\
							<span class="temp-part">审核类型：<span><%=approvalTypeName%></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 if(data1.receive_type==2){%>\
									<div class="p-item">项目部分用户</div>\
									<% for(var i=0;i<data5.length;i++){%>\
										<span class="p-item"><%=data5[i].name + data5[i].mobile%><%if(i!=data5.length-1){%>、<%}%></span>\
									<%}%>\
								<%}else if(data1.receive_type==3){%>\
									<% for(var i=0;i<data5.length;i++){%>\
										<span class="p-item"><%=data5[i].name%><%if(i!=data5.length-1){%>、<%}%></span>\
									<%}%>\
								 <%}else if(data1.receive_type==4){%>\
									<div class="p-item">按部分分组发放</div>\
									<% for(var i=0;i<deptGroupList.length;i++){%>\
										<span class="p-item"><%=deptGroupList[i].name%><%if(i!=deptGroupList.length-1){%>、<%}%></span>\
									<%}%>\
									<%}%>\
							</div>\
						</div>\
						<ul class="dialog-wx-list">\
							<% for(var i=0;i<auditList.length;i++){%>\
							<li class=" clearfloat">\
								<span class="w-i-tips">审核人:</span>\
								<span class="w-i-approve"><%=auditList[i].approvalUser%></span>\
							</li>\
							<li class=" clearfloat">\
								<span class="w-i-tips">审核时间:</span>\
								<span class="w-i-approve"><%=auditList[i].approvalTime%></span>\
							</li>\
							<li class=" clearfloat">\
								<span class="w-i-tips">审核结果:</span>\
								<span class="w-i-approve"><%=auditList[i].approvalResult==1?"通过":"不通过"%></span>\
							</li>\
							<li class="clearfloat">\
								<span class="w-i-tips">审核意见:</span>\
								<span class="w-i-approve"><%=auditList[i].approvalOpinion%></span>\
							</li>\
							<%}%>\
						</ul>\
					</div>\
				</div>\
			</div>	',
			"typeTpl": '<option value="">选择审核类型</option>\
			<% for(i=0;i<data.length;i++){%> \
				<option value="<%=data[i].id%>"><%=data[i].name%></option>\
			 <%}%>'
	};
	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("")

				let contextPathURL = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
				if (userType == -1||userType == 1 || userType == 2|| userType == 6) {
					$("#conditionform input").val("");
					$('#comdId').val(companyArr[0].label).attr('comd__id', companyArr[0].value).attr('meetCode', companyArr[0].meetCode);
					companyId = $("#conditionform #comdId").attr('comd__id');
					_this.setOrgData(contextPathURL);
				} else {
					$("#conditionform input:not('#orgId')").val("");
					companyId = localStorage.getItem("companyId")
					_this.setOrgData(contextPathURL);
				}
			})

			let contextPathURL = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
			if (userType == -1||userType == 1 || userType == 2|| userType == 6) {
				_this.getCompanyList({}, contextPathURL)
				$('body').on("focus", '#comdId', function (event) {
					_this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
				});
				$('body').on('blur', '#comdId', function (event) {
					var _that = $(this)
					cjqt.search_fuzzy.event_blur(_that, 'comd__id')
				});
				$('body').on('click', '.select_wrap>.comd__span', function (event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _that = $(this)
					cjqt.search_fuzzy.event_click(_that, 'comd__id', '#comdId')
					companyId = $("#conditionform #comdId").attr('comd__id')
					_this.setOrgData(contextPathURL);
				});
				$('body').on("input",'#comdId',function(event){ // input内容变化执行
					_this.setFuzzyFilter($('#comdId').val(), companyArr, backData => {
						_this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , backData);
					})
				});
			} else {
				companyId = localStorage.getItem("companyId")
				_this.setOrgData(contextPathURL);
			}
    },
	setOrgData: function (contextPathURL) {
		var _this = this;
		_this.getOrgList({
			pageNo: 1,
			pageSize: 9999,
			"conditions[companyId]": companyId
		}, contextPathURL)
		$('body').on("focus", '#orgId', function (event) {
			_this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span', orgArr);
		});
		$('body').on('blur', '#orgId', function (event) {
			var _that = $(this)
			cjqt.search_fuzzy.event_blur(_that, 'org__id')
		});
		$('body').on('click', '.select_wrap>.org__span', function (event) {
			event.preventDefault();
			event.stopPropagation();
			/* Act on the event */
			var _that = $(this)
			cjqt.search_fuzzy.event_click(_that, 'org__id', '#orgId')
		});
		$('body').on("input", '#orgId', function (event) {
			_this.setFuzzyFilter($('#orgId').val(), orgArr, backData => {
				_this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span', backData);
			})
		});
	},
	// 获取运营中心数据
	getCompanyList: function (obj, contextPathURL) {
		var _this = this;
		companyArr = [];
		$.ajax({
			url: contextPathURL + '/api/organisation/company/getselectlist',
			type: "POST",
			dataType: "json",
			data: obj,
			success: function (data) {
				if (data.code == 200 && data.data) {
					companyArr = data.data;
					_this.setInputData($('#comdId'), 'comd__id', 'comd__span', companyArr);
					companyId = $("#conditionform #comdId").attr('comd__id')
					_this.setOrgData(contextPathURL);
				} else {
					layer.msg(data.msg);
				}
			}
		});
	},
	// 获取项目数据
	getOrgList(obj, contextPathURL) {
		var _this = this;
		orgArr = [];
		$.ajax({
			url: contextPathURL + '/api/organisation/organization/getselectlist',
			type: "POST",
			dataType: "json",
			data: obj,
			success: function (data) {
				if (data.code == 200 && data.data) {
					orgArr = data.data;
					_this.setInputData($('#orgId'), 'org__id', 'org__span', orgArr);
					if(orgArr.length==1){
						_this.getIfCanApproval(data.data[0].value)
					}
				} else {
					layer.msg(data.msg);
				}
			}
		});
	},
	setInputData: function (_this, attrName, liClassName, dataArr) {
		// 先清空
		_this.attr(attrName, '')
		var html = ''
		if (dataArr.length) {
			_this.val(dataArr[0].label).attr(attrName, dataArr[0].value).attr('meetCode', dataArr[0].meetCode);
			if (attrName == 'org__id') {
				console.log('是否执行查询')
				$('#conditionform .search-btn').click();
			}
			$.each(dataArr, function (index, el) {
				var meetCode = el.meetCode || ''
				html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
				html += el.label
				html += '</span>'
			});
			_this.parent().find('.select_wrap').empty().append(html);
		} else {
			_this.val('').attr(attrName, '').attr('meetCode', '');
			_this.parent().find('.select_wrap').empty().hide()
		}
	},
	setOrgCompanyData: function (_this, attrName, liClassName, dataArr) {
		var html = ''
		if (dataArr.length) {
			_this.parent().find('.select_wrap').show()
			$.each(dataArr, function (index, el) {
				var meetCode = el.meetCode || ''
				html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
				html += el.label
				html += '</span>'
			});
			_this.parent().find('.select_wrap').empty().append(html)
		} else {
			_this.parent().find('.select_wrap').empty().hide()
		}
	},
	setFuzzyFilter: function (strLabel, dataArr, backData) {
		const fuzzyArr = dataArr; // 内容省略
		const objArr = [];
		fuzzyArr.forEach(item => {
			if (item.label.includes(strLabel)) {
				objArr.push(item);
			}
		});
		backData(objArr);
	},
	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')
			}
		});
	},
	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){//显示审核下拉列表
						$(".approvalStyle").show();
						_this.getApprovalTypeList(orgId)
					}else{////不显示审核下拉列表
						$(".approvalStyle").hide();
					}
				} else {
					layer.msg(data.msg)
				}
			},
			error: function (error) {
				layer.msg('error')
			}
		});
	},
		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: 'roleName',
							title: '当前审核角色',
							width: 100
						},{
							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: 300,
							align: 'center',
							templet: function (data) {
								var str = '';
								//做测试的两条数据
                                if (data.state == 0) {
                                    if (permApprove == 1) {
                                    	if(data.isApproval==1){
                                    		str += '<button class="t-btn t-red-btn t-sh-btn" data-id=' + data.id + ' data-type="2">审核</button>';
                                    	}else if(data.approvalType==0){
                                    		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>';
								}
								str += '<button class="t-btn t-red-btn check-blue-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(),
											"approvalType": $("#approvalType").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(),
										"approvalType": $("#approvalType").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(),
										"approvalType": $("#approvalType").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;
						});

						//审核
						$(".t-sh-btn").on("click",function(){
							//这个版本 审核还可以编辑内容
							var id = $(this).data("id");
                          	location.href= contextPath + "/notice/appNotice/redirectToWXApprovel?id="+id;
						});
					}
				});
				//查询
				$('#conditionform  .search-btn').on('click', function () {
					var org_Id = $("#conditionform #orgId").attr('org__id');
					if (!org_Id&&userType!=1&&userType!=2&&userType != -1) {
						layer.msg('请选择项目')
						return;
					}
					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(),
							"approvalType": $("#approvalType").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(data.code == '400'){
						layer.msg('发布成功！'+data.msg)
					} else {
						if (type == 1) callback && callback();
						layer.msg(data.data)
					}
				},
				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();
})
