;
!(function(win) {
	"use strict";
	var pcLogin = function(){
		let path = top.location.pathname.split('/');
		path.splice(-1,1,'');
		path = path.join('/');
		console.log(path + 'login/');
		top.location.href = path + 'login/';
		return true;
	};
	window.hywa = {
		config: {
			href: '/buyer-side-web',
			// href: 'http://172.16.90.125:8765',
			port: {
				login: '/user/pcLogin', //登录
				loginOut: "/user/pcLogout", //退出
				mainMenu: '/menu/sysMenuTree', //获取左侧菜单
				changePassword: "/user/changePwd", //修改密码
				check_userPhone: "/login/userCheck", //检验手机号
				mainInfo: '/user/findSysInfoByUserId', //主页信息
				uploadFileUrl: '/file/upload', //上传图片
				getMenuBtn: '/menu/getButton', //获取菜单按钮

				// 农产品
				productTableUrl: '/product/findProductByWebFrom',
				productBigTypeUrl: '/dict',
				productSmallTypeUrl: '/dict/productSmallType',
				productAddFormUrl: '/product',
				productUpdateFormUrl: '/product/update',
				productStatusUrl: '/product/onOff',
				productByIdUrl: '/product',
				del_productTableData: '/product',

				// 店铺
				shopTableUrl: '/sellerInfo',
				shopStatusUrl: '/sellerInfo/isAvailable',
				shopByIdUrl: '/sellerInfo',

				// 用户-买家
				userTableUrl: '/buyer/buyerList',
				userByIdUrl: '/buyer/examine',
				userStatusUrl: '/buyer/onOff',

				// 骑手
				riderTableUrl: '/rider',
				riderAddFormUrl: '/rider',
				riderUpdateFormUrl: '/rider',
				riderByIdUrl: '/product',
				riderDelUrl: '/rider',
				riderStatusUrl: '/rider/available',

				// 消息发布
				mesTableUrl: '/announcement/findAnnouncementInfoAll',
				mesStatusUrl: '/announcement/available',
				mesFormUrl: '/announcement/saveOrUpdate',
				mesByIdUrl: '/announcement/findAnnouncementById',
				imgContentUpload: '/file/uploadImage',
				show_img: '/file/showImage?filePath=',

				// 交易统计
				tradeTableUrl: '/analysis/transaction/list',
				shopsTableUrl: '/analysis/seller/list',
				tradeTotalUrl: '/analysis/transaction',
				shopsTotalUrl: '/analysis/seller',
				tradeExportUrl: '/analysis/transaction/excel',
				shopExportUrl: '/analysis/seller/excel',

				// 访客分析
				visitorTableUrl: '/analysis/customer',
				viewsVolumeUrl: '/analysis/views',

				// 排行榜
				goodsTableUrl: '/analysis/product/leaderboard',
				sellerTableUrl: '/analysis/seller/leaderboard',

				// 单品分析
				singleGoodsTotalUrl: '/analysis/product',
				singleGoodsTableUrl: '/analysis/product/details',
				singleOrderVolumeUrl: '/analysis/orders',

				multiTypeSelect: "/dict", //参数多条件查询
				getProvince: "/region/province/index", //获取省
				getCity: "/region/city/index", //获取市
				getCounty: "/region/county/index", //获取县

				// 订单
				purchaseOrderTableUrl: "/orderInfo/list",
				flowOrderTableUrl: "/transferOrder/findByOrderId",
				orderByIdUrl: '/orderInfo/orderDetails',

				// 骑手取货
				riderPickTableUrl: '/transferOrder/list',
				
				//费用设置
				costsSetUrl:'/costsSet',

				// 权限
				userList: "/user/findAll", //用户列表
				userAddNew: "/user", //添加用户
				delete_newAddUser: "/user", //删除用户
				select_user: "/user/findById", //查询用户
				forbidUser: '/user/disableUser', //禁止用户
				purchaseUserList: '/user/findSpotName', //获取用户收购点信息

				regionListUrl: '/area/search',
				regionFormUrl: '/area',
				roleDataList: "/role/getAll", //获取角色列表

				roleListUrl: '/role/getAll',
				roleFormUrl: '/role',
				roleByid: '/role/findById',

				menuListUrl: '/menu/getMenuByRole',
				menuFormUrl: '/menu/saveRoleMenu',
			}
		},
		sessionTable: {
			tableName: 'system',
			userData: 'userData',
		},
		jumpPage: {
			home: "../index.html",
			login: 'login/'
		},
		codeVerify: {
			401: pcLogin,
			402: pcLogin,
			403: pcLogin,
			404: pcLogin,
			405: pcLogin,
			1004: function() {
				return true;
			},
			2006: function() {
				return false;
			},
			default: function() {
				return true;
			}
		},
		//字体库,layui样式,自己的公共样式,所有页面样式
		css: ['iconfont/iconfont.css', 'layui/css/layui.css', 'css/common.css'],
		//需要加载的js
		js: []
	};
	//加载样式
	link(window.hywa.css);
	//加载JS
	require(window.hywa.js);

	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]);
		//xhr.lay_loading =  layer.load(0, {shade: false});
		try {
			if (!_this.url.userId) {
				var token = layui.sessionData(window.hywa.sessionTable.tableName);
				_this.url.userId = (JSON.stringify(token) != '{}' ? token.userData.userId : false);
			}
		} catch (e) {

		}
		// debugger
		_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);
		console.log("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 || "不知道怎么了!!!";
			}
			if (json.retBody && !!json.retBody.list && !!json.retBody.list.length) {
				_this.json.count = json.retBody.total || 0;
				_this.json.data = json.retBody.list || [];
			} else if (json.retBody != "null" && !!json.retBody && Array.isArray(json.retBody.list) && !json.retBody.total) {
				_this.json.data = [];
			} else {
				_this.json.data = Array.isArray(json.retBody) ? (function() {
					_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);
			xhr.setRequestHeader('accessToken', (JSON.stringify(token) != '{}' ? token.token : false));
		}
	};
	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;
}
