'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});
exports.isFileAPISupported = exports.isTouchDevice = exports.retrieveImageURL = exports.parseDOM = exports.getParseUrl = exports.getConstructUrl = exports.getCroppedImg = exports.initPage = exports.initObj = exports.initItem = exports.initSelect = exports.attrAccept = exports.getUid = undefined;

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _extends3 = require('babel-runtime/helpers/extends');

var _extends4 = _interopRequireDefault(_extends3);

var _typeof2 = require('babel-runtime/helpers/typeof');

var _typeof3 = _interopRequireDefault(_typeof2);

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var now = +new Date();
var index = 0;

var getUid = exports.getUid = function getUid() {
	return 'rc-' + now + '-' + ++index;
};

var endsWith = function endsWith(str, suffix) {
	return str.indexOf(suffix, str.length - suffix.length) !== -1;
};

var attrAccept = exports.attrAccept = function attrAccept(file, acceptedFiles) {
	if (file && acceptedFiles) {
		var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(',');
		var fileName = file.name || '';
		var mimeType = file.type || '';
		var baseMimeType = mimeType.replace(/\/.*$/, '');

		return acceptedFilesArray.some(function (type) {
			var validType = type.trim();
			if (validType.charAt(0) === '.') {
				return endsWith(fileName.toLowerCase(), validType.toLowerCase());
			} else if (/\/\*$/.test(validType)) {
				// This is something like a image/* mime type
				return baseMimeType === validType.replace(/\/.*$/, '');
			}
			return mimeType === validType;
		});
	}
	return true;
};

// -- 业务相关 --

var initSelect = exports.initSelect = function initSelect(res, value, label, children) {
	var level = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;

	var __arr = [];
	var __child = [];
	if (res instanceof Array && level > 0) {
		for (var j = 0; j < res.length; j++) {
			__arr = [].concat((0, _toConsumableArray3.default)(__arr), [{
				value: res[j][value] || j,
				label: res[j][label] || res[j],
				children: initSelect(res[j][children], value, label, children, level - 1)
			}]);
		}
		return __arr;
	}
	return level == 0 ? undefined : [];
};
/**
 * 初始化数据
 * @param  {String} res 传入的数据
 * @param  {String} id  数组是已str区分 ，默认'id'
 * @param  {String} _count
 * @param  {Object} initObj 判断是否有init
 * @param  {Array} initArr 判断是否有init
 * @return {String}
 * 参考reducers中的使用
 */
var initItem = exports.initItem = function initItem(res, str, count, initObj, initArr) {
	var itemArr = [];
	var itemObj = {};
	var data = void 0;
	var id = str || 'id';
	if ((typeof res === 'undefined' ? 'undefined' : (0, _typeof3.default)(res)) == "object" && res.data && res.data instanceof Array) {
		// 传入的不是数组。res.data是数组
		data = res.data;
	} else if (res instanceof Array) {
		// 传入的是数组
		data = res;
	} else {
		return console.error('初始化参数错误');
	}
	for (var i = 0; i < data.length; i++) {
		itemArr = [].concat((0, _toConsumableArray3.default)(itemArr), [data[i][id]]);
		itemObj = (0, _extends4.default)({}, itemObj, (0, _defineProperty3.default)({}, data[i][id], initObj || data[i]));
	}
	/* 判断是否有_count*/
	if (count) {
		var _count = res._count;

		return { itemArr: itemArr, itemObj: itemObj, _count: _count };
	} else {
		return { itemArr: itemArr, itemObj: itemObj };
	}
};
/**
 * 作为分页初始数据
 * for mobile
 */
var initObj = exports.initObj = {
	currentPage: 0, // 当前页数
	totalPage: 1, // 总页数
	isEnd: 0, // 是否正在加载 0 上拉加载，1为加载中，2为已全部加载,3数据异常
	itemArr: [],
	itemObj: {}

};
/**
 * 作为分页初始数据
 * for pc
 */
var initPage = exports.initPage = {
	curPage: 0, // 当前页数
	totalPage: 1, // 总页数
	totalCount: 0,
	pageSize: 10, // 条数
	isEnd: 0, // 是否正在加载 0 上拉加载，1为加载中，2为已全部加载,3数据异常
	itemArr: {},
	itemObj: {}
};
/**
 * 图片
 */
var getCroppedImg = exports.getCroppedImg = function getCroppedImg(canvas) {
	var fileName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '____fileName';
	var getFile = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

	// As base64
	var base64Image = canvas.toDataURL("image/png");
	// As a blob 移动端不兼容
	return new Promise(function (resolve, reject) {
		var file = void 0;
		if (getFile) {
			var arr = base64Image.split(',');
			var mime = arr[0].match(/:(.*?);/)[1];
			var bstr = atob(arr[1]);
			var n = bstr.length;
			var u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			file = new Blob([u8arr], { type: mime });
			// file = (typeof File && fileName) ? new File([file], fileName) : file;
			file.name = fileName;
		}
		resolve({ file: file, base64Image: base64Image });
	});
};
/**
 * 重构url
 * @param  {Object}
 * @return {String}
 */
var getConstructUrl = exports.getConstructUrl = function getConstructUrl(route) {
	var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
	// 创建新的url
	var path = route.path,
	    query = route.query;

	var result = path.join('/');
	var queryArr = [];
	if (query && (typeof query === 'undefined' ? 'undefined' : (0, _typeof3.default)(query)) === 'object') {
		queryArr = Object.keys(query).sort().filter(function (key) {
			return query[key] !== null;
		}).map(function (key) {
			return key + '=' + query[key];
		});
	}

	if (queryArr.length > 0) {
		result += '?' + queryArr.join('&');
	}

	return result;
};
/**
 * 解析url
 * @param  {String} url
 * @return {Object}
 */
var getParseUrl = exports.getParseUrl = function getParseUrl() {
	var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '' + location.pathname + location.search;
	var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
	// 解析url
	var path = [];
	var query = {};
	// const urlArr = url.replace('/', '').split('?');
	var urlArr = url.split('?');
	path = urlArr[0].split('/');

	if (urlArr.length > 1) {
		urlArr[1].split('&').forEach(function (str) {
			var arr = str.split('=');
			var key = arr[0];
			var value = arr[1];
			if (isNaN(value) || value[0] === '0') {
				query[key] = value;
			} else {
				query[key] = Number(value);
			}
		});
	}

	return {
		path: path,
		query: query
	};
};
var parseDOM = exports.parseDOM = function parseDOM(str) {
	var parser = typeof DOMParser === 'undefined' ? null : new DOMParser();

	if (!parser) {
		return null;
	}
	return parser.parseFromString(str, 'text/html');
};

var retrieveImageURL = exports.retrieveImageURL = function retrieveImageURL(dataTransferItems, callback) {
	for (var i = 0; i < dataTransferItems.length; i++) {
		var item = dataTransferItems[i];
		if (item.type === 'text/html') {
			item.getAsString(function (value) {
				// value = <img src="" ... /> 即网页拖入的值
				var doc = parseDOM(value); // 生成一个document 类似iframe（但有区别）
				var img = doc.querySelector('img');
				if (img && img.src) {
					callback(img.src);
				}
			});
			break;
		}
	}
};

var isTouchDevice = exports.isTouchDevice = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && ('ontouchstart' in window || navigator.msMaxTouchPoints > 0));

var isFileAPISupported = exports.isFileAPISupported = typeof File !== 'undefined';

/**
 * ios 11 fixed input bug
 */
// const isiOS11 = _global.device.ios && parseInt(_global.device.osVersion) == 11;
// const iOS11Set = () => {
// 	if (isiOS11 ) {
// 		const $ = document.getElementById('pages');
// 		$.style.overflow = 'hidden';
// 		$.style.height = window.innerHeight + `px`;
// 	};
// };
// const iOS11Remove = () => {
// 	if (isiOS11 ) {
// 		const $ = document.getElementById('pages');
// 		$.style.removeProperty("overflow");
// 		$.style.removeProperty("height");
// 	};
// };
// const iOS11Absolute = isiOS11 ? { position: `absolute` } : {};
// const iOS11Relative = isiOS11 ? { position: `relative` } : {};
// const iOS11FlexEnd = isiOS11
// 	? { // 暂时这里不先考虑兼容
// 		display: `flex`,
// 		alignItems: `flex-end`,
// 		height: `100%`
// 	}
// 	: {};
// const iOS11FlexCenter = isiOS11
// 	? { // 暂时这里不先考虑兼容
// 		display: `flex`,
// 		alignItems: `center`,
// 		justifyContent: `center`,
// 		height: `100%`
// 	}
// 	: {};
// export const hackForiOS11 = {
// 	ios11: isiOS11,
// 	set: iOS11Set,
// 	remove: iOS11Remove,
// 	absolute: iOS11Absolute,
// 	relative: iOS11Relative,
// 	flexEnd: iOS11FlexEnd,
// 	flexCenter: iOS11FlexCenter
// };