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 modelId = "";
var modelName = "";

mui.ready(function() {
	if(!mui.os.plus) {
		getStartFlow(3491569617311);
	}
});

var insName = "";
mui.plusReady(function() {
	var self = plus.webview.currentWebview();
	modelId = self.modelId;
	modelName = self.modelName;
	console.log("modelId===" + modelId + "======modelName=====" + modelName);
	var title1 = mui('#title');
	var state = app.getState(); //获取登陆信息 
	insName = state.user.name + modelName
	title1[0].innerHTML = insName;
	getStartFlow(modelId);
});


function changeTitle(){
	var btn = ["确定", "取消"];
    mui.prompt('请输入标题？', insName, '重命名', function(e) {
        if(e.index == 1) {
            mui('#title')[0].innerHTML = e.value;
            insName = e.value;
        }
    });	
}


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

//获取流程信息
function getStartFlow(modelId) {
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	var groupId = state.user.groupId;
	var unitId = state.user.unitId;
	
	
	mui.ajax(url, {

		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		data: {
			'serviceId': 'bpm_20150319002GetStartFlowInfo',
			'params': '{modelId:"' + modelId + '",groupId:"' + groupId + '",unitId:"' + unitId + '",staffId:"'+staffId+'"}'
		},
		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;

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

//获取表单信息
function getFormInfo(modelId) {
	//开启等待框
	var w = null;
	if(mui.os.plus) {
		w = plus.nativeUI.showWaiting("处理中，请等待...", {
			loading: {
				display: "inline"
				
			}
		});
	}
	var state = app.getState(); //获取登陆信息
	var staffId = state.user.useId;
	var formId = vm.flow.formId;
	var tmodelId = vm.flow.tmodelId;
	
	//以下5个参数用于 getFormDefaultValue()方法中oasession需要的当前人员数据
	var loginID = state.user.useId;						//loginID 8970258956979
 	var groupName = state.user.deptName;				//groupName 开发组
 	var name = state.user.name;							//name 测试3
 	var currentPosition = state.user.positionName;		//positionName 员工
 	var id = state.user.unitId;						    //id 347517153919893
	
	var	par  = ' staffId:"' + staffId + '"';
		par += ',modelId:"' + modelId + '"';
		par += ',formId:"'  + formId + '"';
		par += ',tmodelId:"'+ tmodelId + '"';
		
		
		par += ',loginID:"'+ loginID + '"';
		par += ',groupName:"'+ groupName + '"';
		par += ',name:"'+ name + '"';
		par += ',currentPosition:"'+ currentPosition + '"';
		par += ',id:"'+ id + '"';
	mui.ajax(url, {
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		data: {
			'serviceId': 'bpm_20180525getflowform',
			'params': '{' + par +  '}'
		},
		timeout: 60000, //超时时间设置为10秒；
		headers: {
			'Accept': 'application/json'
		},
		success: function(data) {
			//服务器返回响应
			console.log("表单信息:" + JSON.stringify(data));

			var elementID = '';
			for(var p in vm3.formElements){
				if(vm3.formElements[p].type == 13 && vm3.formElements[p].canEdit == 1 ){
					elementID =	vm3.formElements[p].tableField;
				}
			}
				
			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;
				
				//以下部分用于下拉多选
				var arr = new Array();
				var i=0;
				for(var p in vm3.formElements){
					if(vm3.formElements[p].type == 5){
						arr[i] = vm3.formElements[p].tableField;
						++i;
					}
				}				
				vm3.$nextTick(function(){							//数据加载完成之后
					for(var i=0;  i<arr.length; i++){				//多选的表单的tableField
						var id = arr[i]+'dept'						//select框的ID
						//console.log(id);
						changevalue(id);							//进行select框与input框的状态(显示/隐藏)转换及数据的显示
					}
				});
				
				//以下代码用于执行表单动作
				vm3.$nextTick(function(){							//数据加载完成之后
					SUMANDCHANGE();
				});			
				
				//定时判断是否选中下一环节操作人，填充申请表单人名
				//fillName();
			} else {
				mui.toast("获取流程信息错误");
			}
		},
		error: function(xhr, type, errorThrown) {
			//异常处理；
			console.log(xhr + "========" + type + "===========" + errorThrown);
		}
	});
};

function SUMANDCHANGE(){
	
	for(var p in vm3.formElements){
		if(vm3.formElements[p].Bddz == "合计"){
			var rule =  vm3.formElements[p].BddzText.replace(/my:/g,'');
			var tar =  vm3.formElements[p].tableField;
			//console.log(rule);
			var i=0;
			var arrRule = new Array();
			for(var p in vm3.formElements){
				if(rule.indexOf(vm3.formElements[p].elementName) >=0 ){
					arrRule[i] = vm3.formElements[p].tableField;
					++i;
				}
			}	
			//console.log(arrRule);
			//为arr中的id添加事件
			for(var p in arrRule){	
				document.getElementById(arrRule[p]).addEventListener("change",function(){
				   	var Sum = 0;										//总计
					for(var a in arrRule){						
						var val = $('#' + arrRule[a]).val();			//金额 1 2 3 
					   	//console.log(val);
						if(val != ""){
							var isNum = isIntNum(val);					//金额1 2 3是否是--非负浮点数
							if(!isNum){
								mui.toast('请填入正确的数字  -- ' + val);
								doSum =false;
							}else{
								Sum += parseFloat(val);								//累加
							}
						}
					}
					$("#" + tar).val(Sum.toFixed(2));
					$("#" + tar).trigger("input");
				})
			}
		}
		if(vm3.formElements[p].Bddz == "转大写"){
			
			var srcrule =  vm3.formElements[p].BddzText.replace(/my:/g,'');
			var tarid =  vm3.formElements[p].tableField;
			var tarname = vm3.formElements[p].elementName
			//console.log("srcrule = " +srcrule);
			//console.log("tarname + tarid = " + tarname + tarid);
			var srcid = '';
			for(var p in vm3.formElements){
				if(srcrule.indexOf(vm3.formElements[p].elementName) >=0 ){
					srcid = vm3.formElements[p].tableField;
				}
			}
			//console.log("srcid "+srcid);
			$("#" +srcid).bind("input propertychange",function () {
				var val = $("#" +srcid).val();
				var dxval = DX(val);
				$("#" + tarid).val(dxval);
	        });
		}
	}
}

function DX(n) {    
    var fraction = ['角', '分'];    
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];    
    var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];    
    var head = n < 0? '欠': '';    
    n = Math.abs(n);    
  
    var s = '';    
  
    for (var i = 0; i < fraction.length; i++){    
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');    
    }    
    s = s || '整';    
    n = Math.floor(n);    
  
    for (var i = 0; i < unit[0].length && n > 0; i++){    
        var p = '';    
        for (var j = 0; j < unit[1].length && n > 0; j++)     
        {    
            p = digit[n % 10] + unit[1][j] + p;    
            n = Math.floor(n / 10);    
        }    
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;    
    }    
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');    
}


function isIntNum(val){
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val)){
        return true;
    }else{
        return false;
    }
}

function changevalue(id){
	$('#'+id).chosen().change(function(){		//当select框的值改变时
		$('#'+id).hide();						//隐藏select框
		
		console.log("值" + $('#'+id).val());
		idinput = id.substring(0,id.length-4);	//input框的ID
		$('#'+idinput).val(  $('#'+id).val() );
		$('#'+idinput).show();					//显示input框
		document.getElementById(idinput).addEventListener('tap', function() {	//input框与select框转换
			$('#'+id).show();
			$('#'+idinput).hide();
		});							
	});
}

function fillName(){		//定时判断是否选中下一环节操作人，填充申请表单人名
	
	var time = setInterval(function(){
		var src = $('#' + vm.nextHandTmodels[0].nextTmodelId).val();	//发起流程时只有一个nextHandTmodels
		if(src != ''){
			window.clearInterval(time);
			//console.log("选中的值 = " + src);			
			//console.log("评审人模板id = " + vm.nextHandTmodels[0].nextTmodelId + ' 评审人身份 ' + vm.nextHandTmodels[0].nextTmodelName);
			for(var i=0; i < vm3.formElements.length; i++ ){
				if(vm.nextHandTmodels[0].nextTmodelName  ==  vm3.formElements[i].elementName){
					//console.log("tableField = " + vm3.formElements[i].tableField);
					$('#' + vm3.formElements[i].tableField).val(src);
				}
			}
		}
	},3000);
}

//表单提交按钮
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 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();
	
	
	//效验 noNull为1（不可为空）0（可为空） 时的数据是否为空
	var srcShuju = vm3.formElements;	// 加载的表单数据，包含noNull属性
	var formShuju = formElements;		// 只要两个属性name/value，填写完成后的
	
	for(var i=0; i<srcShuju.length; i++){
		if(srcShuju[i].noNull == 1){
			//console.log('elementName = ' + srcShuju[i].elementName + ' -- ' + formShuju[i].value);
			if(formShuju[i].value == ""){
				alert("请完成"+srcShuju[i].elementName);
				return;
			}
		}
	}
	
	var form = '{formId:"' + formId + '",formElements:' + JSON.stringify(formElements) + '}';
	document.getElementById("saveBtn").setAttribute("disabled", true); //按钮变灰不可用
	//document.getElementById("crop").removeAttribute("disabled");按钮可用方法
	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: "../flow_main.html",
					extras: {}
				});

			} else {
				alert('提交失败：' + data.msg);
				location.reload();
			}
		},
		error: function(html) {
			var flag = (typeof console != 'undefined');
			if(flag) {
				console.log("服务器忙，提交数据失败，代码:" + html.status + "，请联系管理员！");
				alert("服务器忙，提交数据失败，请联系管理员！");
			}
		}
	});
});

//时间控件
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);
	var dTime = new Date(); 
    dTime.setHours(6, 0); 
	plus.nativeUI.pickDate(function(e) {
		var d = e.date;
		var a = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() ;
		
		plus.nativeUI.pickTime(function(e) { 
        var d = e.date; 
        $("#" + id).val(a + ' ' + d.getHours() + ":" + d.getMinutes());
	    },{ 
	        title: "请选择时间", 
	        is24Hour: true, 
	        time: dTime 
	    });
	}, {
		title: "请选择日期",
		date: dDate,
		minDate: minDate,
		maxDate: maxDate
	});      
}

//日期控件
function date(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);
	var dTime = new Date(); 
    dTime.setHours(6, 0); 
	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 openDrawingBoard(elementID){
	
	mui.openWindow({
		url: "drawingBoard.html",
		extras: {
			'elementID':elementID,
			'type':1
		}
	});
}









