var SYS_VER = parseInt(Math.random() * 10000000000);
function resetButton(menus, $) {
	var menuId = location.href.substring(location.href.indexOf("id=") + 3, location.href.indexOf("id=") + 35);
	for (var i = 0; i < menus.length; i++) {
		for (var j = 0; j < menus[i].subMenuList.length; j++) {
			if (menuId == menus[i].subMenuList[j].id) {
				var rights = menus[i].subMenuList[j].subMenuList;
				for (var k = 0; k < rights.length; k++) {
					if (rights[k].isChecked == 0) {
						$(rights[k].authStr.substring(rights[k].authStr.lastIndexOf(":") + 1) + "-btn-0").hide();
					}
					else {
						$(rights[k].authStr.substring(rights[k].authStr.lastIndexOf(":") + 1) + "-btn-0").show();
					}
				}
				break;
			}
		}
	}
}
function loadJS(url) {
	document.write("<scirpt src='" + url + "?ver=" + SYS_VER + "'></scirpt>")
}
!(function (win) {
	"use strict";
	window.hywa = {
		config: {
			href: 'http://172.16.90.64:21009/',
			imgbyapplets: 'http://47.98.47.246:8310',
			port: {
				login: '/web/user/login', //登录
				loginOut: "/web/user/logout", //退出
				changePassword: "/web/user/edit", //修改密码

				userList: "/web/user/searchByPage", //列表
				add_user: "/web/user/add", //添加
				edit_user: "/web/user/edit", //修改
				delete_user: "/web/user/del", //删除
				select_user: "/web/user/searchById", //查询单个
				forbidUser: '/web/user/forbidden', //禁止用户
				restPwd: "/web/user/restPwd",//重置密码
				//首页
				select_searchByPage: "/web/feedback/searchByPage",//评价明细列表
				del_feedback: "/web/feedback/batchDel",//删除评价
				qurey_echartTotal: "/web/code/record/statOneYear", //扫码图标统计
				query_listTotal: "/web/code/record/statYesterdayAndAllTime", //获取文字数统计
				//角色设置
				roleList: "/web/role/searchByPage", //获取角色列表
				add_role: "/web/role/add", //新增角色
				edit_role: "/web/role/edit", //修改角色
				delete_role: "/web/role/del", //修改角色
				select_role: "/web/role/searchById", //通过ID获取角色详细信息
				role_getAuth: "/web/role/searchRoleAuthInfo",//查询角色权限
				role_saveAuth: "/web/role/distrRoleAuthInfo",//保存企业授权信息
				//经销商管理
				dealerList: "/web/goods/dealer/searchByPage",
				add_dealer: "/web/goods/dealer/add",
				select_dealer: "/web/goods/dealer/findById",
				edit_dealer: "/web/goods/dealer/edit",
				delete_dealer: "/web/goods/dealer/delete",
				selectPId_dealer: "/web/goods/dealer/getCode",
				//企业
				orgList: "/web/org/searchByPage", //列表
				add_org: "/web/org/add", //添加
				edit_org: "/web/org/edit", //修改
				delete_org: "/web/org/del", //删除
				select_org: "/web/org/searchById", //查询单个
				select_Info_org: "/web/org/searchOrgInfo",//查询推广企业信息
				edit_Info_org: "/web/org/editExtendInfo",//企业推广保存
				org_getAuth: "/web/org/searchAuthInfo",//拉取企业授权信息
				org_saveAuth: "/web/org/distrOrgAuthInfo",//保存企业授权信息
				add_org_user: '/web/org/addOrgUser',//添加企业管理用户

				//产地
				regionList: "/web/goods/field/searchByPage", //列表
				add_region: "/web/goods/field/add", //添加
				edit_region: "/web/goods/field/edit", //修改
				delete_region: "/web/goods/field/del", //删除
				select_region: "/web/goods/field/searchById", //查询单个
				rnlist_region: "/web/goods/field/getBaseList",
				areaSearch: "/web/goods/field/getAreaInfo",//地址查询
				getOrchardList: "/web/goods/field/getOrchardList", // 获取原料生产数据

				//产品信息
				pdinfoList: "/web/goods/batch/searchByPage", //列表
				add_pdinfo: "/web/goods/batch/add", //添加
				add_rawMaterialInfo: "/web/inputs/save",//修改模式 - 添加原料项
				del_rawMaterialInfo: "/web/inputs/del",//修改模式 - 删除原料项
				add_produceProcessInfo: "/web/normal/save",//修改模式 - 添加生成过程项
				edit_produceProcessInfo: "/web/normal/edit",//修改模式 - 修改生成过程项
				del_produceProcessInfo: "/web/normal/del",//修改模式 - 删除生成过程项
				add_processingCirculationInfo: "/web/normal/save",//修改模式 - 添加加工流通过程项
				edit_processingCirculationInfo: "/web/normal/edit",//修改模式 - 修改加工流通过程项
				del_processingCirculationInfo: "/web/normal/del",//修改模式 - 删除加工流通过程项
				edit_pdinfo: "/web/goods/batch/edit", //修改
				delete_pdinfo: "/web/goods/batch/del", //删除
				select_pdinfo: "/web/goods/batch/searchById", //查询单个
				pdinfo2List: "/web/goods/searchByPage", //列表
				add_pdinfo2: "/web/goods/add", //添加
				edit_pdinfo2: "/web/goods/edit", //修改
				delete_pdinfo2: "/web/goods/del", //删除
				select_pdinfo2: "/web/goods/searchById", //查询单个
				pdinfo_qrcode: "/web/goods/batch/batchGoodsQRCode",//产品批次生成溯源码

				//溯源码管理
				qrcodeList: "/web/code/record/searchByPage", //列表
				view_qrcode: "/web/code/record/searchDetailById", //查看
				drop_qrcode: "/web/code/record/forbiddenCodeInfo", //废弃
				export_qrcode: "/web/code/record/exportDetailRecord", //导出
				delete_qrcode: "/web/code/record/delByPhysical", //删除
				drop_single: "/web/code/info/forbidden",//废弃单个溯源码
				show_codeDetail: "/web/code/record/showDetail",//溯源码预览
				print_qrcode: "/web/code/info/getPrintDetail", //溯源码打印
				setPrint_done: "/web/code/info/updateQRIsPrint",//标记已打印二维码
				//系统日志
				menuList: "/log/queryFuncName",//获取菜单列表
				logList: "/log/queryAll",//获取日志列表
				show_menu: "/menu/search", //查看权限菜单树
				get_menuList: "/menu/menuAllTree", //查看菜单列表
				select_menu: "/menu/search", //查看菜单详细,ID条件
				update_menu: "/menu", //菜单新增修改

				// 权限
				roleListUrl: '/role/getAll',
				roleFormUrl: '/role',
				roleByid: '/role/findById',
				menuListUrl: '/menu/getMenuByRole',
				menuFormUrl: '/menu/saveRoleMenu',
				systemListUrl: '/system/find',//系统维护查询
				systemFormUrl: '/system',//系统维护保存
				uploadImage: "/web/normal/uploadPics",
			}
		},
		sessionTable: {
			tableName: 'system',
			userData: 'userData'
		},
		jumpPage: {
			home: "../pages/?ver=" + SYS_VER,
			login: "../../?ver=" + SYS_VER
		},
		codeVerify: {
			405: function () {
				console.log('logout')
				//top.location.href = window.hywa.jumpPage.login;
				return true;
			},
			404: function () {
				// top.location.href = window.hywa.jumpPage.login;
				return true;
			},
			500: function () {
				//top.location.href = window.hywa.jumpPage.login;
				return true;
			},
			1004: function () {//认证失败
				top.location.href = window.hywa.jumpPage.login;
				return true;
			},
			2010: function () {//不能修改删除自己
				return false;
			},
			2011: function () {//不能对超级管理员进行操作
				return false;
			},
			1002: function () {//密码错误
				return false;
			},
			3003: function () {//修改前后密码不能相同
				return false;
			},
			3004: function () {//修改前后密码不能相同
				return false;
			},
			2006: function () {//文件上传失败
				return false;
			},
			2002: function () {//参数不能为空
				return false;
			},
			2003: function () {//类型被引用,请先删除引用
				return false;
			},
			2004: function () {
				return false;
			},
			2005: function () {//文件不能为空
				return false;
			},
			3009: function () {
				return false;
			},
			3008: function () {
				return false;
			},
			3011: function () {
				return false;
			},
			3017: function () {
				return true;
			},
			3013: function () {
				return false;
			},
			3019: function () {
				return false;
			},
			3036: function () {
				return false;
			},
			3037: function () {
				return false;
			},
			3038: function () {
				return false;
			},
			3039: function () {
				return false;
			},
			3070: function () {
				return false;
			},
			default: function () {
				return false;
			}
		}
	};

	win.hijack = function () {
		var _this = this;
		layui.use(['layer'], function () {
			_this.layer = layui.layer;
		});
		_this.json = {
			code: -404,
			msg: "返回数据格式错误",
			count: 0,
			data: []
		};
	};
	win.hijack.prototype.onload = function (xhr) {
		var _this = this;
		if (xhr.readyState === 4) { // 成功完成
			// 判断响应结果:
			if (xhr.status === 200) {
				//layer.close(xhr.xhr.lay_loading);
				xhr.responseText = JSON.stringify(_this.changeJSON(xhr.responseText).json);
				switch (_this.json.code) {
					case 0:
						// return _this.okMsg(_this.json.msg);
						return false;
					default:
						return _this.errorMsg(_this.json.code, _this.json.msg);
				};
			} else {
				return _this.errorMsg(xhr.status);
			}
		} else if (xhr.readyState === 1) {
			xhr.setRequestHeader('x-requested-with', "XMLHttpRequest");
		} else {

		}
	};
	win.hijack.prototype.open = function (arg, xhr) {
		var _this = this;
		_this.url = location.searchObj(arg[1]);
		_this.url.pageNum = _this.url.page - 0;
		_this.url.pageSize = _this.url.limit - 0;
		_this.url.pageNum || (delete _this.url.pageNum);
		_this.url.pageSize || (delete _this.url.pageSize);

		_this.url.pageNum && (delete _this.url.page);
		_this.url.pageSize && (delete _this.url.limit);
		arg[1] = _this.changeUrl(_this.url, arg[1].split('?')[0]).url;
	};
	win.hijack.prototype.changeUrl = function (obj, url) {
		var _this = this;
		_this.url = (_this.httpVerify(url) ? (function () {
			return _this.httpVerify(hywa.config.port[url]) ? hywa.config.href + hywa.config.port[url] : hywa.config.port[url];
		})() : url);
		_this.url += "?";
		for (var i in obj) {
			_this.url += i + "=" + obj[i] + "&";
		}
		_this.url = _this.url.substr(0, _this.url.length - 1);
		return this;
	};
	win.hijack.prototype.httpVerify = function (url) {
		return (url.substr(0, 5) != 'http:' && url.substr(0, 6) != 'https:' && url.substr(0, 2) != '//');
	};
	win.hijack.prototype.changeJSON = function (json) {
		var _this = this;
		try {
			json = JSON.parse(json);
			if (json.retHead) {
				_this.json.code = json.retHead.errCode;
				_this.json.msg = json.retHead.errMsg || "不知道怎么了!!!";
				_this.json.count = json.retHead.total || 0;
			} else {

			}
			if (JSON.stringify(json.retBody) == '{}') {
				json.retBody = []
			}
			if (json.retBody && !!json.retBody.list && !!json.retBody.list.length) {
				_this.json.count = _this.json.count || json.retBody.total || 0;
				_this.json.data = json.retBody.list || [];
				_this.json.button = json.buttonRep || {};
				if (JSON.stringify(_this.json.button) != '{}') {
					(function addRgt(data, rgt) {
						for (let i = 0; i < data.length; i++) {
							data[i] = Object.assign(data[i], rgt);
							if (data[i].children)
								addRgt(data[i].children, rgt);
						}
					})(_this.json.data, _this.json.button);
					for (let i = 0; i < _this.json.data.length; i++) {
						_this.json.data[i] = Object.assign(_this.json.data[i], _this.json.button);
					}
				}
			} else if (json.retBody != "null" && !!json.retBody && Array.isArray(json.retBody.list) && !json.retBody.total) {
				_this.json.data = [];
				_this.json.button = json.buttonRep || {};
				if (JSON.stringify(_this.json.button) != '{}') {
					(function addRgt(data, rgt) {
						for (let i = 0; i < data.length; i++) {
							data[i] = Object.assign(data[i], rgt);
							if (data[i].children)
								addRgt(data[i].children, rgt);
						}
					})(_this.json.data, _this.json.button);
					for (let i = 0; i < _this.json.data.length; i++) {
						_this.json.data[i] = Object.assign(_this.json.data[i], _this.json.button);
					}
				}
			} else {
				_this.json.data = Array.isArray(json.retBody) ? (function () {
					_this.json.count = _this.json.count || json.retBody.length;
					return json.retBody;
				})() : (json.retBody != 'null' ? [json.retBody] : []);
			}
		} catch (e) {
			_this.json = {
				code: -404,
				msg: "返回数据格式错误",
				count: 0,
				data: []
			};
		}
		return this;
	};
	win.hijack.prototype.errorMsg = function (code, msg) {
		var _this = this;
		_this.layer.msg("(" + code + ") " + (msg || "服务器通讯不畅！"), {
			icon: 2,
			time: 3000
		});
		return (window.hywa.codeVerify[(code - 0 || 'default')] || window.hywa.codeVerify['default'])();
	};
	win.hijack.prototype.okMsg = function (msg) {
		var _this = this;
		_this.layer.msg(msg, {
			icon: 1,
			time: 800
		});
		return false;
	};
	win.hijack.prototype.setRequestHeader = function (xhr) {
		var _this = this;
		if (typeof xhr.RequestHeader == 'undefined') {
			xhr.RequestHeader = true;
			var token = layui.sessionData(window.hywa.sessionTable.tableName);
			JSON.stringify(token) != '{}' && xhr.setRequestHeader('accessToken', token.token);
		}
	};
	var hook = new hijack();
	hookAjax({
		//拦截函数
		open: function (arg) {
			return hook.open(arg, this.xhr);
		},
		//拦截回调
		onreadystatechange: function (xhr) {
			// console.log(xhr.readyState)
			return hook.onload(xhr);
		},
		onload: function (xhr) {
			return hook.onload(xhr);
		},
		setRequestHeader: function (h, xhr) {
			// console.log("加头",JSON.stringify(xhr));
			hook.setRequestHeader(xhr);
		}
	});
})(window);
/**
 * 时间格式化
 */
Date.prototype.format = function (format) {

	var date = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"h+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3),
		"S+": this.getMilliseconds()
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	for (var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
				date[k] : ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}
/**
 * URL参数转换为对象
 */
Location.prototype.searchObj = function (url) {
	var obj = {};
	var arr = (url || this.search).match(/[?&][^?&]+=[^?&]+/g);
	if (arr) {
		arr.forEach(function (item) {
			var tempArr = item.substring(1).split('=');
			obj[decodeURIComponent(tempArr[0])] = decodeURIComponent(tempArr[1]);
			length++;
		});
	}
	return obj;
}