//邮储银行（奶茶）专用的
import useCode from "../pages/ycnc/hooks/useCode";
import {login} from '../api/ycnc'

function http(options) {
	uni.showLoading({
		title: "加载中",
		mask: true,
	});
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			header: {
			  //邮储奶茶
			  'content-type': 'application/x-www-form-urlencoded',
			},
			responseType: 'json',
			success: async (res) => {
				if (res.statusCode && res.statusCode != 200) {
					uni.hideLoading().then(() => {
						uni.showToast({
							title: "api错误" + res.errMsg,
							icon: 'none'
						});
					})
					reject()
				} else {
					if(res.data?.code >= 200 && res.data?.code < 300){
						setTimeout(()=>{
							uni.hideLoading()
						},300)
						resolve(res.data.data)
					}else if(res.data?.code === 401){
						const authCode = await useCode();
						const params = {code:authCode};
        				const {token} = await login({params});
						window.localStorage.setItem('token',token);
						//邮储奶茶
						http(options).then(_res => {
							resolve(_res)
						})
					}else{
						uni.hideLoading().then(() => {
							uni.showToast({
								title: res.data.message,
								icon: 'none'
							});
						})
						reject(res.data.message)
					}
				}
			},
			// 这里的接口请求，如果出现问题就输出接口请求失败
			fail: (err) => {
				uni.hideLoading().then(() => {
					uni.showToast({
						title: err,
						icon: 'none'
					});
				})
				reject(err)
			}
		})
	})
}

export default http