var url = API.API_URL();
mui.init();

var viewApi = mui('#app').view({
	defaultPage: '#setting'
});

//初始化单页的区域滚动
mui('.mui-scroll-wrapper').scroll({

	bounce: false, //滚动条是否有弹力默认是true

	indicators: false //是否显示滚动条

});
//			mui("#pullrefresh").pullRefresh().setStopped(true);
//			mui('#pullrefresh').pullRefresh().setStopped(true); //暂时禁止滚动
var view = viewApi.view;

function test(o) {
	alert(o);
};
(function($, doc) {

	//处理view的后退与webview后退
	var oldBack = $.back;
	$.back = function() {
		if(viewApi.canBack()) { //如果view可以后退，则执行view的后退
			viewApi.back();
		} else { //执行webview后退
			oldBack();
		}
	};
	//监听页面切换事件方案1,通过view元素监听所有页面切换事件，目前提供pageBeforeShow|pageShow|pageBeforeBack|pageBack四种事件(before事件为动画开始前触发)
	//第一个参数为事件名称，第二个参数为事件回调，其中e.detail.page为当前页面的html对象
	view.addEventListener('pageBeforeShow',
		function(e) {
			console.log(e.detail.page.id + ' beforeShow');
		});
	view.addEventListener('pageShow', function(e) {
		console.log(e.detail.page.id + ' show');
	});
	view.addEventListener('pageBeforeBack', function(e) {
		console.log(e.detail.page.id + ' beforeBack');
	});
	view.addEventListener('pageBack', function(e) {
		console.log(e.detail.page.id + ' back');
	});
})(mui);


var vm = new Vue({
	el: '#startFlow', //bodydiv
	data: {
		selModelId:'',
		flow: {},
		nextTmodels: [],
		nextHandTmodels: []
	},
	methods: {
		getTUserName: function(tmodel) {
			return "usersName" + tmodel.nextTmodelId;
		},
		getTUserId: function(tmodel) {
			return "users" + tmodel.nextTmodelId;
		},
	}
});

//获取流程信息
function getStartFlow(modelId) {

	mui.ajax(url, {

		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		data: {
			'serviceId': 'bpm_20150319002GetStartFlowInfo',
			'params': '{modelId:"' + modelId + '"}'
		},
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Accept': 'application/json'
		},
		success: function(data) {
			//服务器返回响应
			console.log("流程信息:" + JSON.stringify(data));
			if(data.returnCode == "0") {
				var returnParams = data.returnParams;
				vm.flow = returnParams.flow[0];
				vm.nextTmodels = returnParams.nextTmodels;
				vm.nextHandTmodels = returnParams.nextHandTmodels;
				if(vm.nextTmodels.length != 0){
					vm.selModelId = vm.nextTmodels[0].nextTmodelId;
				}
			} else {
				mui.toast("获取流程信息错误");
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(xhr + "========" + type + "===========" + errorThrown);
		}
	});
};

//表单驳回按钮
var returnBth = document.getElementById("returnBth");
returnBth.addEventListener("click", function() {
	alert('是否取消');
	location.href = "../process.html";
});

//表单提交按钮
var saveBtn = document.getElementById("saveBtn");
saveBtn.addEventListener("click", function() {
	var title = $(".mui-title").html();
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	var staffName = state.user.name;
	var gxId = state.user.gxId;
	var groupId = state.user.groupid;
	var modelId = vm.flow.modelId;
	var tmodelId = vm.flow.tmodelId;
	var pathJudgeType = vm.flow.pathJudgeType; //0并行分支,1手动分支,2条件分支 
	var nextHandTmodels = vm.nextHandTmodels;
	var formId = vm.flow.formId;
	var usesNames = [];
	
	if(1 == pathJudgeType) {
		var nextTmodelId = $("#nextTmodelId").val(); //手动选择选中的下一环节
		if(nextTmodelId == "") {
			alert("请选择下一环节");
			return;
		}
		if(nextHandTmodels.length > 0) {
			var username = $("#" + nextTmodelId).attr("userId");
			if(username == "" || !username) {
				alert("请选择环节操作人");
				return;
			}
		}
		usesNames = [{
			nextTmodelId: nextTmodelId,
			username: username
		}];
	} else if(0 == pathJudgeType) {
		if(nextHandTmodels.length > 0) {
			for(var i = 0; i < nextHandTmodels.length; i++) {
				var nextTmodelId = nextHandTmodels[i].nextTmodelId;
				var username = $("#" + nextTmodelId).attr("userId");
				if(username == "" || !username) {
					alert("请选择环节操作人");
					return;
				}
				usesNames.push({
					nextTmodelId: nextTmodelId,
					username: username
				});
			}
		}
	}
		
	var insName = state.user.name+title;
	var fileIds = $("#fileIds").val();//附件id
	if(!fileIds){
		fileIds = "";
	}

	var flow = '{staffId:"' + staffId + '",staffName:"' + staffName + '",gxId:"' + gxId + '",insName:"'+insName+'",tmodelId:"' + tmodelId + '",modelId:"' + modelId + '",fileIds:"' + fileIds + '",groupId:"' + groupId + '",usesNames:' + JSON.stringify(usesNames) + '}';
	//表单字段信息
	var formElements = $("#form_element").serializeArray();
	
	
	var form = '{formId:"' + formId + '",formElements:' + JSON.stringify(formElements) + '}';
	document.getElementById("saveBtn").disabled =true; //按钮变灰不可用
	console.log(flow);
	jQuery.ajax({
		type: 'POST',
		dataType: 'json', //服务器返回json格式数据
		url: url,
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		data: {
			'serviceId': 'bpm_20150325001FlowStart',
			'params': '{flow:' + flow + ',form:' + form + '}'
		},
		success: function(data) {
			if(data.returnCode == 0) {
				alert('提交成功');
				mui.openWindow({
					createNew: true,
					url: "../process.html",
					extras: {}
				});
			
			} else {
				alert('提交失败：' + data.msg);
				location.reload();
			}
		},
		error: function(html) {
			var flag = (typeof console != 'undefined');
			if(flag){
				console.log("服务器忙，提交数据失败，代码:" + html.status + "，请联系管理员！");
				alert("服务器忙，提交数据失败，请联系管理员！");
			}
		}
	});
});

//上传附件
function file_upload(fileIds) {
	var formData = new FormData($("#fileForm")[0]);
	jQuery.ajax({
		type: 'POST',
		url: API.API_ROOT+'/uploadFileRecorderAction.do',
		data: formData,
		// 告诉jQuery不要去处理发送的数据
		processData: false,
		// 告诉jQuery不要去设置Content-Type请求头
		contentType: false,
		success: function(data) {
			console.log(data);
			$('#'+fileIds).val(data);
		},
		error: function(html) {
			var flag = (typeof console != 'undefined');
			if(flag)
				console.log("服务器忙，提交数据失败，代码:" + html.status + "，请联系管理员！");
			alert("服务器忙，提交数据失败，请联系管理员！");
		}
	});
}