import config from '../config/common' // 配置文件
import handle401 from './handle401'
// import MD5 from 'md5'

export default {
	domain() {
		// return config.uni_app_web_api_url.replace('api', '')
		return config.uni_app_web_local_api_url.replace('api', '')
	},
	getRequestHeaders(url, type = 'post', isIgnoreTenant) {
		const auth = 'Bearer ' + uni.getStorageSync('accessToken')
		// const user = uni.getStorageSync('loginUserVerify')
		// const RootOrgId = uni.getStorageSync('RootOrgId')
		const appInfoData = uni.getStorageSync('appInfo')
		const tenant = uni.getStorageSync('Tenant') || '01' //uni.getStorageSync('Tenant') || 
		const userId = appInfoData?.User?.ID || ''
		const userName = appInfoData?.User?.NAME || ''
		const orgId = appInfoData?.User?.ORG_ID || ''
		const dataRule = appInfoData?.DataRule ? appInfoData?.DataRule.join(',') : ''
		const departmentId = appInfoData?.User?.DEPARTMENT_ID || ''
		const mineType = appInfoData?.User?.MineType || ''
		const headers = {
			'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
			Authorization: auth,
			Tenant: tenant,
			userid: userId,
			// username: userName,  // username不能使用中文放在header
			departmentId,
			MineType: mineType,
			orgId,
			DataRule: dataRule,
			RequestType: '2'
		}
		// 非 OP 路径接口，header 需要添加 Tenant
		// const Tenant = uni.getStorageSync('Tenant')
		// url.indexOf('OP') != 0 && !isIgnoreTenant && (headers.Tenant = Tenant)
		return headers
	},
	send(options = {}, onlyData, isShowLoading) {
		const u = config.serviceHost(options.url)
		// loading加载
		if (isShowLoading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			})
		}

		// options.url = config.uni_app_web_api_url + '' + options.url
		options.url = u
		// 请求方式
		options.method = options.method || 'GET'
		// TODO:
		// let users = uni.getStorage("users");
		// if(users != null){
		//   options.header = { "Auth-Token" : users.token };
		// }
		// options.header = options.header

		// 发起Promise请求
		return new Promise((resolve, reject) => {
			uni.request(options).then(async (res, err) => {
				uni.hideLoading()
				let {
					errMsg,
					data,
					statusCode
				} = res
				// 登陆过期
				if (statusCode === 401) {
					const refreshData = await handle401(options)
					errMsg = refreshData.errMsg
					data = refreshData.data
					statusCode = refreshData.statusCode
				}

				if (statusCode !== 200) {
					if (statusCode === 400) {
						uni.removeStorageSync('accessToken')
						uni.removeStorageSync('refreshToken')

						let pages = getCurrentPages()
						if(pages.length > 0) {
							let prevPage = pages[pages.length - 1]
							if (prevPage.route !== 'pages/login/index') {
								uni.navigateTo({
									url: '/pages/login/index'
								})
							} else {
								uni.showModal({
									title: "400：没有访问权限",
									showCancel: false,
									content: data.error_description
								})
							}
						}

					} else {
						uni.showToast({
							title: '请求错误: ' + statusCode,
							icon: 'error'
						})
					}
					return
				}

				if (errMsg !== 'request:ok') {
					reject(errMsg)
				} else {
					uni.hideLoading()
					// 相应拦截、根据后端的状态码来写，可以自行判断和封装
					if (!data.IsSuccessful && onlyData) {
						// wyw api 调用错误提示  需要用户确认 再消失
						uni.showModal({
							title: '错误提示',
							content: data.ErrorMessage,
							showCancel: false,
						})
						reject(data.ErrorMessage)
					} else {
						resolve(data)
					}
				}
			})
		})
	},
	upload(url = '', filePath) {
		// return this.send({
		// 	url: url,
		// 	data: data,
		// 	header: this.getRequestHeaders(url, 'post')
		// }, onlyData)
		const appInfoData = uni.getStorageSync('appInfo')
		const tenant = uni.getStorageSync('Tenant') || ''
		const userId = appInfoData?.User?.ID || ''
		const orgId = appInfoData?.User?.ORG_ID || ''
		return new Promise((resolve, reject) => {
			uni.showLoading()
			uni.uploadFile({
				url: url,
				filePath: filePath[0],
				name: 'file',
				formData: {
					OrgId: orgId,
					userID: userId
				},
				header: {
					Tenant: tenant,
					userid: userId
				},
				success: (res) => {
					if (res.statusCode === 200) {
						uni.hideLoading()
						resolve(JSON.parse(res.data))
						const uploadResult = JSON.parse(res.data)
						if (uploadResult.IsSuccessful) {
							resolve(uploadResult.Data)
						} else {
							reject(uploadResult.ErrorMessage)
						}
					}
				},
				fail: (err) => {
					console.log(err)
				}
			})
		})
	},
	get(url = '', data = {}, onlyData = true) {
		return this.send({
			url: url,
			data: data,
			header: this.getRequestHeaders(url, 'get')
		}, onlyData)
	},
	post(url = '', data = {}, onlyData = true, isShowLoading = true) {
		const DataRule = uni.getStorageSync('DataRule')
		const dataStr = JSON.stringify(Object.assign({}, data, {
			DataRule
		}))
		// const requestKey = url + '_' + MD5(dataStr) + '_requestKey'
		// TODO: 节流
		// const loaded = uni.getStorageSync(requestKey)
		// if (loaded) return null
		// uni.setStorageSync(requestKey, true)
		return this.send({
			url: url,
			data: data,
			header: this.getRequestHeaders(url, 'post'),
			method: 'POST'
		}, onlyData, isShowLoading)
	}
}
