// 公共函数库
const app = getApp()
const qiniuUploader = require("./qiniuUploader.js");
class Base {
	constructor() {
		this.baseUrl = app.globalData.globalUrl;
	}

	newRequest(params, flag = false, tips = true) {
		let that = this

		if (!params.type) {
			params.type = 'GET'
		}

		// 版本
		// if (!params.version) {
		//   params.version = 'v1.0/'
		// }

		// var cur_url = that.baseUrl + params.version + params.url
		var cur_url = that.baseUrl + params.url

		if (params.otherUrl) {
			cur_url = params.otherUrl
		}

		wx.request({
			url: cur_url,
			data: params.data,
			method: params.type,
			header: {
				Authorization: app.globalData.first_token
				// 'token': 'sys',
			},
			success: function (res) {
				params.confirmback && params.confirmback(res) //请求完成后回调
				if (wx.showLoading()) {
					wx.hideLoading() //隐藏加载动画
				}
				if (res.statusCode == 200) {
					let rstcode = res.data.meta.code, msg = res.data.meta.message
					// todo: 状态码判断
					if (rstcode == 200) {
						params.callback && params.callback(res.data.data) // 请求成功 
					} else if (rstcode == '-400') { // 400 token过期
						if (!flag) {
							that.changeToken(params)
							// app.getSessionKey(function () {
							// 	that.newRequest(params, true,tips=true)
							// })
						}
					} else if (rstcode == '404') {
						wx.showModal({
							title: '错误',
							content: '网络请求失败'
						})
					} else {
						params.errorback && params.errorback(res) // 错误回调 
						if (tips) {
							wx.showToast({
								title: msg,
								icon: 'none',
								duration: 2000
							})
						}
					}
				} else {
					if (wx.showLoading()) {
						wx.hideLoading() //隐藏加载动画
					}
					wx.showModal({
						title: '错误',
						content: '网络请求失败'
					})
				}
			}
		})
	}

	changeToken(params) {
		wx.showLoading({
			title: '努力加载中...',
		})
		let that = this
		let tokenUrl = that.baseUrl + '/api/v1.0/change/token'
		wx.request({
			url: tokenUrl,
			data: {
			},
			method: 'post',
			header: {
				'content-type': 'application/json', // 默认值
				Authorization: app.globalData.first_token
			},
			success(res) {
				wx.hideLoading() //隐藏加载动画
				if (res.statusCode == 200) {
					let rstcode = res.data.meta.code
					if (rstcode == 200) {
						app.globalData.first_token = res.data.data.access_token
						that.newRequest(params)
					} else {
						app.getSessionKey(function () {
							that.newRequest(params, true, true)
						})
					}
				}
			}
		})
	}



	//富文本
	richText(detail) {
		if (detail != '' && detail != null && detail != undefined) {
			var newDetail = '';
			newDetail = detail.replace(/\<[\/]?(section)/g, function (m, m1) {
				return m.replace('section', 'div')
			});
			newDetail = newDetail.replace(/\<[\/]?(ruby)/g, function (m, m1) {
				return m.replace('ruby', 'span')
			});
			newDetail = newDetail.replace(/\<[\/]?(rt)/g, function (m, m1) {
				return m.replace('rt', 'span')
			});
			newDetail = newDetail.replace(/\<[\/]?(rp)/g, function (m, m1) {
				return m.replace('rp', 'span')
			});
			newDetail = newDetail.replace(/\<[\/]?(video)/g, function (m, m1) {
				return m.replace('video', 'video')
			});
			newDetail = newDetail.replace(/(\<img)/g, '$1 class="hellorich"');
			newDetail = newDetail.replace(/(\<div)/g, '$1 class="hellorich"');
			newDetail = newDetail.replace(/(\<p)/g, '$1 class="hellorich"');
			newDetail = newDetail.replace(/(\<video)/g, '$1 class="helloVideo"');

			return newDetail;
		} else {
			return ''
		}
	}

	//判断字符是否为空的方法
	stringIsEmpty(str) {
		if (typeof str == "undefined" || str == null || str == "") {
			return true;
		} else {
			return false;
		}
	}
	// 判断手机号格式
	telChange(tel) {
		const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
		if (!reg.test(tel)) {
			return true
		} else {
			return false
		}
	}
	// object通过value换取key
	findKey(value) {
		let arr = value.split('/api/')
		let name = arr.length > 1 ? arr[1] : arr[0]
		return name.replace(/\//g, "_")
	}

	trimStrSpace(str) {
		return str.replace(/(^\s*)|(\s*$)/g, '')
	}


	/**
	 * 提示框
	 * icon [success,loading,none]
	 */
	toast(
		title,
		duration = 2000,
		icon = 'none',
		image = '',
		mask = true,
		callback
	) {
		wx.showToast({
			title: title,
			icon: icon,
			image: image,
			duration: duration,
			mask: mask,
			success: function () {
				callback && callback()
			}
		})
	}

	modal(
		content = '',
		callback,
		errorback
	) {
		wx.showModal({
			title: "提示",
			content: content,
			success: function (res) {
				if (res.confirm) {
					callback && callback()
					console.log('用户点击确定')
				} else if (res.cancel) {
					errorback && errorback()
					console.log('用户点击取消')
				}
			}
		})
	}
	goBack(num) {
		var pages = getCurrentPages()
		var prevPage = pages[pages.length - parseInt(num)]
		prevPage.setData({
			isrefresh: true
		})
		setTimeout(function () {
			wx.navigateBack({
				delta: parseInt(num - 1)
			})
		}, 800)
	}
	//七牛上传
	initQiniu() {
		var options = {
			uptokenURL: 'https://repairtest.zeruiedu.com/api/v1.0/upload/token',
			domain: 'https://fhxm.xueyoubangedu.com/',
			uploadURL: 'https://up-z1.qiniup.com'
		};
		qiniuUploader.init(options);
	}

}

export {
	Base
}