var movable = {
	width: 100,
	height: 100,
	disabled: false,
	left: 0,
	top: 0,
	app: false
}

function isPC() {
	if (typeof navigator !== 'object') return false;
	var userAgentInfo = navigator.userAgent;
	var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
	var flag = true;
	for (var v = 0; v < Agents.length - 1; v++) {
		if (userAgentInfo.indexOf(Agents[v]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
}
var isH5 = false
if (typeof window === 'object') isH5 = true

function setInitValue(dataset) {
	movable.width = +dataset.width
	movable.height = +dataset.height
	movable.top = +dataset.top
	movable.left = +dataset.left
	//H5获取bool值为undefined
	movable.disabled = (+dataset.disabled) == 1 ? true : false
	movable.app = (+dataset.app) == 1 ? true : false
}

function touchstart(e, ins) {
	var state = e.instance.getState()
	var touch = e.touches[0] || e.changedTouches[0];
	if (isH5 && isPC()) {
		touch = e;
	}
	var dataset = e.instance.getDataset()
	state.startX = touch.clientX
	state.startY = touch.clientY
	setInitValue(dataset)
}

function styleChange(left, top, ins) {
	if (!ins) return;
	var mview = ins.selectComponent('.fui-fab__btn-wrap');
	if (!mview) return;
	mview.setStyle({
		transform: 'translate3d(' + left + 'px,' + top + 'px,0)'
	})
}

function touchmove(e, ins, events) {
	if (movable.disabled) return;
	if (e.preventDefault) {
		e.preventDefault()
	}
	if (movable.app && event && event.preventDefault && event.cancelable) {
		event.preventDefault()
	}
	var state = {}
	var touch = {}
	if (isH5 && isPC()) {
		touch = e;
		if (events && events.instance) {
			state = events.instance.getState()
		}
	} else {
		touch = e.touches[0] || e.changedTouches[0]
		state = e.instance.getState()
	}
	var pageX = touch.clientX;
	var pageY = touch.clientY;
	var left = pageX - state.startX + (state.lastLeft || 0);
	left = left < -movable.left ? -movable.left : left;
	left = left > movable.width ? movable.width : left;
	state.startX = pageX

	var top = pageY - state.startY + (state.lastTop || 0);
	top = top < -movable.top ? -movable.top : top;
	top = top > movable.height ? movable.height : top;
	state.startY = pageY

	state.lastLeft = left
	state.lastTop = top
	styleChange(left, top, ins)
}

var _movable = false;

function mousedown(e, ins) {
	if (!isH5 || !isPC()) return
	touchstart(e, ins)
	_movable = true
	window.onmousemove = function(event) {
		if (!isH5 || !isPC() || !_movable) return
		touchmove(event, ins, e)
	}
	window.onmouseup = function(event) {
		if (!isH5 || !isPC() || !_movable) return
		_movable = false
	}
}

function fabreset(reset, oldreset, owner, ins) {
	if (reset > 0) {
		var state = ins.getState()
		state.startY = 0;
		state.startX = 0;
		state.lastLeft = 0;
		state.lastTop = 0;
		styleChange(0, 0, owner)
	}
}

module.exports = {
	touchstart: touchstart,
	touchmove: touchmove,
	mousedown: mousedown,
	fabreset: fabreset
}
