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

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

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

var view = viewApi.view;

(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);

if(!mui.os.plus) {
	mui.ready(function() {
		getFlowInfo();
		getFormInfo();
	})
}
mui.plusReady(function() {

	var self = plus.webview.currentWebview();
	tinsId = self.tinsId;
	insId = self.insId;
	modelName = self.modelName;
	//	var title1 = mui('#title');
	//	title1[0].innerHTML = modelName;
	console.log("tinsId=====" + tinsId + "====insId====" + insId);
	getFlowInfo();
	getProcessflow();
	getFormInfo();

});

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

//流程表单
var vm3 = new Vue({
	el: '#form_element',
	data: {
		formInfo: {},
		formElements: []
	}
});

//获取流程信息
function getFlowInfo() {
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	mui.ajax(url, {
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		data: {
			'serviceId': 'bpm_2013V0100PHONE005',
			'params': '{staffId:"' + staffId + '",tinsid:"' + tinsId + '"}'
		},
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Accept': 'application/json'
		},
		success: function(data) {
			//服务器返回响应
			console.log("流程信息:" + JSON.stringify(data));
			if(data && data.returnCode == "0") {
				var returnParams = data.returnParams;
				vm.flow = returnParams.flow[0];
				vm.tmodel = returnParams.tmodel;
				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);
		}
	});
};

//流程流转信息
function getProcessflow() {
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	mui.ajax(url, {
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		data: {
			'serviceId': 'bpm_2013V0100PHONE007',
			'params': '{staffId:"' + staffId + '",insid:"' + insId + '"}'
		},
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Accept': 'application/json'
		},
		success: function(data) {
			//服务器返回响应
			console.log("流转过程信息:" + JSON.stringify(data));
			if(data && data.returnCode == "0") {
				var returnParams = data.returnParams.list;
				if(returnParams.length > 0) {
					vm.processList = vm.processList.concat(returnParams);

				}
			} else {
				mui.toast("获取流程信息错误");
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(xhr + "========" + type + "===========" + errorThrown);
		}
	});
};
//获取表单信息
function getFormInfo() {
	//开启等待框
	var w = null;
	if(mui.os.plus) {
		w = plus.nativeUI.showWaiting("处理中，请等待...", {
			loading: {
				display: "inline"
			}
		});
	}
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	mui.ajax(url, {
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		data: {
			'serviceId': 'bpm_2013V0100PHONE006',
			'params': '{staffId:"' + staffId + '",tinsid:"' + tinsId + '",insId:"' + insId + '"}'
		},
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Accept': 'application/json'
		},
		success: function(data) {
			//服务器返回响应
			console.log("表单信息:" + JSON.stringify(data));
			if(data && data.returnCode == "0") {
				//关闭等待框
				if(mui.os.plus) {
					var t = setInterval(function() {
						w.setTitle("处理中，请等待...");
						w.close();
						clearInterval(t);
					}, 1000);
				}
				var returnParams = data.returnParams;
				var returnParams = data.returnParams;
				vm3.formInfo = returnParams.formInfo[0];
				vm3.formElements = returnParams.formElements;

			} else {
				mui.toast("获取流程信息错误");
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(xhr + "========" + type + "===========" + errorThrown);
		}
	});
};

//驳回提交按钮
var returnBth = document.getElementById("returnBth");
returnBth.addEventListener("click", function() {
	flowProcess(0);
});
//表单提交按钮
var saveBtn = document.getElementById("saveBtn");
saveBtn.addEventListener("click", function() {
	flowProcess(1);
});

function flowProcess(result) {
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	var gxId = state.user.gxId;
	var groupId = state.user.groupid;
	var insId = vm.flow.insId;
	var tinsId = vm.flow.tinsId;
	var modelId = vm.flow.modelId;
	var tmodelId = vm.flow.tmodelId;
	var preTinsId = vm.flow.preTinsId;
	var pathJudgeType = vm.flow.pathJudgeType; //0并行分支,1手动分支,2条件分支 
	var isMoreIns = vm.flow.isMoreIns;
	var seModel = vm.flow.seModel;
	var insName = vm.flow.insName;
	var nextHandTmodels = vm.nextHandTmodels;
	var formId = vm3.formInfo.formId;
	var formInsId = vm3.formInfo.formInsId;
	var usesNames = [];
	if(result == 1) {
		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");
					//							alert(nextTmodelId+"======="+username);
					if(username == "" || !username) {
						alert("请选择环节操作人");
						return;
					}
					usesNames.push({
						nextTmodelId: nextTmodelId,
						username: username
					});
				}
			}
		}
	}
	document.getElementById("saveBtn").setAttribute("disabled", true); //按钮变灰不可用
	//document.getElementById("crop").removeAttribute("disabled");按钮可用方法
	//开启等待框
	var w = null;
	if(mui.os.plus) {
		w = plus.nativeUI.showWaiting("处理中，请等待...", {
			loading: {
				display: "inline"
			}
		});
	}
	var fileIds = $("#fileIds").val(); //附件id
	if(!fileIds) {
		fileIds = "";
	}
	var remark = $("#remark").val();
	var flow = '{staffId:' + staffId + ',gxId:' + gxId + ',insName:"' + insName + '",tmodelId:"' + tmodelId +
		'",modelId:"' + modelId + '",insId:"' + insId + '",tinsId:"' + tinsId + '",preTinsId:"' + preTinsId +
		'",fileIds:"' + fileIds + '",groupId:"' + groupId + '",isMoreIns:"' + isMoreIns + '",pathJudgeType:"' + pathJudgeType +
		'",seModel:"' + seModel + '",result:"' + result + '",nextTmodelId:"' + nextTmodelId + '",remark:"' + remark + '",usesNames:' + JSON.stringify(usesNames) + '}';
	//表单字段信息
	var formElements = $("#form_element").serializeArray();
	var form = '{formId:"' + formId + '",formInsId:"' + formInsId + '",formElements:' + JSON.stringify(formElements) + '}';
	console.log(flow);
	jQuery.ajax({
		dataType: 'json', //服务器返回json格式数据
		type: 'POST',
		url: url,
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		data: {
			'serviceId': 'bpm_2013V0100PHONE008',
			'params': '{flow:' + flow + ',form:' + form + '}'
		},
		// 告诉jQuery不要去处理发送的数据
		//						processData: false,
		// 告诉jQuery不要去设置Content-Type请求头
		//						contentType: false,
		success: function(data) {
			console.log("返回信息:" + JSON.stringify(data));
			if(mui.os.plus) {
				//关闭等待框
				var t = setInterval(function() {
					w.setTitle("处理中，请等待...");
					w.close();
					clearInterval(t);
				}, 1000);
			}
			if(data.returnCode == "1") {
				mui.toast(data.returnMsg);
				mui.openWindow({
					createNew: true,
					url: "../flow_approve_list.html",
					extras: {}
				});
			} else if(data.returnCode == "2") {
				mui.toast(data.returnMsg);
				mui.openWindow({
					createNew: true,
					url: "../flow_approve_list.html",
					extras: {}
				});
			} else {
				mui.toast(data.returnMsg);
				location.reload();
			}
		},
		error: function(html) {
			var flag = (typeof console != 'undefined');
			if(flag) {
				console.log("服务器忙，提交数据失败，代码:" + html.status + "，请联系管理员！");
				mui.toast("服务器忙，提交数据失败，请联系管理员！");
			}
		}
	});
}

//日期控件
function time(id) {
	var dDate = new Date();
	dDate.setFullYear(2014, 7, 16);
	var minDate = new Date();
	minDate.setFullYear(2010, 0, 1);
	var maxDate = new Date();
	maxDate.setFullYear(2016, 11, 31);
	plus.nativeUI.pickDate(function(e) {
		var d = e.date;
		var a = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
		$("#" + id).val(a);

	}, {
		title: "请选择日期",
		date: dDate,
		minDate: minDate,
		maxDate: maxDate
	});
}

//上传附件
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("服务器忙，提交数据失败，请联系管理员！");
		}
	});
}

//文件下载的任务
function openFile(path) {

	if(path.indexOf("http") == -1) {

		path = API.API_IP_PORT + "" + path;
	}
	var dtask = plus.downloader.createDownload(path, {}, function(d, status) { //创建一个下载任务，可以在网上搜索这个方法了解

		if(status == 200) {
			mui.toast("下载成功!");
			plus.runtime.openFile(d.filename, {}, function(e) { //调用第三方应用打开文件  
				alert(path);
				alert('打开失败');
			});
		} else {
			alert("Download failed: " + status);

		}

	});
	dtask.start();
}