import * as types from '../store/mutations-types'
import store from '../store/store'
import {
	appSecret,
	apiBaseUrl
} from './config'
import apiErrorHandler from '../api/error.js'
import MD5 from 'crypto-js/md5'

let headers = {
	// 'Content-Type': 'application/x-www-form-urlencoded' //设置默认头信息
	"locale": 'zh-Hans',
}
const timeout = 20 * 1000 //默认20秒超时

/**
 * 生成签名
 * @param param
 * @returns {string}
 */
const sign = (param) => {
	let sign = '',
		key = [],
		p = Object.assign({}, param)

	//参数排序
	p.key = appSecret
	_.forIn(p, (v, k) => {
		key.push(k)
	})
	key.sort()

	//生成签名字符串
	key.map((v, k) => {
		p[v] = (p[v] != null && p[v] != undefined) ? p[v] : '';
		if (typeof(p[v]) === 'object') {
			p[v] = JSON.stringify(p[v])
		}
		sign += `&${v}=${p[v]}`
	})
	sign = sign.substr(1)
	sign = MD5(sign)
	sign = sign.toString()

	return sign
}

/**
 * 错误处理
 * @param error
 * @param reject
 */
const errorHandler = (error, reject) => {
	if (process.env.NODE_ENV === 'development') {
		console.warn(error)
	}

	apiErrorHandler(error, reject)
}

export default (url = '', params = {}, options = {}, type) => {
	let config = {}
	// edit by knight 20210819 根据不同请求设置请求头
	const locale = uni.getStorageSync('locale')
	if(locale) headers.locale= locale
	let _headers = Object.assign({}, headers, options.headers);

	// console.log(_headers);

	//默认get 不显示加载提示 自动处理错误
	options = Object.assign({
		method: 'get',
		loading: false,
		errorHandle: true
	}, options)
	options.method = options.method.trim().toUpperCase();

	if (url) {

		//获取签名
		// const signStr = sign(params)

		//修改：sign都使用post传参,get方法改为拼接url
		if (options.method === 'GET') {
			let getParams = '';
			_.forIn(params, (v, k) => {
				getParams += `&${k}=${v != null && v != undefined ? v : ''}`
			})
			getParams = getParams.substr(1)
			if (getParams.length > 0)
				url = url.indexOf('?') > -1 ? url + '&' + getParams : url + '?' + getParams

			//清除可能post过去的数据
			// params = {}
		}

		// params.sign = signStr

		//处理返回值是原生图片类型 --- app不支持！！！
		// if (options.requestType === 'image') {
		// 	config.responseType = 'arraybuffer'
		// }

		//处理文件上传信息
		// if (options.requestType == 'file') {
		// 	config.headers = {}
		// 	config.headers.post = {}
		// 	config.headers.post['Content-Type'] = 'multipart/form-data' //文件上传头信息
		// }

		// edit by knight 20210819 部分接口不需要转string
		// if(!options.keepObject){
		// 	//因为uni.request 发送给服务端时数据类型都是string，所以对object对要先处理
		// 	_.forIn(params, (v, k) => {
		// 		if (typeof(v) == 'object') {
		// 			params[k] = JSON.stringify(v)
		// 		}
		// 	})
		// }

		//测试出输出信息
		if (process.env.NODE_ENV === 'development') {
			console.log({
				url: url,
				params: params
			})
		}
		if(store.getters.userToken() && url != '/system/pda-login' && !type){
			_headers['Authorization'] = 'Bearer ' + store.getters.userToken();
		}

		// console.log(_headers);

		return new Promise((resolve, reject) => {
			if (options.loading) {
				uni.showLoading({})
			}

			let urlStr = `admin-api${url}`;
			if(urlStr.includes('app-api')){
				urlStr = url;
			}

			const requestTask = uni.request({
				url: `${apiBaseUrl}${urlStr}`,
				header: _headers,
				data: params,
				method: options.method,
				timeout: timeout,
				success(res) {
					if (res.data.code == 0) {

						//测试出输出信息
						if (process.env.NODE_ENV === 'development') {
							console.log({
								data: res.data.data
							})
						}

						resolve(res.data.data)
					} else if(res.data.code === 666 || res.data.code === 566) {
            // 666需要二次移出，566需要二次预装
            resolve(res.data)
          } else {
						if (options.errorHandle) {
							errorHandler(res.data, reject)
						} else {
							reject(res.data)
						}
					}
				},
				fail(error) {
					if (options.errorHandle) {
						errorHandler(error, reject)
					}
					reject(error)
				},
				complete() {
					if (options.loading) {
						uni.hideLoading({})
					}
				}
			})
		})
	}
}
