import {
	baseUrl,
	baseApiUrl
} from './config.js';
import * as common from './common.js' //引入common
import * as db from './db.js' //引入common
// 需要登陆的，都写到这里，否则就是不需要登陆的接口
let methodsToken = ['profile', 'refreshUser', 'wxLogin', 'changeMobile', 'getWuyuanUser', 'getContentDetail',
	'addCart', 'previewOrder',
];
const post = (method, data, callback, type, orgurl) => {
	let userToken = '';
	let auth = '';
	// 判断token是否存在
	// console.log("method: ", method);
	if (methodsToken.indexOf(method) >= 0) {
		// 获取用户token
		let auth = db.get("auth");
		// console.log(auth);
		let nowdate = (new Date()) / 1000; //当前时间戳
		//新增用户判断是否登录逻辑begin
		common.isLogin();
		//新增用户判断是否登录逻辑end
		if (!auth || auth.createtime + auth.expires_in < nowdate) {
			common.toLogin();
			return false;
		} else {
			userToken = auth.token;
		}
	}

	if (type) {
		method = type + '/' + method
	} else {
		method = '/' + method
	}

	let realurl = baseApiUrl + method;

	if (orgurl) {
		realurl = baseUrl + orgurl;
	}


	uni.showLoading({
		title: '',
		icon: 'loading'
	});
	uni.request({
		url: realurl,
		data: data,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded',
			'token': userToken,
			'__token__': userToken

		},
		method: 'POST',
		success: (response) => {
			uni.hideLoading();
			const result = response.data
			if (result.msg == 'Please login' || result.msg == '请登陆') {
				db.del("user");
				db.del("auth");
				console.log('未登陆')
				uni.showToast({
					title: result.msg,
					icon: 'none',
					duration: 2000,
					complete: function() {
						uni.reLaunch({
							url: '/pages/index/index',
						})
					}
				});
			}
			callback(result);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				showError(error.response);
			}
		},
	});
}

// 上传图片
export const uploadImage = (method, data = {}, callback, num = 9, type) => {
	if (type) {
		method = type + '/' + method
	} else {
		method = method
	}
	let userToken = '';
	let auth = db.get("auth");
	userToken = auth.token;
	uni.chooseImage({
		count: num,
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++) {
				data.file = tempFilePaths[i]
				uni.uploadFile({
					url: baseApiUrl + method,
					filePath: tempFilePaths[i],
					fileType: 'image',
					name: 'file',
					headers: {
						'Accept': 'application/json',
						'Content-Type': 'multipart/form-data',
						'token': userToken
					},
					formData: data,
					success: (uploadFileRes) => {
						callback(JSON.parse(uploadFileRes.data))
					},
					fail: (error) => {
						if (error && error.response) {
							common.showError(error.response);
						}
					},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					},
				});
			}
		}
	});
}

const get = (url, callback) => {
	uni.showLoading({
		title: '加载中'
	});
	let realurl = baseUrl + url;

	if (url.indexOf('http:') >= 0 || url.indexOf('https:') >= 0) {
		let realurl = url;
	}
	uni.request({
		url: realurl,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
		},
		method: 'GET',
		success: (response) => {
			callback(response.data);
		},
		fail: (error) => {
			if (error && error.response) {
				showError(error.response);
			}
		},
		complete: () => {
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});
}

const showError = error => {
	let errorMsg = ''
	switch (error.status) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '跨域拒绝访问'
			break
		case 404:
			errorMsg = `请求地址出错: ${error.config.url}`
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = error.msg
			break
	}
	uni.showToast({
		title: errorMsg,
		icon: 'none',
		duration: 2000
	});
}



const syncget = (url, data) => {
	return new Promise(function(resolve, reject) {
		get(url + queryParams(data, true), (result) => {
			try {
				resolve(result);
			} catch (e) {
				reject(e);
			}
		})
	})

}

const syncpost = (f, m, d) => {
	return new Promise(function(resolve, reject) {
		post(f, d, (result) => {
			try {
				resolve(result);
			} catch (e) {
				reject(e);
			}
		}, m, m);
	})

}
// 登录
export const third = (data, callback) => post('third', data, callback, 'discover/user/third');
// 用户绑定手机
export const bindphone = (data, callback) => post('bind', data, callback, 'discover/User');
// 修改用户信息
export const profile = (data, callback) => post('profile', data, callback, 'discover/User');
// 发送验证码
export const sendSmsVerify = (data, callback) => post('sendSmsVerify', data, callback, 'discover/User');
// 刷新用户
export const refreshUser = (data, callback) => post('refreshUser', data, callback, 'discover/User');

// 注册
export const register = (data, callback) => post('register', data, callback, 'discover/User');
// 登录
export const login = (data, callback) => post('login', data, callback, 'discover/User');
// 退出登录
export const logout = (data, callback) => post('logout', data, callback, 'discover/User');
// 上传头像
export const upload = (data, callback) => post('upload', data, callback, 'discover/Ajax');

// 绑定手机
export const changeMobile = (data, callback) => post('changeMobile', data, callback, 'discover/User');

//获取手机号前先登录
export const wxLogin = (data, callback) => post('wxLogin', data, callback, 'user');
//获取手机号
export const getMobile = (data, callback) => post('getPhoneNumber', data, callback, 'user');
//取CMS配置
// export const getConfig = async (params = {}) => await syncget('addons/cms/api.common/init', params);


function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
	let prefix = isPrefix ? '?' : ''
	let _result = []
	if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets';
	for (let key in data) {
		let value = data[key]
		// 去掉为空的参数
		if (['', undefined, null].indexOf(value) >= 0) {
			continue;
		}
		if (value.length > 0) {
			value = value.replace(/%/g, "%25");
			value = value.replace(/\&/g, "%26");
			value = value.replace(/\+/g, "%2B");
		}

		// 如果值为数组，另行处理
		if (value.constructor === Array) {
			// e.g. {ids: [1, 2, 3]}
			switch (arrayFormat) {
				case 'indices':
					// 结果: ids[0]=1&ids[1]=2&ids[2]=3
					for (let i = 0; i < value.length; i++) {
						_result.push(key + '[' + i + ']=' + value[i])
					}
					break;
				case 'brackets':
					// 结果: ids[]=1&ids[]=2&ids[]=3
					value.forEach(_value => {
						_result.push(key + '[]=' + _value)
					})
					break;
				case 'repeat':
					// 结果: ids=1&ids=2&ids=3
					value.forEach(_value => {
						_result.push(key + '=' + _value)
					})
					break;
				case 'comma':
					// 结果: ids=1,2,3
					let commaStr = "";
					value.forEach(_value => {
						commaStr += (commaStr ? "," : "") + _value;
					})
					_result.push(key + '=' + commaStr)
					break;
				default:
					value.forEach(_value => {
						_result.push(key + '[]=' + _value)
					})
			}
		} else {
			_result.push(key + '=' + value)
		}
	}
	return _result.length ? prefix + _result.join('&') : ''
}

//取轮播图
export const getBannerList = (data, callback) => get('/api/wuyuan/swiper_icon/lists' + queryParams(data, true),
	callback);
export const getWuyuanUser = (data, callback) => post('getWuyuanUser', data, callback, 'wuyuan/user');
// 学院底部课程
export const getHomeData = (data, callback) => post('getHomeData', data, callback, '',
	'addons/yuneducation/page/getHomeData');
// 课程界面数据
export const getCourseList = (data, callback) => post('getCourseList', data, callback, '',
	'addons/yuneducation/course/getCourseList');
// 课程详情
export const getCourseDetail = (data, callback) => post('getCourseDetail', data, callback, '',
	'addons/yuneducation/course/getCourseDetail');
// 获取课程考核
export const getCourseExamine = (data, callback) => post('getCourseExamine', data, callback, '',
	'addons/yuneducation/course/getCourseExamine');
// 课程开始学习
export const startLearn = (data, callback) => post('startLearn', data, callback, '',
	'addons/yuneducation/course/startLearn');
// 试播
export const getContentDetail = (data, callback) => post('getContentDetail', data, callback, '',
	'addons/yuneducation/course/getContentDetail');
// 加入购物车
export const addCart = (data, callback) => post('addCart', data, callback, '',
	'addons/yuneducation/order/addCart');
// 预览订单
export const previewOrder = (data, callback) => post('previewOrder', data, callback, '',
	'addons/yuneducation/order/previewOrder');
// 提交订单
export const submitOrder = (data, callback) => post('submitOrder', data, callback, '',
	'addons/yuneducation/order/submitOrder');
// 移除购物车
export const removeCart = (data, callback) => post('removeCart', data, callback, '',
	'addons/yuneducation/order/removeCart');
// 讲师详情
export const getTeacherDetail = (data, callback) => post('getTeacherDetail', data, callback, '',
	'addons/yuneducation/teacher/getTeacherDetail');
// 培训分类列表
export const getCategoryList = (data, callback) => post('getCategoryList', data, callback, '',
	'addons/yuneducation/course/getCategoryList');
// 获取培训列表
export const getScheduleList = (data, callback) => post('getScheduleList', data, callback, '',
	'addons/yuneducation/schedule/getScheduleList');
// 获取培训详情

export const getScheduleDetail = (data, callback) => post('getScheduleDetail', data, callback, '',
	'addons/yuneducation/schedule/getScheduleDetail');
// 培训开始学习
export const scheduleStartLearn = (data, callback) => post('startLearn', data, callback, '',
	'addons/yuneducation/schedule/startLearn');
// 获取我的课程列表
export const getMineCourseList = (data, callback) => post('getMineCourseList', data, callback, '',
	'addons/yuneducation/course/getMineCourseList');