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();
	})
}
var tinsId = "";
var insId = "";
var did = "";
mui.plusReady(function() {

	var self = plus.webview.currentWebview();
	tinsId = self.tinsId;
	insId = self.insId;
	did = self.did;
	getFlowInfo();
	getProcessflow();
	getFormInfo();

});

var vm2 = new Vue({
	el: '#dispatch_info',
	data: {
		dispatch_infos: {},
		files: {}
	}
});

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

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

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

//获取表单信息
function getFormInfo() {
	//开启等待框
	var 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': 'oa_Dispatch_2018V0010PHONE004',
			'params': '{staffId:"' + staffId + '",did:"' + did + '"}'
		},
		timeout: 10000, //超时时间设置为10秒；
		headers: {
			'Accept': 'application/json'
		},
		success: function(data) {
			//服务器返回响应
			if(data && data.returnCode == "0") {
				//关闭等待框
				var t = setInterval(function() {
					w.setTitle("处理中，请等待...");
					w.close();
					clearInterval(t);
				}, 1000);
				vm2.files = data.returnParams.files;
				vm2.dispatch_infos = data.returnParams.dispatchInfo;
			} 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 modelId = vm3.tmodel.modelId;
	var tmodelId = vm3.tmodel.tmodelId;
	var preTinsId = vm3.tache.preTinsId;
	var pathJudgeType = vm3.tmodel.pathJudgeType.value; //0并行分支,1手动分支,2条件分支 
	var isMoreIns = vm3.tmodel.isMoreIns.value;
	var se = vm3.tmodel.se.value;
	var insName = vm3.flow.insName;
	var nextTmodelId = vm3.nextTmodels[0].nextTmodelId.tmodelId;
	var nextHandTmodels = vm3.nextHandTmodels;
	var usesNames = [];
	var ids = vm2.dispatch_infos.id;
	var selModelId = vm3.selModelId;
	
	if(result == 1) {
		if(1 == pathJudgeType) {
			var nextTmodelId = $("#nextTmodelId").val(); //手动选择选中的下一环节
			if(nextTmodelId == "") {
				alert("请选择下一环节");
				return;
			}
			$("textarea[id*='usersName']:visible")
			if(nextHandTmodels.length > 0 && $("input[id="+selModelId+"]:visible").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 && $("input[id="+selModelId+"]:visible").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
					});
				}
			}
		}
	}
	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 remark1 = $("#remark1").val();
	var flow = '{staffId:' + staffId + ',gxId:' + gxId + ',insName:"' + insName + '",tmodelId:"' + tmodelId +
		'",modelId:"' + modelId + '",insId:"' + insId + '",tinsId:"' + tinsId + '",preTinsId:"' + preTinsId +
		'",groupId:"' + groupId + '",isMoreIns:"' + isMoreIns +'",did:"' + did +
		'",se:"' + se + '",nextTmodelId:"' + nextTmodelId + '",remark1:"' + remark1 + '",usesNames:' + JSON.stringify(usesNames) + '}';
	//表单字段信息
	var dispatch_infos = $("#dispatch_info").serializeArray();
	var form = '{dispatch_info:' + JSON.stringify(dispatch_infos) +'}';
	console.log(flow);
	jQuery.ajax({
		dataType: 'json', //服务器返回json格式数据
		type: 'POST',
		url: url,
		contentType: "application/x-www-form-urlencoded; charset=utf-8",
		data: {
			'serviceId': 'oa_Dispatch_2018V0010PHONE006',
			'params': '{flow:' + flow + ',form:' + form + '}'
		},
		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: "dispatch_approve_list.html",
					extras: {}
				});
			} else if(data.returnCode == "2") {
				mui.toast(data.returnMsg);
				mui.openWindow({
					createNew: true,
					url: "dispatch_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();
}