const app = getApp();
const env = {
	NODE_ENV: 'dev',
	dev: {
		// apiUrl: 'https://apitest.tongyu99.com',
		apiUrl: 'https://apitest.zhiqiyun.com'
	},
	product: {
		apiUrl: 'https://api.tongyu99.com'
	},
	tongyu: {
		apiUrl: 'https://kkapi.tongyu99.com'
	},
	// 集和堂
	jihetang: {
		apiUrl: 'https://api.ysb.zhiqiyun.com'
	},
	prd: {
		apiUrl: 'https://apimall.zhiqiyun.com'
	},
	pota: {
		// apiUrl: 'http://192.168.110.98:8098'   
		// apiUrl: 'http://192.168.110.180:8098' ,//f
		apiUrl: 'http://192.168.110.182:8098' ,//z
		// apiUrl: 'http://192.168.110.226:8098' //y
		// apiUrl: 'http://192.168.110.117:8098'//l
		// apiUrl: 'http://192.168.110.216:8098'
	}
}

var header = {
	'content-type': 'application/x-www-form-urlencoded',
	// 'appId': 'ZQMN3wuNVXAUiCv', //奥工匠正式环境
	// 'appId': 'ZQc5K6QOarBKJP4', //奥工匠测试环境
	// 'appId': 'ZQLekhQIkRxXr1C', //力美田
	// 'appId': 'ZQOQ5tTJYT6SM5V', //广联嗨购-智企云、注意直播插件
	// 'appId': 'ZQHtZekB64Yafta', //广联嗨购-通御
	// 'appId': 'ZQYkWdRhL2kIAwB', //仁和大药房
	// 'appId': 'ZQEHw4S7Gcaa78i', //广州集和堂
	// 'appId': 'ZQ6XiKauuAoSyfS', //金药堂
	// 'appId': 'ZQRSPr4qnuXwDhh', //叮当德胜
	// 'appId': 'ZQa41Hu7FvZyyNS', //乡亲闪送
	// 'appId': 'ZQT6vNJf7Axoy3T', //舒健之家
	// 'appId': 'ZQ59ZJo4TNLwmJx', //晓琳优品
	// 'appId': 'ZQan9wBIpcv48uN', //博爱优品  // 
	// 'appId': 'ZQ70mYvjoPD4DKt', //采芝灵
	// 'appId': 'ZQbLBtuI3UHBH7W', //河南新时尚

	// 切换成荣康需要去pages.json文件中pages将pages/index/index和pages/timelyDelivery/index位置互换，
	// 还需在tabBar中将pages/live/live直播页面注释 放开pages/timelyDelivery/index页面
	// 'appId': 'ZQ1VK5oc17I387E', //荣康
	// 'appId': 'ZQyhfB15fRD4oyZ',//春和祥(小详优选)
	// 'appId': 'ZQ0lLxSnxchdAWv',//四季康来
	// 'appId': 'ZQ0E8h3MkfniR7T',//康宁医药
	// 'appId': 'ZQYPXLwAjFsUauW',//通御优选
	// 'appId': 'ZQNTQcK0jjP6xu6',//百惠康
	// 'appId': 'ZQ0sZSrxva6KiMR', //通御体验
	// 'appId': 'ZQmSmCPZwDNOdg0',//九芝堂
	// 'appId': 'ZQdNLxle47GNK6E',//济民
	// 'appId': 'ZQV47ZfNRAcKDWn',//佐今明
	// 'appId': 'ZQHwYFoTQAKqQR5', //柚荚
	// 'appId': 'ZQTyfVuvX03FHPB', //焦娇美人西渡店
	// 'appId': 'ZQKadcCOddpJwkT',//利省家居
	// 'appId': 'ZQ7ViGD7S1aasT9',   //柚荚YOUGA
	// 'appId': 'ZQOrNJoG127SrcW',  //云助手
	// 'appId': 'ZQ9yuJK43epkCb9',  //精戈MALL
	// 'appId': 'ZQVhiq0ueRaGNUg',  //一源有品/艾康团
	'appId': 'ZQgrcXgeIQ1oPSl', //享团
	// 'appId': 'ZQn1yRLLTlwTxlw',  //清泉云
	// 'appId': 'ZQcWYTdcOPsM5vH', //哈哈一起零食
	// 'appId': 'ZQDd5ottiRqkw2n', //测试
	// 'appId': 'ZQkLZa6ytyXyi3B', //一度教育
	// 'appId': 'ZQWUN8wdYBFHX10', //享游敦煌
	// 'appId': 'ZQfa7C3fxB0X2Hg', //艾康团
	// 'appId': 'ZQcE7DsNhdymuX2', //绿色助农鼓云
	// 'appId': 'ZQqd7o72Q75wq1C', //齐育图书商城
	// 'appId': 'ZQFtuQbAnuIj7nC', //桦飞优选
	// 'appId': 'ZQVeqRWpfeVCYAq', //十二时辰
	// 'appId': 'ZQT6vNJf7Axoy3T', //舒健之家
	// 'appId': 'ZQ7Xyww1dCDVfP2', //宏润食品
	// 'appId': 'ZQ5TUrK1LrehKl8', //大隐生态
}

/**小程序配置 */
const publics = {
	picUrls: 'https://zhiqiyun.oss-cn-hangzhou.aliyuncs.com/static/', //图片地址
	'copyrighttitle': '智企云', //底部版权公司名称
	'copyrighttel': '400-698-5980', //底部版权服务电话
	'copyrightlogo': 'zhiqiyun', //底部版权 logo 文件名

	'yaomeng': 'https://cfwz.yaomengwang.cn/hunan?enterpriseCode=hnty&orderId=', //药盟接口地址
	'storemanagers': 'https://websmall.zhiqiyun.com?appId=', //saas门店管理地址（智企云所有）
	'channel': '', //处方中间渠道号  SAAS系统为空
	'is_customer_pick_up': false,
	
	// 奥工匠
	// 'mapLBSKEY': 'UW5BZ-MTX66-FCPSC-ET264-2UESO-FHBXW',
	// 'iconSrc': 'lblue/',
	// 'titleTopBgColor':'#1582F7',
	//小程序ID  wx636585333198880d
	
	// 力美田
	// 'mapLBSKEY': 'VBSBZ-4LWLK-7E5JC-AY5R4-H2NP6-QYBPC',
	// 'iconSrc': 'hBlue/',
	// 'titleTopBgColor':'#66a3c3',//72a0b4
	//小程序ID  wx0afb77bedadc1c22

	// 广联嗨购
	// 'mapLBSKEY': 'D4ZBZ-HDV6P-GEQDJ-V5Q5Y-3YPN7-OJBOS',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',//00923f、00a3ff、c70303
	//小程序ID  wxe5a8d24e2ad87575


	// 仁和大药房=
	// 'mapLBSKEY': 'OONBZ-VZXKU-A7TV2-2LWRF-IKLSE-PSFKX',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx51aa31ccf71b221a

	//广州集和堂
	// 'mapLBSKEY': 'GGOBZ-NVE3W-XM4RG-RZ3R4-LUMH2-KGB7J',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wxa453effc4de53ac2

	//金药堂
	// 'mapLBSKEY': '6XQBZ-OSFK2-LWIUD-CZ5ZO-S2V23-HJBBO',
	// 'iconSrc': 'orange/',
	// 'titleTopBgColor':'#ffbb00',
	// //小程序ID  wxbb4bc21cf658d44d

	//叮当德胜
	// 'mapLBSKEY': '4SUBZ-KDL64-VM2UW-D3MGZ-RDANV-BPBTN',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#d00b14',
	// //小程序ID  wx35586586dfc5ed27

	//乡亲闪送
	// 'mapLBSKEY': 'SG4BZ-LNUL4-ZM4U5-D3YVT-LB6NJ-A5FZV',
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor':'#1796CB',
	//小程序ID  wx5e68cd5e35b52ec3
	
	//舒健之家
	// 'mapLBSKEY': 'WA7BZ-64ALS-CZHOV-65W4F-57MTK-3FBWP',
	// 'mapLBSKEY': 'YYUBZ-CDME3-GTQ3A-34NVB-2DOPH-ROFZ4',
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor': '#1796CB',
	//小程序ID  wxb78faf888080863d  

	//晓琳优品
	// 'mapLBSKEY': 'U3XBZ-3JTLW-3QYRO-OZUUT-TQJLK-VCFRF',
	// 'iconSrc': 'green/',
	// 'titleTopBgColor':'#00923f',
	// //小程序ID  wx2228ff7ff3c18914

	//博爱优品
	// 'mapLBSKEY': '5BOBZ-CZC6V-IMUPM-USQNJ-TBTM5-J4BN7',
	// 'iconSrc': 'lightseagreen/',
	// 'titleTopBgColor':'#18AAA3',
	//小程序ID  wxd3d88847ac4f3a77

	//采芝灵
	// 'mapLBSKEY': 'GQ5BZ-YUJL4-WN4UX-XKZSV-R6LCH-WVBSQ',
	// 'iconSrc': 'lightseagreen/',
	// 'titleTopBgColor':'#18AAA3',
	//小程序ID  wxfbaa745f985e9516

	// 河南新时尚
	// 'mapLBSKEY': 'TYXBZ-RSNC6-SUFSK-ML6L7-TJC32-KDF5U',
	// 'iconSrc': 'orange/',
	// 'titleTopBgColor':'#fc5c25',
	//小程序ID  wxa2910c5a579be98e
	
	// 河南新时尚新
	// 'mapLBSKEY': '4RVBZ-ORDL4-WKNU3-DU3AF-PE5CS-CQFNY',
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor':'#0065AC',
	//小程序ID  wx0d8aaea41f357f01

	// 春和祥
	// 'mapLBSKEY': '6FTBZ-N6RWW-ZDURM-R57AO-OK6QH-3XFWF',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx37ac89533b3239de

	//荣康
	// 'mapLBSKEY': 'NPTBZ-NHJWV-RHSP6-UD5CZ-DZJMH-4UFCY',
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor': '#0065AC',
	//小程序ID  wx25cf96bbe43242ad

	//四季康来
	// 'mapLBSKEY': 'MF5BZ-VRMWP-44HDQ-VALQ2-V2OR2-FSFVW',
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor':'#0065AC',
	//小程序ID  wx01650f3aa51361af

	// 康宁医药
	// 'mapLBSKEY': 'V2BBZ-OSVK6-YG5S2-MZCL2-7TFRT-MIF2WP',
	// 'iconSrc': 'green/',
	// 'titleTopBgColor':'#23AC3A',
	//  小程序ID  wx0e8038f07fda6370

	// 'adGroupId': '1196269897935630343',//通御优选
	// 'mapLBSKEY': '4VYBZ-KHUK3-6HW34-3WARL-FSA5Q-D4BVL',
	// 'iconSrc': 'lightseagreen/',
	// 'titleTopBgColor':'#008457',
	//小程序ID  wxae03e9c5b5fcb1fb 

	//百惠康
	// 'mapLBSKEY': 'JUHBZ-KT43F-OZLJV-J42KS-ZZXO3-WDFPH',  //新KEY
	// 'iconSrc': 'green/',
	// 'titleTopBgColor':'#00923f',
	//小程序ID  wxec640e9e6dee99a9

	// 通御体验
	// 'mapLBSKEY': 'EHDBZ-WKOWK-MAEJA-AFDZ6-TRT75-2HFGP',
	// 'iconSrc': 'lightseagreen/',
	// 'titleTopBgColor': '#18AAA3',
	//小程序ID  wxcbb16b5f84df483e

	// 九芝堂
	// 'mapLBSKEY': 'E6UBZ-JI6WX-6J44X-Z774E-MWZWK-TRBAM',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx21258194d46c2837

	// 济民
	// 'mapLBSKEY': '6Z6BZ-4FFRX-H2T4D-74TLV-GB2VO-QPBNX',
	// 'iconSrc': 'green/',
	// 'titleTopBgColor':'#00923f',
	//小程序ID  wx86813a2fbde25177


	// 'adGroupId': '1196269897935630340',//佐今明  
	// 'mapLBSKEY': '7UJBZ-RG7WP-ZKRDP-LW2UZ-JFG2E-XVFBO',  //新KEY
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor':'#0065AC',
	//小程序ID  wx3bcfbcd294199cda


	// 'adGroupId': '1196269897935630338', //柚荚
	// 'mapLBSKEY': 'CTLBZ-HV5KP-2Z3DD-VFPJO-6HGOT-QBBDT',
	// 'iconSrc': 'orange/',
	// 'titleTopBgColor': '#fc5c25',
	//小程序ID  wxd6be35d5cf3554e2
	//'myTopBgColor':'#c9136d',

	// 'adGroupId': '1196269897935630339',//焦娇美人西渡店
	// 'mapLBSKEY': 'XJ4BZ-X5OW6-XJ2ST-M4PAA-4I4RZ-T3BH7',
	// 'iconSrc': 'pink/',
	// 'titleTopBgColor':'#c9136d',
	//小程序ID  wx1824dd234dbd9cd4


	// 'adGroupId': '1196269897935630348',//柚荚YOUGA
	// 'mapLBSKEY': 'JCQBZ-SZQKK-U56JV-AOEIP-KNS73-6SF4Q',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx145fb0289399d9d7

	// 'adGroupId': '1196269897935630346',//利省家居
	// 'mapLBSKEY': 'GVJBZ-JWAC6-XVMSG-E2NOL-VKUFO-3DBYS',
	// 'iconSrc': 'blue/',
	// 'titleTopBgColor':'#0065AC',
	//小程序ID  wx97cf9850fd1e0d96


	// 'adGroupId': '1196269897935630352',//云助手
	// 'mapLBSKEY': 'RRQBZ-DKHWD-TMF45-HHHOV-ADLQZ-DEB7X',
	// 'iconSrc': 'lblue/',
	// 'titleTopBgColor':'#00a3ff',
	//小程序ID  wx0ecc71add476037a

	// 'adGroupId': '1196269897935630357',//精戈MALL
	// 'mapLBSKEY': 'C53BZ-4HD66-P4RSQ-EGH4V-OGTF5-QVB2D',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#c30d23',
	//小程序ID  wxf6806bd34099aca1

	// 'adGroupId': '1196269897935630357',//艾康团
	// 'mapLBSKEY': 'GXZBZ-Z4VE6-62QST-MD4VW-3PLET-FZFS5',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx0ee780805b7f89c6
	//秘钥2acf05cba68661cd6a74d029bf89aefb

	// 'adGroupId': '1196269897935630352', //享团-宜得了
	'mapLBSKEY': 'YQZBZ-6LMC4-IGQUO-XE64O-4UJL6-YNB77',
	'iconSrc': 'red/',
	'titleTopBgColor': '#cd0b01',
	// 小程序ID  wxe7bec198ecfe1162

	// 'adGroupId': '1196269897935630352',//清泉云购
	// 'mapLBSKEY': 'JYDBZ-4V2C5-BJTIU-Q5N3Q-55TA5-XNB2A',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	// 小程序ID  wx33b41a76932836fa

	//哈哈一起零食
	// 'mapLBSKEY': 'PMXBZ-SDLKP-J2JDO-VTXQX-LAYEE-LJFMG',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx89a0cbd5a9a684d2

	//一度教育
	// 'mapLBSKEY': '6F6BZ-TNLKF-BNGJW-NZRO7-IHLCZ-XWFSX',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx727adf669dd4f0ec

	//享游敦煌
	// 'mapLBSKEY': 'ABXBZ-E4GCJ-NGJFD-KGHBJ-2HRK2-LRBTL',
	// 'iconSrc': 'gold/',
	// 'titleTopBgColor':'#d27a07',
	//小程序ID  wx8090f2557f633d35
	
	//一源有品
	// 'mapLBSKEY': 'ICHBZ-7AWK6-CQRSZ-EQBDM-AVIDK-WNFE2',
	// 'iconSrc': 'red/',
	// 'titleTopBgColor':'#cd0b01',
	//小程序ID  wx506847824713881c
	// 秘钥cf8b5009d6b4e6ffbb75befeecb9e522
	
	//绿色助农鼓云
	// 'mapLBSKEY': 'S5FBZ-QDGL3-G6733-33C6R-JOYB3-24FV5',
	// 'iconSrc': 'orange/',
	// 'titleTopBgColor':'#fc5c25',
	//小程序ID  wx584d4802269eb4ff
	
	//齐育图书商城
	// 'mapLBSKEY': 'ZC4BZ-DFNC4-CFPUZ-DJ7MP-XA2CK-L7FGU',
	// 'iconSrc': 'orange/',
	// 'titleTopBgColor':'#FF7B00',
	//小程序ID  wx295f7a721393b35b

	//桦飞优选
	// 'mapLBSKEY': '5H5BZ-IRRC3-EN633-YB7JJ-A4AIO-6JBRI',
	// 'iconSrc': 'green/',
	// 'titleTopBgColor':'#00923f',
	//小程序ID  wx3977e474e1b3e01c
	
	//十二时辰
	// 'mapLBSKEY': 'BW4BZ-T4ZL3-TM73D-3BKGX-YMGPF-O5F7Y',
	// 'iconSrc': 'green/',
	// 'titleTopBgColor':'#00923f',
	// 'skinNotColor': true
	//小程序ID  wx74438083f45c646a
	
	//宏润食品
	// 'mapLBSKEY': '6TKBZ-K3KCD-6PQ44-PP5IB-EJY23-ZRBAM',
	// 'iconSrc': 'lblue/',
	// 'titleTopBgColor':'#00a3ff',
	//小程序ID  wxa6d0922207de7cc4
	
	//大隐生态
	// 'mapLBSKEY': 'VMLBZ-NR5KJ-DKHFH-KKNNN-RLJQK-UHFFQ',
	// 'iconSrc': 'lightseagreen/',
	// 'titleTopBgColor':'#2b968e',
	//小程序ID  wx6337e58691994808
}
/*
 * 获取token
 */
const getToken = (success) => {
	let token = getStorage('AUTH_TOKEN');
	if (token) {
		success.call(this, token);
		return false;
	} else {
		loadToken(data => {
			success.call(this, data);
		});
	}

}
const loadToken = (success) => {
	let that = this
	uni.request({
		url: env[env.NODE_ENV].apiUrl + '/api/access_token',
		data: {},
		method: 'get',
		header: header,
		success(json) {
			if (json.statusCode !== 200) return msg(json.data.message);
			if (json.data.code !== 0) return msg(json.data.msg)
			setStorage('AUTH_TOKEN', json.data.data);
			success.call(that, json.data.data);
		},
		fail() {
			msg('access_token 获取失败');
		}
	})
}

/**
 * 微信小程序静默授权登录
 * @param {*} parentId 
 * @param {*} merchantId 
 */
const silenceLogin = (parentId, merchantId) => {
	// #ifdef MP-WEIXIN
	if (!isLogins(false)) { //未登录
		uni.login({
			success(res) {
				console.log('静默授权登录>>>', res);
				let params = {
					code: res.code,
					parentId: parentId ? parentId : '',
					merchantId: merchantId ? merchantId : ''
				}
				return new Promise((resolve, reject) => {
					postRequest('/api/v3/silence/login', params, data => {
						if(data.token) setStorage('AUTH_TOKEN',data.token);
						getRequest('/api/user/my', {}, suc => {
							data.isDistriUser = suc.isDistriUser;
							setStorage('userInfo', data);
						});
						resolve();
					});
				})
			}
		});
	}
	// #endif
}

const getWXUserProfile = (suc) => {
	let that = this;
	var sessionKey = '';
	var openid = '';

	getApp().globalData.getCheckSessoin(json => {
		sessionKey = json.session_key;
		openid = json.openid;
	});

	try {
		uni.getUserProfile({
			desc: '完善信息',
			success: res => {
				updataWxInfos(res.iv, res.encryptedData, sessionKey, openid, suc);
			},
			fail: res => {
				console.log('授权失败数据>>>', res);
				msg(res);
			}
		});
	} catch (e) {
		//  老版
		wx.getUserInfo({
			success: function(ress) {
				updataWxInfos(res.iv, res.encryptedData, sessionKey, openid, suc);
			}
		});
	}
}

/**
 * 保存微信头像
 */
const updataWxInfos = (iv, encryptedData, sessionKey, openid, suc) => {
	if (!encryptedData || !iv) return false;
	let _params = {
		sessionKey: sessionKey,
		openId: openid,
		iv: iv,
		encryptedData: encryptedData
	};
	postRequest('/api/user/weixin/update', _params, json => {
		setStorage('userInfo', json);
		suc.call();
	});
}

const clearValueEmpty = (data) => {
	let keyValue = {};
	for (let key in data) {
		let value = typeof data[key];
		if (value == 'string' && value) {
			if (data[key] != 'undefined' && data[key] != " " && data[key] != undefined && data[key] != null) {
				keyValue[key] = data[key];
			}
			// keyValue[key] = data[key];
		} else if (value == 'number' && value != null) {
			keyValue[key] = data[key];
		} else if (value == 'boolean') {
			keyValue[key] = data[key];
		} else {
			if (data[key]) keyValue[key] = data[key];
		}
	}
	return keyValue;
}

/**
 * 公共请求
 * 
 * @param {*} url  请求url
 * @param {*} data 请求参数
 * @param {*} method 请求方法
 * @param {*} success 成功函数
 * @param {*} isLoad 是否显示加载提示
 */
const baseRequest = (url, data, method, success, isLoad) => {
	getToken(token => {
		if (!isLoad) uni.showNavigationBarLoading();
		header.authorityToken = token;
		if (url.indexOf('/v3') != -1 || url.indexOf('/paper/create') != -1) {
			header['content-type'] = 'application/json;charset=UTF-8'
		} else {
			header['content-type'] = 'application/x-www-form-urlencoded'
		}
		uni.request({
			url: env[env.NODE_ENV].apiUrl + url,
			data: clearValueEmpty(data),
			method: method,
			header: header,
			success(json) {
				if (!isLoad) uni.hideNavigationBarLoading();
				if (json.statusCode !== 200) return msg(json.data.message);
				if (json.data.code === 10021 || json.data.code === 10020) {
					// console.log("第二次执行")

					removeStorage('AUTH_TOKEN');
					return redirectIndex();
				}
				if (json.data.code !== 0) {
					return msg(json.data.msg)
				}
				// console.log("第二次执行")
				let data = json.data.data;
				if (typeof data === 'string' && data.indexOf("{") === 0) {
					data = JSON.parse(data);
				}
				success.call(this, data);
			},
			fail() {
				if (!isLoad) uni.hideNavigationBarLoading();
			},
			// complete(){
			//  success.call(this, data);
			// },
		})
	})
}

const loadIng = (msg) => {
	uni.showLoading({
		title: msg,
		mask: true
	})
}

/**POST请求 */
const postRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'post', success, isLoad);
}
const postRequestLoding = (url, data, success, isLoding) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'post', success, false, isLoding);
}

/**GET请求 */
const getRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'get', success, isLoad);
}
/**Put请求 */
const putRequest = (url, data, success, isLoad) => {
	header['content-type'] = 'application/x-www-form-urlencoded'
	baseRequest(url, data, 'put', success, isLoad)
}
const putRequestJson = (url, data, success, isLoad) => {
	header['content-type'] = 'application/json;charset=UTF-8'
	baseRequest(url, data, 'put', success, isLoad)
}


/**
 * 上传文件
 * @param {*} url 请求url
 * @param {*} data 携带数据
 * @param {*} success 请求成功函数
 */
const uploadFile = (url, data, success) => {
	// console.log(env[env.NODE_ENV].apiUrl + url, data)
	getToken(token => {
		uni.uploadFile({
			url: env[env.NODE_ENV].apiUrl + url,
			filePath: data,
			name: 'file',
			header: {
				'appId': header['appId'],
				'authorityToken': token
			},
			success(res) {
				if (res.statusCode !== 200) return msg('文件上传失败');
				let data = JSON.parse(res.data);
				if (data.code !== 0) return msg(data.msg);
				success.call(this, data.data);
			},
		})
	})
}


/**弹窗 */
const msg = (title, success) => {
	if (title) {
		uni.showToast({
			title: title,
			icon: 'none',
			success() {
				if (success) success.call(this);
			}
		});
	}
	return false;
}

const msgConfirm = (msg, success, cancel) => {
	uni.showModal({
		title: '提示',
		content: msg,
		success(res) {
			if (res.confirm) {
				success.call(this);
			} else {
				if (cancel) cancel.call(this);
			}
		}
	})
}

const msgConfirmText = (msg, confirmText, success, cancel) => {
	uni.showModal({
		title: '提示',
		content: msg,
		confirmText: confirmText,
		success(res) {
			if (res.confirm) {
				success.call(this);
			} else {
				if (cancel) cancel.call(this);
			}
		}
	})
}

const alertMsg = (msg, success) => {
	uni.showModal({
		title: '提示',
		content: msg,
		showCancel: false,
		success(res) {
			if (success) success.call(this);
		}
	})
	return false;
}

const load = msg => {
	uni.showLoading({
		title: msg,
		mask: true
	})
}

const g = (url, success, isLoad) => {
	getRequest(url, {}, success, isLoad)
}

const p = (url, success, isLoad) => {
	postRequest(url, {}, success, isLoad)
}

const send = (url, mobile, success, error) => {
	if (!mobile) {
		return msg('手机号码不能为空', error);
	}
	postRequest(url, {
		phone: mobile
	}, json => {
		if (json.code !== 0) {
			return msg(json.msg, error);
		}
		let time = 60;
		const initTime = setInterval(() => {
			time--;
			if (time > 0) {
				success.call(this, time + '秒后获取');
			} else {
				clearInterval(initTime);
				success.call(this, '获取验证码');
			}
		}, 1000)
	})
}
// 登陆拦截
const redirectIndex = (params) => {
	// uni.clearStorageSync();
	// console.log(params)
	var pages = getCurrentPages();
	// console.log("pages》》》》》登陆拦截", pages);
	let currentUrl;
	if (pages) {
		var currentPage = pages[pages.length - 1];
		if (currentPage) {
			currentUrl = currentPage.route;
			let query = currentPage.data.query;
			if (query) {
				for (let key in query) {
					const fo = key + '=' + query[key];
					currentUrl += currentUrl.indexOf('?') > -1 ? '&' + fo : '?' + fo;
				}
			}
			if (currentUrl) {
				console.log('currentUrl》》》》》', currentUrl);
				setStorage("REDIRECT_URL", '/' + currentUrl)
				if (currentUrl == 'pages/authorize/authorize') {
					console.log('当前已经处于登录页面，不在向下执行跳转');
					return
				}
			}
		}
	}
	let redirectUrl = '/pages/authorize/authorize' + (params ? params : '');
	// console.log("登陆拦截")
	uni.navigateTo({
		url: redirectUrl
	})
	return false;
}

const saveImage = (url) => {
	uni.saveImageToPhotosAlbum({
		filePath: url,
		success() {
			msg('图片保存成功');
		}
	})
}

const saveImageToPhotosAlbum = (url) => {
	if (!url) return msg('小程序码不存在');
	uni.getImageInfo({
		src: url,
		success(json) {
			// uni.getSetting({
			//   success(res) {
			//     if (!res.authSetting['scope.writePhotosAlbum']) {
			//       uni.authorize({
			//         scope: 'scope.writePhotosAlbum',
			//         success() {
			//           saveImage(json.path);
			//         }
			//       })
			//     } else {
			//       saveImage(json.path);
			//     }
			//   }
			// })
		}
	})
}

const getConfig = (config, id) => {
	let con = {};
	config.info.forEach(inf => {
		// console.log(inf.version, inf.version ? inf.version.indexOf(id) : '-')
		if (inf.isSet && (!inf.version || inf.version.indexOf(id) > -1))
			con[inf.setName] = inf.setDefault;
	});
	config.card.forEach(inf => {
		if (inf.isSet && (!inf.version || inf.version.indexOf(id) > -1))
			con[inf.setName] = inf.setDefault;
	});
	config.realTime.forEach(inf => {
		if (inf.isSet && (!inf.version || inf.version.indexOf(id) > -1))
			con[inf.setName] = inf.setDefault;
	});
	return con;
}

const isLogin = async (error) => {
	let userInfo = getStorage('userInfo');
	if (!userInfo || !userInfo.id) {
		if (error) return false;
		// console.log("第一次执行")
		return redirectIndex();
	}
	return true;
}

//检测是否登录
const isLogins = (isGoLogin) => {
	let userInfo = getStorage('userInfo');
	if (!userInfo) {
		if (isGoLogin) {
			redirectIndex();
		}
		return false;
	}
	return true;
}

const setStorage = (key, value) => {
	uni.setStorageSync(env.NODE_ENV + "_" + key, value)
}

const getStorage = (key) => {
	return uni.getStorageSync(env.NODE_ENV + "_" + key)
}

const removeStorage = (key) => {
	return uni.removeStorageSync(env.NODE_ENV + "_" + key);
}

/**
 * 缓存模板id
 */
// const gettmplIds = () => {
//   getRequest('/api/wxmes/querylist', {}, res => {
//     setStorage('tmplIds', res)
//     console.log(res)
//   })
// }

//微信支付订单公共方法 
const payOrder = (id,success) => {
	var loctionAddressMap = getStorage('loctionAddressMap');
	var datas = {
		id: id
	};
	if (loctionAddressMap) {
		datas.province = loctionAddressMap.province;
		datas.city = loctionAddressMap.city;
	};
	if(getStorage('isVideoScene')){
		uni.checkBeforeAddOrder({
			success (res){ 
				console.log('下单前置检查',res)
				let data = res.data;
				data.requiredFundType = 0;
				datas.sceneCheckStr = JSON.stringify(data);
				wexinPay(datas,success)
			},
		})
	}else{
		wexinPay(datas,success)
	}
	
}

//支付中或已支付
const payStatus = (json, id, success) =>{
	if(json&&json.code === 115){
		setTimeout(res=>{
			uni.hideLoading();
			isShowLoading = false;
			uni.showModal({
				title: '提示',
				content: '当前订单正在支付或30秒后重试',
				confirmText: '我知道了',
				showCancel: false,
				success(res) {
				}
			})
		},3000)
		return false;
	}
	if (json.type === 2 || json.type === 3) {
		//调用后台判断订单是否支付成功
		let i = 0;
		let timer = setInterval(() => {
			postRequest('/api/order/check', {
				id: id
			}, res => {
				if (res.isSuccess || i === 4) {
					clearInterval(timer);
					success.call(this, res.isSuccess);
				} else {
					i++;
				}
			}, true)
		}, 200);
		// success.call(this);
		return false;
	}
}

// 支付成功回调
const paySuccess = (id,success) =>{
	console.log('支付成功')
	let i = 0;
	let timer = setInterval(() => {
		postRequest('/api/order/check', {
			id: id
		}, res => {
			console.log(i)
			if (res.isSuccess || i === 5) {
				clearInterval(timer);
				success.call(this, res.isSuccess);
			} else {
				i++;
			}
		}, true)
	}, 500);
}
// 支付失败回调
const payFail = (id) =>{
	console.log('支付失败')
	postRequest('/api/order/cancelPay', {
		id: id
	}, data => {
		uni.redirectTo({
			url: '/mine/orderDet/orderDet?id=' + id,
		})
	})
}

const wexinPay = (datas, success) => {
	let isShowLoading = false;
	if (!isShowLoading) {
		loadIng('加载中');
		// console.log('加载中')
		isShowLoading = true;
	}
	// #ifdef MP-WEIXIN
	postRequest('/api/order/weixin/pay', datas, json => {
		// console.log('json',json)
		payStatus(json, datas.id, success)
		
		const sceneCheckStr = datas.sceneCheckStr;
		
		if(sceneCheckStr && JSON.parse(sceneCheckStr).requiredFundType === 1){ 
			console.log('拉起收银台')
			wx.requestOrderPayment({
				timeStamp: json.timeStamp,
				nonceStr: json.nonceStr,
				package: json.packages,
				signType: json.signType,
				orderInfo: json.orderInfo,
				paySign: json.sign,
				success: function() {
					paySuccess(datas.id,success)
				},
				fail: function(res) {
					console.log(res);
					payFail(datas.id)
				}
			})
		}else{
			uni.requestPayment({
				timeStamp: json.timeStamp,
				nonceStr: json.nonceStr,
				package: json.packages,
				signType: json.signType,
				paySign: json.sign,
				success: function() {
					paySuccess(datas.id,success)
				},
				fail: function(res) {
					console.log(res);
					payFail(datas.id)
				}
			})
		}
		if (isShowLoading) {
			uni.hideLoading();
			isShowLoading = false;
		}
	})
	// #endif
	// #ifdef MP-ALIPAY
	datas.payChannel = 'alipay_lite ';
	postRequest('/api/order/weixin/pay', datas, json => {
		// console.log(json)
		if (json.type === 2 || json.type === 3) {
			//调用后台判断订单是否支付成功
			let i = 0;
			let timer = setInterval(() => {
				postRequest('/api/order/check', {
					id: id
				}, res => {
					if (res.isSuccess || i === 4) {
						clearInterval(timer);
						success.call(this, res.isSuccess);
					} else {
						i++;
					}
				}, true)
			}, 200);
			// success.call(this);
			return false;
		}
		uni.requestPayment({
			provider: 'alipay',
			orderInfo: json.packages,
			success: function() {
				paySuccess(datas.id,success)
			},
			fail: function(res) {
				payFail(datas.id)
				console.log(res);
			}
		})
		if (isShowLoading) {
			uni.hideLoading();
			isShowLoading = false;
		}
	})
	// #endif
}

//微信支付订单公共方法 
const payOrdersss = (id, success) => {
	let isShowLoading = false;
	if (!isShowLoading) {
		loadIng('加载中');
		// console.log('加载中')
		isShowLoading = true;
	}
	var loctionAddressMap = getStorage('loctionAddressMap');
	var datas = {
		id: id
	};
	if (loctionAddressMap) {
		datas.province = loctionAddressMap.province;
		datas.city = loctionAddressMap.city;
	};
	// #ifdef MP-WEIXIN
	postRequest('/api/order/weixin/pay', datas, json => {
		// console.log(json)
		if (json.type === 2 || json.type === 3) {
			//调用后台判断订单是否支付成功
			let i = 0;
			let timer = setInterval(() => {
				postRequest('/api/order/check', {
					id: id
				}, res => {
					if (res.isSuccess || i === 4) {
						clearInterval(timer);
						success.call(this, res.isSuccess);
					} else {
						i++;
					}
				}, true)
			}, 200);
			// success.call(this);
			return false;
		}
		uni.requestPayment({
			timeStamp: json.timeStamp,
			nonceStr: json.nonceStr,
			package: json.packages,
			signType: json.signType,
			paySign: json.sign,
			success: function() {
				console.log('支付成功')
				let i = 0;
				let timer = setInterval(() => {
					postRequest('/api/order/check', {
						id: id
					}, res => {
						console.log(i)
						if (res.isSuccess || i === 5) {
							clearInterval(timer);
							success.call(this, res.isSuccess);
						} else {
							i++;
						}
					}, true)
				}, 500);
			},
			fail: function(res) {
				console.log('支付失败')
				postRequest('/api/order/cancelPay', {
					id: id
				}, data => {
					uni.redirectTo({
						url: '/mine/orderDet/orderDet?id=' + id,
					})
				})
				console.log(res);
			}
		})
		if (isShowLoading) {
			uni.hideLoading();
			isShowLoading = false;
		}
	})
	// #endif
	// #ifdef MP-ALIPAY
	datas.payChannel = 'alipay_lite ';
	postRequest('/api/order/weixin/pay', datas, json => {
		// console.log(json)
		if (json.type === 2 || json.type === 3) {
			//调用后台判断订单是否支付成功
			let i = 0;
			let timer = setInterval(() => {
				postRequest('/api/order/check', {
					id: id
				}, res => {
					if (res.isSuccess || i === 4) {
						clearInterval(timer);
						success.call(this, res.isSuccess);
					} else {
						i++;
					}
				}, true)
			}, 200);
			// success.call(this);
			return false;
		}
		uni.requestPayment({
			provider: 'alipay',
			orderInfo: json.packages,
			success: function() {
				console.log('支付成功')
				let i = 0;
				let timer = setInterval(() => {
					postRequest('/api/order/check', {
						id: id
					}, res => {
						console.log(i)
						if (res.isSuccess || i === 5) {
							clearInterval(timer);
							success.call(this, res.isSuccess);
						} else {
							i++;
						}
					}, true)
				}, 500);
			},
			fail: function(res) {
				console.log('支付失败')
				postRequest('/api/order/cancelPay', {
					id: id
				}, data => {
					uni.redirectTo({
						url: '/mine/orderDet/orderDet?id=' + id,
					})
				})
				console.log(res);
			}
		})
		if (isShowLoading) {
			uni.hideLoading();
			isShowLoading = false;
		}
	})
	// #endif
}

//微信支付订单公共方法 ==活动
const payOrders = (id, success, type) => {
	let isShowLoading = false;
	if (!isShowLoading) {
		loadIng('加载中');
		// console.log('加载中')
		isShowLoading = true;
	}
	postRequest('/api/order/weixin/pay', {
		id: id
	}, json => {
		// console.log(json)
		payStatus(json, id, success)
		uni.requestPayment({
			timeStamp: json.timeStamp,
			nonceStr: json.nonceStr,
			package: json.packages,
			signType: json.signType,
			paySign: json.sign,
			success: function() {
				paySuccess(id, success)
			},
			fail: function(res) {
				console.log('支付失败')
				postRequest('/api/order/cancelPay', {
					id: id
				}, data => {
					uni.redirectTo({
						url: '/mine/activity/activity',
					})
				})
				console.log(res);
			}
		})
		if (isShowLoading) {
			uni.hideLoading();
			isShowLoading = false;
		}
	})
}

const authSetting = (authority, success, error) => {
	// console.log(authority,success)
	// #ifndef H5
	uni.getSetting({
		success(res) {
			if (res.authSetting[authority]) {
				success.call(this);
				return false;
			}
			uni.authorize({
				scope: authority,
				success() {
					success.call(this);
				},
				fail: function(res) {
					error.call(this);
				}
			})
		}
	})
	// #endif
}

const getLocation = (suss) => {
	// #ifdef MP-WEIXIN
	authSetting('scope.userLocation', () => {
		// load('定位中…');
		uni.getLocation({
			type: 'gcj02',
			// isHighAccuracy: true,
			success: function(res) {
				// uni.hideLoading();
				console.log(res, "789")
				suss.call(this, res);
			},
			fail: function(res) {
				console.log("调用失败", res)
				suss.call(this, 2)
				// uni.hideLoading();
			}
		})
	}, () => {
		// uni.hideLoading();
		console.log("取消")
		suss.call(this, 1)
	});
	// #endif
	// #ifdef MP-ALIPAY
	uni.getLocation({
		type: 'gcj02',
		// isHighAccuracy: true,
		success: function(res) {
			// uni.hideLoading();
			console.log(res, "789")
			suss.call(this, res);
		},
		fail: function(res) {
			console.log("调用失败", res)
			suss.call(this, 2)
			// uni.hideLoading();
		}
	})
	// #endif

	// #ifdef H5
	uni.getLocation({
		type: 'gcj02',
		isHighAccuracy: true,
		success: function(res) {
			// uni.hideLoading();
			console.log(res)
			suss.call(this, res, "789");
		},
		fail: function() {
			console.log("调用失败", res)
			suss.call(this, 2)
			// uni.hideLoading();
		}
	})
	// #endif
}

const scopeAddress = (success) => {
	// #ifdef MP-WEIXIN
	authSetting('scope.address', () => {
		uni.chooseAddress({
			success: function(res) {
				success.call(this, res);
			},
		})
	}, () => {
		msg('未设置开放权限')
	});
	// #endif
	// #ifdef MP-ALIPAY
	uni.chooseAddress({
		success: function(res) {
			success.call(this, res);
		},
	})
	// #endif
}

const isAuth = () => {
	const user = getStorage('userInfo');
	return user && user.id;
}

// 去掉字符串中的特殊字符和转义字符
const excludeSpecial = (s) => {
	// 去掉转义字符
	//  s = s.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');

	const pattern = /[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""' + - - _ % 。，、？\s]/g;
	if (s != undefined || s != null) {
		s = s.replace(pattern, "")
	}
	return s;
}

// 行为操作
const saveBehavior = (params, success) => {
	//用户行为：behavior 1、关注 2、收藏 3、点赞 4、浏览 5、确认 6、海报
	//用户行为操作对象：type 1、产品 2、赛事 3、未知 4、内容 5、课程 6、老师 7、素材 8、题目 9、资料领取 10、招聘职位 11、用户 12、用户须知 13、素材 15、科室 16、海报 20、医生 21日历、探索 47评价
	postRequest('/api/v3/save', params, data => {
		success.call(this, data)
	})
}
const getBehavior = (params, success) => {
	//用户行为：behavior 1、关注 2、收藏 3、点赞 4、浏览 5、确认 6、海报
	//用户行为操作对象：type 1、产品 2、赛事 3、未知 4、内容 5、课程 6、老师 7、素材 8、题目 9、资料领取 10、招聘职位 11、用户 12、用户须知 13、素材 15、科室 16、海报 20、医生 21日历、探索 47评价
	console.log('行为')
	getRequest('/api/v3/get', params, data => {
		success.call(this, data)
	})
}
/**
 * text:展示导航名
 * iconPath:未点击显示图标
 * selectedIconPath:选中图标
 * pagePath：页面路径
 * channel：匹配名
 * click：点击事件
 * index：排序
 * show:是否显示
 */
var selectedIconPath
if (header.appId == 'ZQ1VK5oc17I387E') {
	selectedIconPath = '/static/pages/images/' + publics.iconSrc + 'yunyao_h.png'
} else {
	selectedIconPath = '/static/pages/images/' + publics.iconSrc + 'home_h.png'
}
var tab = [{
		text: header.appId == 'ZQ1VK5oc17I387E' ? '云药房' : "首页",
		iconPath: header.appId == 'ZQ1VK5oc17I387E' ? '/static/pages/images/yunyao.png' :
			"/static/pages/images/home.png",
		selectedIconPath: selectedIconPath,
		pagePath: 'pages/index/index',
		channel: 'home',
		click: 'goHome',
		index: header.appId == 'ZQ1VK5oc17I387E' ? 3 : 1,
		show: true
	},
	{
		text: "分类",
		iconPath: "/static/pages/images/sort.png",
		selectedIconPath: '/static/pages/images/' + publics.iconSrc + 'sort_h.png',
		pagePath: 'pages/sort/sort',
		click: 'goSort',
		channel: 'sort',
		index: 2,
		show: true
	},
	{
		text: "社区",
		iconPath: "/static/pages/images/interactive.png",
		selectedIconPath: '/static/pages/images/' + publics.iconSrc + 'interactive_h.png',
		pagePath: 'pages/interactive/index',
		click: 'goInteractive',
		channel: 'interactive',
		index: 3,
		show: true
	},
	{
		text: "直播",
		iconPath: "/static/pages/images/live.png",
		selectedIconPath: '/static/pages/images/' + publics.iconSrc + 'live_h.png',
		pagePath: 'pages/live/live',
		click: 'goLive',
		channel: 'live',
		index: 3,
		show: header.appId == 'ZQ1VK5oc17I387E' ? false : false
	},
	{
		text: "购物车",
		iconPath: '/static/pages/images/cart.png',
		selectedIconPath: '/static/pages/images/' + publics.iconSrc + 'cart_h.png',
		pagePath: 'pages/cart/cart',
		click: 'goCart',
		channel: 'cart',
		index: 5,
		show: true
	},
	{
		text: "我的",
		iconPath: '/static/pages/images/user.png',
		selectedIconPath: '/static/pages/images/' + publics.iconSrc + 'user_h.png',
		pagePath: 'pages/user/user',
		click: 'goUser',
		channel: 'user',
		index: 6,
		show: true
	}
]
module.exports = {
	setStorage: setStorage,
	getStorage: getStorage,
	postRequest: postRequest,
	postRequestLoding: postRequestLoding,
	getRequest: getRequest,
	putRequest: putRequest,
	putRequestJson: putRequestJson,
	msg: msg,
	g: g,
	p: p,
	env: env,
	send: send,
	redirectIndex: redirectIndex,
	saveImage: saveImage,
	saveImageToPhotosAlbum: saveImageToPhotosAlbum,
	uploadFile: uploadFile,
	msgConfirm: msgConfirm,
	getConfig: getConfig,
	load: load,
	isLogin: isLogin,
	isLogins: isLogins,
	payOrder: payOrder,
	payOrders: payOrders,
	getLocation: getLocation,
	scopeAddress: scopeAddress,
	isAuth: isAuth,
	alertMsg: alertMsg,
	getToken: getToken,
	loadIng: loadIng,
	removeStorage: removeStorage,
	public: publics,
	header: header,
	// gettmplIds: gettmplIds,
	excludeSpecial: excludeSpecial,
	tab: tab,
	msgConfirmText: msgConfirmText,
	silenceLogin: silenceLogin,
	getWXUserProfile: getWXUserProfile,
	updataWxInfos: updataWxInfos,
	saveBehavior: saveBehavior,
	getBehavior: getBehavior
}