$(function () {
	var ERROK = 200;
	var contextPath = $("#contextPath").val()
	var table;
	var orgList = [];
	var addressList = [];
	var companyList = [];
	//记录选中的数据:做缓存使用,作为参数传递给后台
	var ids = [];
	var idsArr = [];
	//当前表格中的全部数据:在表格的checkbox全选的时候没有得到数据, 因此用全局存放变量
	var table_data = [];
	template.config("escape", false);
	var orgId = "";
	var tpl = {
		"updateTpl": '<div class="dialog-wp">\
						<div class="mask"></div>\
						<div class="dialog dialog-account-con">\
							<div class="title-wp">\
								<span>修改账号</span>\
								<span class="close-btn"></button>\
							</div>\
							<div class="dialog-account-wp ">\
					 			<div class="account-list">\
									 <div class="account-item required clearfloat" style="display: none">\
										<div class="item-tip"><span class="red">*</span>校区：</div>\
										<div class="item-con">\
											<input type="hidden" id="orgId" value="<%=orgId %>" org__id="<%=orgId %>"/>\
										</div>\
									</div>\
									<div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>企业：</div>\
										<div class="item-con">\
											<select id ="companyUpdate" class="item-select company-id" disabled com__id="<%=virtualArchId%>">\
												<option value="">请选择企业</option>\
												<%if(companyList){%>\
												<%for(var i=0;i<companyList.length;i++){%>\
													<option value="<%=companyList[i].id%>" <%if(virtualArchId==companyList[i].id){%> selected <%}%> ><%=companyList[i].name%></option>\
												<%}%>\
												<%}%>\
											</select>\
									 	</div>\
									</div>\
									 <div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>部门：</div>\
										<div class="item-con">\
											\
											 <select class="item-select dept" disabled dep__id="<%=dept%>">\
												<option value="">请选择部门</option>\
													<option value="<%=dept%>" selected ><%=deptStr%></option>\
											</select>\
										</div>\
									</div>\
									<div class="account-item required clearfloat">\
									<div class="item-tip"><span class="red">*</span>手机号码：</div>\
									<div class="item-con">\
										<input  type="text" class="item-input mobile-phone" placeholder="请输入手机号码" value="<%=mobile %>" readonly>\
									</div>\
								</div>\
									 <div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>姓名：</div>\
										<div class="item-con">\
											<input  type="text" class="item-input user-name" placeholder="请输入姓名" value="<%=userName %>" readonly>\
										</div>\
									</div>\
									<div class="account-item clearfloat required">\
										<div class="item-tip "><span class="red"></span>识别图片：</div>\
										<div class="item-con">\
											<div class="photo-list-wp clearfloat">\
												<div class="photo-list clearfloat">\
												<%if(facePicList){%>\
													<%for(var i=0;i<facePicList.length;i++){%>\
														<div class="photo-item" data-imageid="<%=facePicList[i].imageId%>">\
															<div class="photo-item-img" style="background-image: url(<%=serveImgUrl+facePicList[i].imageUrl%>)"></div>\
															<div class="del-btn"></div>\
														</div>\
													<%}%>\
													<%}%>\
												</div>\
												\
											</div>\
										</div>\
									</div>\
									<div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>积分余额：</div>\
										<div class="item-con">\
											<input  type="number" class="item-input integral-balance" placeholder="请输入积分余额" value="<%=integrale %>" onkeyup="this.value=this.value.replace(/^\d+$/,&apos;&apos;);">\
										</div>\
									</div>\
									 <div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>送餐地址：</div>\
										<div class="item-con">\
											\
											 <select class="item-select dinner-address">\
												<option value="">请选择送餐地址</option>\
												<%if(addressList){%>\
												<%for(var j=0;j<addressList.length;j++){%>\
													<option value="<%=addressList[j].id%>" <%if(addressList[j].id==address){%> selected <%}%> ><%=addressList[j].itemname%></option>\
												<%}%>\
												<%}%>\
											</select>\
										</div>\
									</div>\
									 <div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>类型：</div>\
										<div class="item-con">\
											 <div class="radio-wp">\
											   <span class="radio-input">\
												 <input type="radio" id="zu" class="radio-item user-type" data-status="2" name="userType" <%if(roleType==2){%>checked<%}%>/>\
												  <span class="radio-inner"></span>\
											   </span>\
											   <label class="radio-con" for="zu">个人账号</label>\
											</div>\
											 <div class="radio-wp">\
											   <span class="radio-input">\
												 <input type="radio" id="zu1" class="radio-item user-type" data-status="1" name="userType" <%if(roleType==1){%>checked<%}%>/>\
												  <span class="radio-inner"></span>\
											   </span>		\
											   <label class="radio-con" for="zu1">管理员</label>\
											</div>\
											<div class="radio-wp">\
											<span class="radio-input">\
											<input type="radio" id="zu2" class="radio-item user-type" data-status="3" name="userType" <%if(roleType==3){%>checked<%}%>/>\
											 <span class="radio-inner"></span>\
											</span>		\
											<label class="radio-con" for="zu2">可被代订</label>\
									 </div>\
										</div>\
									</div>\
					 			</div>\
								 <div class="dialog-btns">\
									<button class="sure-add-btn btn-red">确定</button>\
								</div>\
							</div>\
						</div>\
					</div>	',
		"photoTpl": '<div class="photo-item" data-url="<%=imageUrl%>">\
					<div class="photo-item-img" style="background-image: url(<%=url%>)"></div>\
					<div class="del-btn"></div>\
				</div>',
		"rechargeTpl": '<div class="dialog-wp">\
						<div class="mask"></div>\
						<div class="dialog dialog-account-con">\
							<div class="title-wp">\
								<span>自动充值</span>\
								<span class="close-btn"></button>\
							</div>\
							<div class="dialog-account-wp ">\
					 			<div class="account-list recharge-wp">\
									 \
									 <% if(orgList!=null&&orgList.length>1){ %>\
										 <div class="account-item required clearfloat">\
											<div class="item-tip"><span class="red">*</span>校区：</div>\
											<div class="item-con">\
											<input class="item-select organ-id" name="orgId" id="orgId" org__id="<%=orgList[0].id%>" autocomplete="off" value="<%=orgList[0].name%>"/>\
		              						<span class="select_wrap _hide"></span>\
										 	</div>\
										</div>\
									<%}else{%>\
										 <div class="account-item required clearfloat" style="display: none">\
											<div class="item-tip"><span class="red">*</span>校区：</div>\
											<div class="item-con">\
												<input type="hidden" id="orgId" value="<%=orgId%>" org__id="<%=orgId%>"/>\
										 	</div>\
										</div>\
									<%}%>\
									 <div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>开启自动充值：</div>\
										<div class="item-con">\
											 <div class="radio-wp">\
											   <span class="radio-input">\
												 <input type="radio" id="zu" class="radio-item recharge-status recharge-status-1" data-status="1" name="status" <%if(data && data.reSetDto.status==1){%> checked <%}else if(!data){%> checked <%}%>/>\
												  <span class="radio-inner"></span>\
											   </span>		\
											   <label class="radio-con" for="zu">上架</label>\
											</div>\
											 <div class="radio-wp">\
											   <span class="radio-input">\
												 <input type="radio" id="zu1" class="radio-item recharge-status recharge-status-0" data-status="0" name="status" <%if(data && data.reSetDto.status==0){%> checked <%}%>/>\
												  <span class="radio-inner"></span>\
											   </span>		\
											   <label class="radio-con" for="zu1">下架</label>\
											</div>\
										</div>\
									</div>\
									<div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>单日数量：</div>\
										<div class="item-con">\
											<input  type="text" class="item-input day-count" placeholder="请输入单日数量" value="<%if(data){%><%=data.reSetDto.dayCount%><%}%>"  min="1" oninput="this.value = this.value.replace(/[^0-9]/g, \'\');">\
											<div class="rechage-tip">开启自动充值后每月1日00:10:00,系统会为所有有效账户（不包括禁用账户）充值单日数量*当月工作日数的积分。</div>	\
										</div>\
									</div>\
									<%if(type ==1){%>\
										 <div class="account-item required clearfloat">\
											<div class="item-tip"><span class="red">*</span>自动充值记录：</div>\
											<div class="item-con record-item-con " data-id="<%if(data){%><%=data.reSetDto.id%><%}%>">\
												<%if(data && data.recordList){%>\
													<ul class="recharge-record-list">\
														<%for(var i=0;i<data.recordList.length;i++){%>\
															<li class="recharge-record-item"><%=data.recordList[i].createTime%>&nbsp;&nbsp; +<%=data.recordList[i].sumCount%></li>\
														<%}%>\
													</ul>\
												<%}else{%>\
													<div class="no-record">暂无充值记录</div>\
												<%}%>\
											</div>\
										</div>\
									<%}else{%>\
										 <div class="account-item required clearfloat">\
											<div class="item-tip"><span class="red">*</span>自动充值记录：</div>\
											<div class="item-con record-item-con">\
												\
												<div class="no-record">暂无充值记录</div>\
											</div>\
										</div>\
									<%}%>\
					 			</div>\
								 <div class="dialog-btns">\
									<button class="sure-recharge-btn btn-red">确定</button>\
								</div>\
							</div>\
						</div>\
					</div>	',
		"recordTpl": '<%if(!!data && !!data.recordList){%>\
								<ul class="recharge-record-list">\
									<%for(var i=0;i<data.recordList.length;i++){%>\
										<li class="recharge-record-item"><%=data.recordList[i].createTime%>&nbsp;&nbsp; +<%=data.recordList[i].sumCount%></li>\
									<%}%>\
								</ul>\
							<%}else {%>\
								<div class="no-record">暂无充值记录</div>\
							<%}%>',
		"batchRechargeTpl": '<div class="dialog-wp">\
						<div class="mask"></div>\
						<div class="dialog dialog-account-con">\
							<div class="title-wp">\
								<span>批量充值</span>\
								<span class="close-btn"></button>\
							</div>\
							<div class="dialog-account-wp ">\
					 			<div class="account-list recharge-wp">\
									 \
									\
										 <div class="account-item required clearfloat" style="display: none">\
											<div class="item-tip"><span class="red">*</span>校区：</div>\
											<div class="item-con">\
												<input type="hidden" id="orgId" value="<%=orgId%>" org__id="<%=orgId%>"/>\
										 	</div>\
										</div>\
									\
									<div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>充值数量：</div>\
										<div class="item-con">\
											<input  type="text" class="item-input integral" placeholder="请输入充值数量" value="" min="1"  oninput="this.value = this.value.replace(/[^0-9]/g, \'\');">\
											<div class="rechage-tip">确认提交后，会为所有充值账号充值输入数量的积分</div>	\
										</div>\
									</div>\
									 <div class="account-item required clearfloat">\
										<div class="item-tip"><span class="red">*</span>充值账号：</div>\
										<div class="item-con record-item-con">\
											<ul class="recharge-record-list">\
												<%for(var j=0;j<personList.length;j++){%>\
													<%if(personList[j].isEnabled ==1){%>\
														<li class="recharge-record-item"  data-id="<%=personList[j].id%>"><%=personList[j].userName%>&nbsp;&nbsp;<%=personList[j].mobile%><span class="del-btn" data-id="<%=personList[j].id%>">删除</span></li>\
													<%}%>\
												<%}%>\
											</ul>\
											<div class="sum-wp">共计：<span class="sum"><%=personList.length%>人</span></div>\
										</div>\
									</div>\
					 			</div>\
								 <div class="dialog-btns">\
									<button class="sure-batch-recharge-btn btn-red">确定</button>\
								</div>\
							</div>\
						</div>\
					</div>	'
	};
	var api = {
		init: function () {
			this.render();
			this.bindEvent();
		},
		render: function () {
			this.rendertable();
			this.itemAjax();
		},
		bindEvent: function () {
			var _this = this;
			layui.use('laydate', function () {
				var laydate = layui.laydate;
				//执行一个laydate实例
				laydate.render({
					elem: '#beginTime' //提交开始时间
				});
				laydate.render({
					elem: '#endTime' //提交结束时间
				});
			});
			//重置
			$(".set-btn").on("click", function () {
				idsArr = []; //清空之前选择的数据
				var $orgId = $("#conditionform  .single-orgid");
				var $dom = $("#conditionform input,#conditionform select")
				if($orgId.length){
					$dom.val("").removeAttr('com__id dep__id')
				}else{
					$dom.val("").removeAttr('org__id com__id dep__id')
				}
				_this.againRenderTable({type:1});
			});
			//自动充值
			$(".auto-recharge").on("click", function () {
				if ($("#conditionform  .single-orgid").length) {
					var orgId = $("#conditionform  .single-orgid").val();
					_this.getAutoSetting(orgId, function (data) {
						$("body").append(template.render(tpl.rechargeTpl)({
							orgList: orgList,
							orgId: orgId,
							data: data,
							type: 1
						}))
						//关闭弹窗
						$(".close-btn").on("click", function () {
							$(".dialog-wp").remove();
						});
						//确定充值
						$(".sure-recharge-btn").on("click", function () {
							_this.saveRecharge(function () {
								$(".dialog-wp").remove();
								layer.msg("设置成功！")
								_this.againRenderTable();
							})
						})
					})
				} else {
					$("body").append(template.render(tpl.rechargeTpl)({
						orgList: orgList,
						type: 2
					}))
				};
				//关闭弹窗
				$(".close-btn").on("click", function () {
					$(".dialog-wp").remove();
				});
				//多校区
				$(".recharge-wp #orgId").on("change", function () {
					var that = $(this)
					setTimeout(function(){
						var orgId = that.attr('org__id');
						_this.getAutoSetting(orgId, function (data) {
							if (!data) {
								$(".recharge-status-1").prop("checked", true);
								$(".recharge-status-0").prop("checked", false);
								$(".day-count").val("");
								$(".item-con.record-item-con").data("id", "")
								$(".item-con.record-item-con").html(template.render(tpl.recordTpl)({
									data: data
								}))
							} else {
								if (data.reSetDto.status == 1) {
									$(".recharge-status-1").prop("checked", true);
									$(".recharge-status-0").prop("checked", false);
								} else {
									$(".recharge-status-1").prop("checked", false);
									$(".recharge-status-0").prop("checked", true);
								};
								//							console.log(!!data && !!data.recordList)
								$(".item-con.record-item-con").data("id", data.reSetDto.id)
								$(".day-count").val(data.reSetDto.dayCount);
								$(".item-con.record-item-con").html(template.render(tpl.recordTpl)({
									data: data
								}))
							}
						})
					},200)
				})
				//确定充值
				$(".sure-recharge-btn").on("click", function () {
					_this.saveRecharge(function () {
						$(".dialog-wp").remove();
						layer.msg("设置成功！")
						_this.againRenderTable();
					})
				})
			})
			//批量充值
			$(".batch-recharge").on("click", function () {
				console.log(idsArr);
				//				var checkStatus = table.checkStatus('testReload');
				var checkStatus = idsArr;
				if (checkStatus.length == 0) {
					layer.msg("请先选择充值人");
					return false
				};
				var orgId = $("#conditionform  #orgId").attr('org__id');

				//				console.log(checkStatus.data) //获取选中行的数据
				$("body").append(template.render(tpl.batchRechargeTpl)({
					orgList: orgList,
					personList: checkStatus,
					orgId: orgId
				}))
				$(".sum-wp .sum").html($(".recharge-record-item").length + "人");
				//关闭弹窗
				$(".close-btn").on("click", function () {
					$(".dialog-wp").remove();
				});
				//确定充值
				$(".sure-batch-recharge-btn").on("click", function () {
					_this.saveBatchRecharge(checkStatus.data, function () {
						$(".dialog-wp").remove();
						layer.msg("充值成功！")
						_this.againRenderTable();
					})
				});
				$(".recharge-record-item .del-btn").on("click", function () {
					if ($(".recharge-record-item").length > 1) {
						$(this).closest(".recharge-record-item").remove();
						$(".sum-wp .sum").html($(".recharge-record-item").length + "人")
					} else {
						layer.msg("至少充值1人！");
						return false;
					}

				})
				//				var checkStatus = table.checkStatus('testReload');
				//				console.log(checkStatus.data) //获取选中行的数据
				//				console.log(checkStatus.data.length) //获取选中行数量，可作为是否有选中行的条件
				//				console.log(checkStatus.isAll ) //表格是否全选
			})
			// 模糊搜索
			_this.search_fuzzy()
		},
		// 模糊搜索事件
		// 模糊搜索事件
		search_fuzzy: function(){
			var default_option = {
				org_attrName:'org__id',
				com_attrName:'com__id',
				dep_attrName:'dep__id',
				org_spanName:'org__span',
				com_spanName:'com__span',
				dep_spanName:'dep__span',
				org_path:'/admin/templ/getOrgListByName',
				com_path:'/admin/templ/getVirList',
				dep_path:'/admin/templ/getDept',
				contextPath:$("#contextPath").val()
			}
			var option_1 = $.extend(true,{},default_option,{
				org_target:'.default-select#orgId',
				com_target:'.default-select#companyId',
				dep_target:'.default-select#departmentId',
			});
			var option_2 = $.extend(true,{},default_option,{
				org_target:'.item-select.organ-id',
			});

			function eve(option_,otherOption){
				var obj = $.extend(true, {}, option_, otherOption);
				var type = obj.type
				var _path, _target, _attrName, _spanName
				if(type == 1){
					_path = obj.org_path
					_target = obj.org_target
					_attrName = obj.org_attrName
					_spanName = obj.org_spanName
				}else if(type == 2){
					_path = obj.com_path
					_target = obj.com_target
					_attrName = obj.com_attrName
					_spanName = obj.com_spanName
				}else if(type == 3){
					_path = obj.dep_path
					_target = obj.dep_target
					_attrName = obj.dep_attrName
					_spanName = obj.dep_spanName
				}
				$('body').on("input",_target,function(event){
					var _this = $(this)
					var obj_input = $.extend(true,{}, obj,{"_this":_this});
					cjqt.search_fuzzy.event_input(_this,_attrName,_spanName,contextPath,_path,obj_input)
				});
				$('body').on("focus",_target,function(event){
					var _this = $(this)
					var obj_focus = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_focus(_this,_attrName,_spanName,contextPath,_path,obj_focus)
				});
				$('body').on('blur',_target,function(event) {
					var _this = $(this)
					var obj_blur = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_blur(_this,_attrName,obj_blur)
				});
				$('body').on('click',_target+'~.select_wrap>.'+_spanName, function(event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _this = $(this)
					var obj_click = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_click(_this,_attrName,_target,obj_click)
				});

			}
			// 搜索联动
			eve(option_1,{type:1})
			eve(option_1,{type:2})
			eve(option_1,{type:3})
			// 自动充值
			eve(option_2,{type:1})
		},
		rendertable: function () {
			var _this = this;
			layui.use('table', function () {
				table = layui.table;
				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/admin/appUser/getConsumerList",
					method: "post",
					where: {
						orgId: $("#orgId").attr('org__id')
					},
					skin: 'nob' //行边框风格
						,
					even: true //开启隔行背景
						,
					size: 'lg' //小尺寸的表格
						,
					cols: [
						[{
								type: 'checkbox',
								fixed: 'left'
							},
							{
								field: 'index',
								title: '序号',
								width: '80',
								templet: '#indexTpl'
							}, {
								field: 'orgName',
								title: '校区',
								minWidth: 180
							},  {
								field: 'virName',
								title: '企业',
								minWidth: 180
							},  {
								field: 'dept',
								title: '部门',
								minWidth: 200
							}, {
								field: 'mobile',
								title: '手机号码',
								minWidth: 200
							}, {
								field: 'userName',
								title: '姓名',
								minWidth: 200
							}, {
								field: 'integral',
								title: '积分余额',
								minWidth: 200
							
							}, {
								field: 'address',
								title: '送餐地址',
								minWidth: 200
							}, {
								field: 'createTime',
								title: '创建时间',
								minWidth: 200

							}, {
								field: 'roleType',
								title: '类型',
								width: 120,
								templet: function (data) {
									//1管理员2普通用户
									if (data.roleType == 1) {
										return '管理员'
									} else if (data.roleType == 2) {
										return '普通用户'
									} else if (data.roleType == 3) {
										return '可被代订'
									}
								}
							}, {
								field: 'status',
								title: '状态',
								width: 120,
								templet: function (data) {
									//1启用0禁用
									if (data.isEnabled == 1) {
										return '启用'
									} else if (data.isEnabled == 0) {
										return '禁用'
									}
								}
							}, {

								title: '可操作',
								fixed: 'right',
								width: 150,
								align: 'center',
								templet: function (data) {
									var str = '';
									// if (data.passType == "2" && data.cardCode) {
									// 	str += '<button class="t-btn t-red-btn t-collection-btn" data-id=' + data.id + ' data-type="1" data-cardid =' + data.cardId + ' data-cardcode =' + data.cardCode + '>收卡</button>';
									// } else if (data.passType == "2" && !data.cardCode) {
									// 	str += '<button class="t-btn t-red-btn t-payment-btn" data-id=' + data.id + ' data-type="1">发卡</button>';
									// }
//									if (data.isEnabled == 1) {
//										str += '<button class="t-btn t-red-btn t-delete-btn" data-id=' + data.id + ' data-type="1">禁用</button>';
//									} else if (data.isEnabled == 0) {
//										str += '<button class="t-btn t-red-btn t-delete-btn" data-id=' + data.id + ' data-type="2">启用</button>';
//									}
									str += '<button class="t-btn t-red-btn t-edit-btn" data-id=' + data.id + '  >修改</button>';
//									str += '<button class="t-btn t-red-btn t-publish-btn" data-id=' + data.id + ' data-type="1" lay-event="detail" >详情</button>';

									return str;
								}
							}
						]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
							,
						msgName: 'msg' //规定状态信息的字段名称，默认：msg
					},
					request: {
						pageName: 'pageNo' //页码的参数名称，默认：page
							,
						limitName: 'pageSize' //每页数据量的参数名，默认：limit
					},
					where: {
						orgId: $("#conditionform  #orgId").attr('org__id'),
					},
					done: function (res, curr, count) {
					
						//隐藏禁选按钮
						var result = res.data;
						for (var i = 0; i < result.length; i++) {
							//							$(".laytable-cell-checkbox input").attr("disabled",true)
							if (result[i].isEnabled == 0) {
								$(".layui-table-fixed  .layui-table-body tbody tr").eq(i).find(".laytable-cell-checkbox ").css('visibility', 'hidden')
							}
						}
						//复现之前选择数据
						table_data = res.data;

						//在缓存中找到id ,然后设置data表格中的选中状态
						//循环所有数据，找出对应关系，设置checkbox选中状态
						for (var i = 0; i < res.data.length; i++) {
							for (var j = 0; j < idsArr.length; j++) {
								//数据id和要勾选的id相同时checkbox选中
								if (res.data[i].id == idsArr[j].id) {
									//这里才是真正的有效勾选
									res.data[i]["LAY_CHECKED"] = 'true';
									//找到对应数据改变勾选样式，呈现出选中效果
									var index = res.data[i]['LAY_TABLE_INDEX'];
									$('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
									$('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
								}
							}
						}
						//设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
						var checkStatus = table.checkStatus('testReload');
						if (checkStatus.isAll) {
							$(' .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
							$('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
						}
						//如果是异步请求数据方式，res即为你接口返回的信息。
						//删除
//						$(".t-delete-btn").on("click", function () {
//							var id = $(this).data("id");
//							var type = $(this).data("type");
//							_this.ajaxDelTemp(id, type, function () {
//								_this.againRenderTable();
//							})
//						});
						//修改
						$(".t-edit-btn").on("click", function () {
							var id = $(this).data("id");
							_this.ajaxDetail(id, function (data) {
								// 拿一下送餐地址
								_this.ajaxDepartAndAddress(data.orgId,2,function(data){
									addressList = data.data
								})
								_this.ajaxCompanyList(data.orgId, function (result) {
									data.companyList = result;
									data.addressList = addressList;
									var imageIds = [];
									var imageUrlids = [];
									var removeUrlids = [];

									$("body").append(template.render(tpl.updateTpl)(data));
									//关闭弹窗
									$(".close-btn,.cancel-add-btn").on("click", function () {
										$(".dialog-wp").remove();
									});
									$(".del-btn").on("click", function () {
										$(this).closest(".photo-item").remove();
										if ($(".photo-item").length < 3) {
											$(".photo-btn").css("display", "block")
										}
									})
									if ($(".photo-item").length == 3) {
										$(".photo-btn").css("display", "none");
									}
									if ($(".photo-item").length) {
										for (var i = 0; i < $(".photo-item").length; i++) {
											imageIds.push($(".photo-item")[i].getAttribute("data-imageid"));
										}
									}
									//上传识别图片
									$(".photo-file").on("change", function () {
										if (!$(".company-id").val()) {
											layer.msg("请先选择企业!");
											return false;
										}
										var file = $(this)[0].files[0];
										var fileName = $(this)[0].value;
										var suffixIndex = fileName.lastIndexOf(".");
										var suffix = fileName.substring(suffixIndex + 1).toUpperCase();
										if ($(".photo-item").length == 3) {
											layer.msg("识别图片最多上传3张!");
											return false;
										}
										if (suffix != "BMP" && suffix != "JPG" && suffix != "JPEG" && suffix != "PNG" && suffix != "GIF") {
											layer.alert("请上传图片（格式BMP、JPG、JPEG、PNG等）!");
											return false;
										}
										lrz(file, {
											quality: 0.8, //设置压缩率   
											width: 400
										}).then(function (results) {
											_this.upload(results.base64);
										});
									})
									//确认添加
									$(".sure-add-btn").on("click", function () {
										// console.log(imageIds);
										// console.log(imageUrlids);
										for (var i = 0; i < $(".photo-item").length; i++) {
											imageUrlids.push($(".photo-item")[i].getAttribute("data-imageid"));
										};
										removeUrlids = _this.array_diff(imageIds, imageUrlids);
										_this.submitAdd(function () {
											$(".dialog-wp").remove();
											layer.msg("修改成功！")
											_this.againRenderTable();
										}, data.id, imageUrlids, removeUrlids);
									})
								});

							})
						});
					}
				});
				//复选框选中监听,将选中的id 设置到缓存数组,或者删除缓存数组
				table.on('checkbox(user)', function (obj) {
					if (obj.checked == true) {
						if (obj.type == 'one') {
							idsArr.push(obj.data);
						} else {
							for (var i = 0; i < table_data.length; i++) {
								idsArr.push(table_data[i]);
							}
						}
					} else {
						if (obj.type == 'one') {
							for (var i = 0; i < idsArr.length; i++) {
								if (idsArr[i].id == obj.data.id) {
									idsArr.remove(i);
								}
							}
						} else {
							for (var i = 0; i < idsArr.length; i++) {
								for (var j = 0; j < table_data.length; j++) {
									if (idsArr[i].id == table_data[j].id) {
										idsArr.remove(i);
									}
								}
							}
						}
					};
					var newIdsArr = [];
					for (var i = 0; i < idsArr.length; i++) {
						var flag = true;
						for (var j = 0; j < newIdsArr.length; j++) {
							if (idsArr[i].id == newIdsArr[j].id) {
								flag = false;
							};
						};
						if (flag) {
							newIdsArr.push(idsArr[i]);
						};
					};
					//					console.log('newIdsArr',newIdsArr);
					//					console.log('idsArr',idsArr);
					idsArr = newIdsArr;
				});

//				table.on('toolbar(user)', function (obj) {
//					var checkStatus = table.checkStatus(obj.config.id);
//					switch (obj.event) {
//						case 'getCheckData':
//							var data = checkStatus.data;
//							layer.alert(JSON.stringify(data));
//							break;
//						case 'getCheckLength':
//							var data = checkStatus.data;
//							layer.msg('选中了：' + data.length + ' 个');
//							break;
//						case 'isAll':
//							layer.msg(checkStatus.isAll ? '全选' : '未全选')
//							break;
//					};
//				});
				//查询
				$('#conditionform  .search-btn').on('click', function () {
					idsArr = []; //清空之前选择的数据
					_this.againRenderTable();
				});
			});
		},
		/**
		 * 删除模板
		 * @param id 模板id
		 * @param callback
		 */
		ajaxDelTemp: function (id, type, callback) {
			var str = "";
			if (type == "1") {
				str = "确认禁用?";
			} else if (type == "2") {
				str = "确认启用?";
			} else if (type == "3") {
				str = "确认删除?";
			}
			layer.confirm(str, {
				btn: ['确定', '取消']
			}, function (index, layero) {
				layer.close(index); //如果设定了yes回调，需进行手工关闭
				$.ajax({
					type: "post",
					url: $("#contextPath").val() + "/admin/appUser/updateConsumer",
					data: {
						"id": id,
						"type": type
					},
					success: function (data) {
						if (data.code == 200) {
							callback();
						} else {
							layer.msg(data.msg)
						}
					},
					error: function () {
						// layer.msg('系统繁忙...')
					}
				});
			}, function (index) {

			});
		},

		/*重新渲染table*/
		againRenderTable: function (option) {
			var obj = $.extend(true, {}, option);
			var type =  obj.type || ''
			var $orgId = $("#conditionform  .single-orgid");
			var orgId = $("#conditionform  #orgId").attr('org__id')
			if(type == 1){
				table.reload('testReload', {
					where: {
						mobile: '',
						userName: '',
						roleType: '',
						orgId: $orgId.length?orgId:'',
						virtualArchId: '',
						dept: ''
					},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				});
			}else{
				table.reload('testReload', {
					where: {
						mobile: $("#conditionform .loginName").val(),
						userName: $("#conditionform .userName").val(),
						roleType: $("#conditionform .roleType").val(),
						orgId: orgId,
						virtualArchId: $("#companyId").attr('com__id') || '',
						dept: $("#departmentId").attr('dep__id') || ''
					},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				});
			}
			
		},
		//请求校区列表
		itemAjax: function () {
			$.ajax({
				type: "post",
				url: contextPath + "/admin/templ/getOrgList",
				success: function (data) {
					if (data.code == ERROK) {
						orgList = data.data;
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		//请求权限组列表
		permissionListAjax: function (orgId, callback) {
			$.ajax({
				type: "post",
				url: contextPath + "/lingling/getDeviceGroupList",
				data: {
					pageSize: 1000,
					pageNo: 1,
					orgId: orgId
				},
				success: function (data) {
					if (data.code == ERROK) {
						callback(data.data)
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 请求详情
		 * @param id
		 * @param callback
		 */
		ajaxDetail: function (id, callback) {
			var _this = this;
			$.ajax({
				type: "post",
				url: contextPath + "/admin/appUser/getConsumerInfo",
				data: {
					id: id
				},
				success: function (data) {
					if (data.code == ERROK) {
						data.data.id = id;
						callback(data.data)
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 新增或修改账号
		 * @param callback
		 * @param id
		 */
		submitAdd: function (callback, id, imageUrlids, removeUrlids) {
			var _this = this;
			var formdata = new FormData();
			if (!!id) {
				formdata.append("id", id)
			}
			//校区
			var orgId = $(".item-con #orgId").attr('org__id');
			if (!orgId) {
				layer.msg("请选择校区");
				return false;
			};
			formdata.append("orgId", orgId)

			// 企业
			var virtualArchId = $(".company-id").attr('com__id');
			if (!virtualArchId) {
				layer.msg("请选择企业");
				return false;
			};
			formdata.append("virtualArchId", $(".company-id").attr('com__id'));


			//手机号码
			var myreg = /^1[3456789]\d{9}$/;
			if (!$(".mobile-phone").val()) {
				layer.msg("请选择手机号码");
				return false;
			}
			if (!myreg.test($(".mobile-phone").val())) {
				layer.msg("请输入正确的手机号码！");
				return false;
			}
			formdata.append("mobilePhone", $(".mobile-phone").val())

			//姓名
			var name = $(".user-name").val()
			if (!name) {
				layer.msg("请输入姓名");
				return false;
			}
			if (_this.strlen(name) > 20) {
				layer.msg("姓名最多10个汉字");
				return false;
			}
			formdata.append("userName", $(".user-name").val())

			//积分
			var integral = $(".integral-balance").val();
			if (!integral) {
				layer.msg("请输入积分");
				return false;
			}
			formdata.append("integral", $(".integral-balance").val())

			//部门
			var dept = $(".dept").val();
			formdata.append("deptid", $(".dept").val());
			formdata.append("deptStr", $(".dept  option:selected").text())

			//送餐地址
			var address = $(".dinner-address").val();
			if (!address) {
				layer.msg("请选择送餐地址！");
				return false;
			}
			if (_this.strlen(address) > 100) {
				layer.msg("送餐地址最多50个汉字");
				return false;
			}
			formdata.append("dinnerAddress", $(".dinner-address").val());


			let addimgUrls = "";
			// 识别图片
			for (var i = 0; i < $(".photo-item").length; i++) {
				if ($(".photo-item")[i].getAttribute("data-url")) {
					addimgUrls += $(".photo-item")[i].getAttribute("data-url") + ",";
				}
			}
			// console.log(addimgUrls);
			formdata.append("addimgUrls", addimgUrls);

			//类型
			formdata.append("userType", $(".user-type:checked").data("status"));
			if (!id) {
				_this.ajaxAdd(formdata, function () {
					callback();
				})
			} else {
				formdata.append("imageUrlids", imageUrlids.join(","));
				formdata.append("removeUrlids", removeUrlids.join(","));
				_this.ajaxUpdate(formdata, function () {
					callback();
				})
			}
		},
		/**
		 * 新增
		 * @param data
		 * @param callbck
		 */
		ajaxAdd: function (data, callback) {
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/appUser/saveUpdateUserInfo",
				data: data,
				cache: false, // 不缓存
				processData: false, // 告诉jQuery不要去处理发送的数据
				contentType: false, // 告诉jQuery不要去设置Content-Type请求头	
				success: function (data) {
					if (data.code == 200) {

						callback();
					} else {
						layer.msg(data.msg)
					}
				},
				error: function () {
					// layer.msg('系统繁忙.....')
				}
			});
		},
		/**
		 * 修改
		 * @param data
		 * @param callbck
		 */
		ajaxUpdate: function (data, callback) {
			$.ajax({
				type: "post",
				url: $("#contextPath").val() + "/admin/appUser/saveUpdateUserInfo",
				data: data,
				cache: false, // 不缓存
				processData: false, // 告诉jQuery不要去处理发送的数据
				contentType: false, // 告诉jQuery不要去设置Content-Type请求头	
				success: function (data) {
					if (data.code == 200) {

						callback();
					} else {
						layer.msg(data.msg)
					}
				},
				error: function () {
					// layer.msg('系统繁忙.....')
				}
			});
		},
		strlen: function (str) {
			var len = 0;
			for (var i = 0; i < str.length; i++) {
				var c = str.charCodeAt(i);
				//单字节加1   
				if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
					len++;
				} else {
					len += 2;
				}
			}
			return len;
		},
		/**
		 * 获取部门和地址
		 * @param id
		 */
		ajaxDepartAndAddress: function (orgId,type,callback) {
			var _this = this;
			//获取部门
			$.ajax({
				type: "post",
				url: contextPath + "/admin/appUser/getDeptAndAddress",
				data: {
					type: type,
					orgId:orgId
				},

				success: function (data) {
					if (data && data.code == ERROK && data.data) {
						var _data = data.data
						if(callback != undefined && (typeof callback) == "function"){
							callback(data)
						}
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 获取企业列表
		 * @param organizationId
		 */
		ajaxCompanyList: function (organizationId, callback) {
			var _this = this;
			//获取部门
			$.ajax({
				type: "post",
				url: contextPath + "/busi/property/getvirtualArchTypeOne",
				data: {
					organizationId: organizationId
				},
				success: function (data) {
					companyList = data;
					callback(companyList);
				},
				error: function (error) {
					layer.msg('error')
				}
			});
		},
		/**
		 * 上传人脸识别图片
		 * @param file file文件
		 */
		upload: function (clearBase64) {
			$.ajax({
				url: $("#contextPath").val() + "/member/validateImage",
				type: "POST",
				dataType: "json",
				data: {
					imageUrl: clearBase64,
					virtualArchId: $(".company-id").attr('com__id')
				},
				timeout: 30000,
				beforeSend: function (xhr) {

				},
				success: function (data) {
					if (data.flag) {
						$(".photo-list").append(template.render(tpl.photoTpl)(data));
						if ($(".photo-item").length == 3) {
							$(".photo-btn").css("display", "none")
						}
						$(".del-btn").on("click", function () {
							$(this).closest(".photo-item").remove();
							if ($(".photo-item").length < 3) {
								$(".photo-btn").css("display", "block")
							}
						})
					} else {
						layer.msg(data.desc)
					}
				},
				error: function (xhr, textStatus) {

				}
			});
		},
		// 两个数组去重
		array_diff: function (a, b) {
			for (var i = 0; i < b.length; i++) {
				for (var j = 0; j < a.length; j++) {
					if (a[j] == b[i]) {
						a.splice(j, 1);
						j = j - 1;
					}
				}
			}
			return a;
		},
		/*
		 * 获取自动充值积分设置(新增)
		 * @param orgId
		 * @param callback
		 */
		getAutoSetting: function (orgId, callback) {
			$.ajax({
				url: $("#contextPath").val() + "/admin/dinner/place/getRechargeSetRecode",
				type: "POST",

				data: {
					orgId: orgId
				},
				success: function (data) {
					if (data.code == ERROK) {
						callback(data.data)

					} else {
						layer.msg(data.msg)
					}
				},
				error: function (xhr, textStatus) {

				}
			});
		},
		/**
		 * 确定自动充值
		 * @param callback
		 */
		saveRecharge: function (callback) {
			var _this = this;
			var id = $(".item-con.record-item-con").data("id");
			var result = {
				orgId: '',
				id: '',
				status: '', //开启自动充值 1上架0下架(1上架else下架)
				dayCount: '' //单日数量
			};
			result["id"] = id;
			//校区
			var orgId = $(".recharge-wp #orgId").attr('org__id');
			if (!orgId) {
				layer.msg("请选择校区！");
				return false;
			}
			result["orgId"] = orgId;

			//开启自动充值
			var status = $(".recharge-status:checked").data("status");
			result["status"] = status;

			//单日数量
			var dayCount = $(".recharge-wp .day-count").val();
			if (!dayCount) {
				layer.msg("请填写单日数量！");
				return false;
			}
			result["dayCount"] = dayCount;

			$.ajax({
				url: $("#contextPath").val() + "/admin/dinner/place/saveAndRechargeSet",
				type: "POST",

				data: result,
				success: function (data) {
					if (data.code == ERROK) {
						callback();
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (xhr, textStatus) {

				}
			});
		},
		/**
		 * 批量充值
		 * @param userIds
		 * @param callback
		 */
		saveBatchRecharge: function (userIds, callback) {
			var _this = this;

			var result = {
				orgId: '',
				integral: '', //积分
				userIds: '', //充值用户，以逗号分隔10004,10005

			};

			//校区
			var orgId = $(".recharge-wp #orgId").attr('org__id');
			if (!orgId) {
				layer.msg("请选择校区！");
				return false;
			}
			result["orgId"] = orgId;



			//充值数量
			var integral = $(".recharge-wp .integral").val();
			if (!integral) {
				layer.msg("请填写充值数量！");
				return false;
			}


			result["integral"] = integral;
			var userIdArr = [];
			$(".recharge-record-item").each(function (index, ele) {
				userIdArr.push($(ele).data("id"));
			})
			//			for(var i=0;i<userIds.length;i++){
			//				userIdArr.push(userIds[i].id);
			//			};
			result["userIds"] = userIdArr.join(",");
			$.ajax({
				url: $("#contextPath").val() + "/admin/dinner/place/updateAppUserList",
				type: "POST",

				data: result,
				success: function (data) {
					if (data.code == ERROK) {
						callback();
						idsArr = [];
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (xhr, textStatus) {

				}
			});
		},
		/**
		 * 发卡
		 * @param id
		 * @param callback
		 */
		sendCard: function (id, callback) {
			if (!$(".cardNumber").val()) {
				layer.msg("请输入实体卡号");
				return false
			}
			$.ajax({
				url: $("#contextPath").val() + "/lingling/provideCard",
				type: "POST",
				data: {
					cardCode: $(".cardNumber").val(),
					userId: id
				},
				success: function (data) {
					if (data.code == ERROK) {
						callback();
					} else {
						layer.msg(data.msg)
					}
				},
				error: function (xhr, textStatus) {

				}
			});
		},
		/**
		 * 收卡
		 * @param id
		 * @param callback
		 */
		deleteCard: function (id, cardCode, callback) {
			var str = "确认收卡?";
			layer.confirm(str, {
				btn: ['确定', '取消']
			}, function (index, layero) {
				layer.close(index); //如果设定了yes回调，需进行手工关闭
				$.ajax({
					url: $("#contextPath").val() + "/lingling/recycleCard",
					type: "POST",
					data: {
						id: id,
						cardCode: cardCode
					},
					success: function (data) {
						if (data.code == ERROK) {
							callback();
						} else {
							layer.msg(data.msg)
						}
					},
					error: function (xhr, textStatus) {}
				});
			}, function (index) {});
		},
		/**
		 * 获取权限组下的用户列表
		 * @param id
		 * @param callback
		 */
		ajaxCustomerList: function (groupId) {
			$.ajax({
				url: $("#contextPath").val() + "/lingling/getGroupUser",
				type: "POST",
				data: {
					groupId: groupId
				},
				success: function (data) {
					if (data.code == ERROK) {
						if (data.data.length > 0) {
							// $(".hadPeople .set-account-num").html('');
							var str = "";
							var list = data.data;
							$.each(list,function(index,item){
								str += "<label><input type='checkbox' name='personed' value='"+item.userId+"' checked='checked'><span>"+item.userName+"</span><span style='padding-left: 8px;'>"+item.mobile+"</span></label>"
							})
							$(".hadPeople").css("display", "block"); 
							$(".hadPeople .set-account-num").append(str);
						}else{
							$(".hadPeople").css("display", "none"); 
						}
					} else {
						// layer.msg(data.msg)
					}
				},
				error: function (xhr, textStatus) {

				}
			});
		},
	};
	api.init();
})

function boostImg(obj) {
	console.log(obj.src);
	$(".alert-bo").css("display", "block")
	$(".alert-bo img").attr("src", obj.src)
}

function closeAlert() {
	$(".alert-bo").css("display", "none")
}

//删除数组自定义函数
Array.prototype.remove = function (dx) {
	if (isNaN(dx) || dx > this.length) {
		return false;
	}
	for (var i = 0, n = 0; i < this.length; i++) {
		if (this[i] != this[dx]) {
			this[n++] = this[i]
		}
	}
	this.length -= 1
}