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

import MD5 from 'crypto-js/md5'

let headers = {
	// "Content-Type": "multipart/form-data"
}

/**
 * 生成签名
 * @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
}

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

export default (url = '', files, params = {}, options = {}) => {

	options = Object.assign({
		loading: false,
		errorHandle: true
	}, options)

	//签名
	// const signStr = sign(params);
	// params.sign = signStr

	return new Promise((resolve, reject) => {
		if (options.loading) {
			uni.showLoading({})
		}
		
		uni.uploadFile({
			url: apiBaseUrl + url,
			filePath: files,
			header: params,
      name: 'file',
			success: (res) => {
				console.log(res)
				if (res.statusCode == 200) {
					res.data = JSON.parse(res.data)
					if (res.data.code == 0) {
						
						//测试出输出信息
						if (process.env.NODE_ENV === 'development') {
							// console.log({
							// 	data: res.data
							// })
						}
						console.log(11, res.data.data)
						resolve(res.data)
					} else {
						if (options.errorHandle) {
							errorHandler(res.data, reject)
						} else {
							reject(res.data)
						}
					}
				} else {
					if (options.errorHandle) {
						errorHandler(res.data, reject)
					} else {
						reject(res.data)
					}
				}
			},
			fail(res) {
				// debugger
				// if (options.errorHandle) {
				// 	errorHandler(error, reject)
				// }
				console.log(res)
			},
			complete() {
				if (options.loading) {
					uni.hideLoading({})
				}
			}
		})
	})
}
