
// 每个tab的页码
var pageNum=0, pageNumArea=0, pageNumUser=0, pageNumTime=0;
// 每个tab页的下拉对象
var tab1_self = null, tab2_self = null, tab3_self = null, tab4_self = null;
// 从URL中获取的项目id,用于新建项目消息点击查看详情
var projectId = getQueryString("projectId");

var project_list_item_html = 
	'<li class="mui-table-view-cell">'+
		'<div class="mui-table">'+
			'<div class="mui-table-cell">'+
				'<h4 class="mui-ellipsis-2 p-title" dataid="{dataid}">'+
					'{name}'+
					'&nbsp;<span class="mui-badge">{area}</span>'+
				'</h4>'+
				'<table class="nbclass-table">'+
					'<tr>'+
						'<td class="mui-h5 td-label">创建人员：</td>'+
						'<td class="mui-h5">{createUserName}</td>'+
						'<td class="mui-h5 text-right pl15 td-label">创建时间：</td>'+
						'<td class="mui-h5">{createTime}</td>'+
					'</tr>'+
					'<tr>'+
						'<td class="mui-h5">重要程度：</td>'+
						'<td class="mui-h5">{importanceName}</td>'+
						'<td class="mui-h5 text-right pl15">负责人员：</td>'+
						'<td class="mui-h5">{fzrNames}</td>'+
					'</tr>'+
					'<tr>'+
						'<td class="mui-h5">计划时间：</td>'+
						'<td class="mui-h5" colspan="3">{startTime} ~ {endTime}</td>'+
					'</tr>'+
					'<tr>'+
						'<td class="mui-h5">客户单位：</td>'+
						'<td class="mui-h5" colspan="3">{typeName}</td>'+
					'</tr>'+
					'<tr>'+
						'<td class="mui-h5">对接人员：</td>'+
						'<td class="mui-h5" colspan="3">{customer}</td>'+
					'</tr>'+
					'<tr>'+
						'<td class="mui-h5">合同编号：</td>'+
						'<td class="mui-h5" colspan="3" style="width: 100%;">{contractno}'+
							'<div class="text-right" colspan="3" style="float:right; text-align:right;">项目状态：{status}</div>'+
						'</td>'+
					'</tr>'+
				'</table>'+
			'</div>'+
		'</div>'+
	'</li>';


mui.init({
	swipeBack:false //启用右滑关闭功能
});

mui('.mui-scroll-wrapper-projectdetails').scroll(); // 项目详情弹出层开启滚动条


//通过jsapi选择企业联系人
function selectEnterpriseContact(type){
	var seltype = [];
	seltype.push(type);
	
	var select_deptIds = '', select_userIds = '';
	var select_deptNames = '', select_userNames = '';

	wx.invoke("selectEnterpriseContact", {
     "fromDepartmentId": -1,// 必填，表示打开的通讯录从指定的部门开始展示，-1表示自己所在部门开始, 0表示从最上层开始
		"mode": "single",	// 必填，选择模式，single表示单选，multi表示多选
	//	"type": ["department", "user"],// 必填，选择限制类型，指定department、user中的一个或者多个
		"type": seltype,
     "selectedDepartmentIds": [],// 非必填，已选部门ID列表。用于多次选人时可重入，single模式下请勿填入多个id
     "selectedUserIds": []	// 非必填，已选用户ID列表。用于多次选人时可重入，single模式下请勿填入多个id
        },function(res){
      		if(!(res.err_msg == "selectEnterpriseContact:ok")){
      		//	alert('获取企业微信联系人失败 ......');
      			return;
      		}
       		if(typeof res.result == 'string'){
          		res.result = JSON.parse(res.result) // 由于目前各个终端尚未完全兼容，需要开发者额外判断result类型以保证在各个终端的兼容性
       		}
       		
       		if(seltype == 'department'){ // 选择部门
       			var selectedDepartmentList = res.result.departmentList;// 已选的部门列表
           		for (var i = 0; i < selectedDepartmentList.length; i++){
              		var department = selectedDepartmentList[i];
              		var departmentId = department.id;// 已选的单个部门ID
               		var departemntName = department.name;// 已选的单个部门名称
               		select_deptIds += ((select_deptIds=='')?'':',') + departmentId;
               		select_deptNames += ((select_deptNames=='')?'':', ') + departemntName;
               		$('#s_departmentid').val(select_deptIds);
               		$('#s_departmentname').val(select_deptNames);
              	}
       		}else{ // 选择用户
       			var selectedUserList = res.result.userList; // 已选的成员列表
              	for (var i = 0; i < selectedUserList.length; i++){
              		var user = selectedUserList[i];
                  	var userId = user.id; // 已选的单个成员ID
               		var userName = user.name;// 已选的单个成员名称
                  	var userAvatar= user.avatar;// 已选的单个成员头像
              		select_userIds += ((select_userIds=='')?'':',') + userId;
              		select_userNames += ((select_userNames=='')?'':', ') + userName;
              		$('#s_userid').val(select_userIds);
              		$('#s_username').val(select_userNames);
      			}
       		}
		}
	);
}


//根据项目ID查询项目详情
function getProjectDetail(pid){
	$.post(ctxPath+'mobile/api/project/findById', {id:pid}, function(result){
		var hasContent = false;
		if(result.ret == 0 && result.name){
			$('#btngroups').attr("dataid", result.id);
			hasContent = (result.content!=null && $.trim(result.content)!='');
		}
		$('#project-content').html(hasContent ? result.content : '<p style="text-align:center;">该创建者很懒，什么内容都没写下~</p>');
	}, 'json');
}

// 查询项目列表 - 所有
function getProjectList(page,self){
	var pagesize = 15;
	var params = {};
	params['offset'] = page;
	params['limit'] = pagesize;
	params['name']  = $('#searchInput').val();
	params['id']  = projectId;
	
	if(page == 1)$('#project-all-list').html('');
	$.post(ctxPath+'mobile/api/project/getList', params, function(result){
		if(result.total == 0 || result.total<=(page*pagesize) || page>20){ // 超过10页不加载了(加载数据太多页面容易崩)
			if(self)self.endPullUpToRefresh(true);	// 当为true时，底部出现没有更多数据，并且不能滑动
		}else{
			if(self)self.endPullUpToRefresh();	// 当为false或空时，底部出现正在加载，滑动到下一页
		}
		if(result.total > 0 && (result.rows).length>0){
			var items = result.rows;
			var html = '';
			for(var i in items){
				var projectstatus = '';
				if(items[i].status == 0){
					projectstatus = '<span class="mui-badge">未开始</span>';
				}else if(items[i].status == 1){
					projectstatus = '<span class="mui-badge mui-badge-success">运行中</span>';
				}else if(items[i].status == 2){
					projectstatus = '<span class="mui-badge mui-badge-warning">已暂停</span>';
				}else if(items[i].status == 3){
					projectstatus = '<span class="mui-badge mui-badge-primary">已结束</span>';
				}
				var createUserName=(items[i].createUserName==null||items[i].createUserName=='null'||items[i].createUserName=='') ? items[i].createUserId : items[i].createUserName;
			//	var createTime = formatDate(items[i].createTime,'MM-dd hh:mm');
				var createTime = fmtDateTime(items[i].createTime);
				html += project_list_item_html.replace("{dataid}", items[i].id).replace("{name}", items[i].name).replace("{status}", projectstatus)
				.replace("{area}", items[i].area).replace("{customer}", items[i].customer).replace("{contractno}", items[i].contractno)
				.replace("{createUserName}", createUserName).replace("{createTime}", createTime)
				.replace("{importanceName}", items[i].importanceName).replace("{typeName}", items[i].typeName)
				.replace("{startTime}", fmtDateTime(items[i].startTime)).replace("{endTime}", fmtDateTime(items[i].endTime))
				.replace("{fzrNames}", items[i].fzrNames);
			}
			if(page == 1)$('#project-all-list').html(html); // 如果是第一页清空数据
			else $('#project-all-list').append(html);
		}
	}, 'json');
}

function fmtDateTime(dd){
	if(dd==null || dd==undefined)return '';
	if(dd.length > 18)dd = dd.substring(6,16);
	return dd;
}

// 查询项目列表 - 根据区域
function getProjectListByArea(page,self){
	var pagesize = 15;
	var params = {};
	params['offset'] = page;
	params['limit'] = pagesize;
	var area = $('#tab_type_area .mui-segmented-control .mui-active').attr('area');
	params['area'] = area;
	params['id']  = projectId;
	
	if(page == 1)$('#project-area-list').html('');
	$.post(ctxPath+'mobile/api/project/getList', params, function(result){
		if(result.total == 0 || result.total<=(page*pagesize) || page>20){ // 超过10页不加载了(加载数据太多页面容易崩)
			if(self)self.endPullUpToRefresh(true);	// 当为true时，底部出现没有更多数据，并且不能滑动
		}else{
			if(self)self.endPullUpToRefresh();	// 当为false或空时，底部出现正在加载，滑动到下一页
		}
		if(result.total > 0 && (result.rows).length>0){
			var items = result.rows;
			var html = '';
			for(var i in items){
				var projectstatus = '';
				if(items[i].status == 0){
					projectstatus = '<span class="mui-badge">未开始</span>';
				}else if(items[i].status == 1){
					projectstatus = '<span class="mui-badge mui-badge-success">运行中</span>';
				}else if(items[i].status == 2){
					projectstatus = '<span class="mui-badge mui-badge-warning">已暂停</span>';
				}else if(items[i].status == 3){
					projectstatus = '<span class="mui-badge mui-badge-primary">已结束</span>';
				}
				var createUserName=(items[i].createUserName==null||items[i].createUserName=='null'||items[i].createUserName=='') ? items[i].createUserId : items[i].createUserName;
				html += project_list_item_html.replace("{dataid}", items[i].id).replace("{name}", items[i].name).replace("{status}", projectstatus)
				.replace("{area}", items[i].area).replace("{customer}", items[i].customer).replace("{contractno}", items[i].contractno)
				.replace("{createUserName}", createUserName).replace("{createTime}", fmtDateTime(items[i].createTime))
				.replace("{importanceName}", items[i].importanceName).replace("{typeName}", items[i].typeName)
				.replace("{startTime}", fmtDateTime(items[i].startTime)).replace("{endTime}", fmtDateTime(items[i].endTime))
				.replace("{fzrNames}", items[i].fzrNames);
			}
			if(page == 1)$('#project-area-list').html(html); // 如果是第一页清空数据
			else $('#project-area-list').append(html);  
		}
	}, 'json');
}

// 查询项目列表 - 根据用户/部门
function getProjectListByUser(page,self){
	var pagesize = 15;
	var params = {};
	params['offset'] = page;
	params['limit'] = pagesize;
	params['deptId'] = $('#s_departmentid').val();
	params['createUserName'] = $('#s_userid').val();
	params['id']  = projectId;
	
	if(page == 1)$('#project-user-list').html('');
	$.post(ctxPath+'mobile/api/project/getList', params, function(result){
		if(result.total == 0 || result.total<=(page*pagesize) || page>20){ // 超过10页不加载了(加载数据太多页面容易崩)
			if(self)self.endPullUpToRefresh(true);	// 当为true时，底部出现没有更多数据，并且不能滑动
		}else{
			if(self)self.endPullUpToRefresh();	// 当为false或空时，底部出现正在加载，滑动到下一页
		}
		if(result.total > 0 && (result.rows).length>0){
			var items = result.rows;
			var html = '';
			for(var i in items){
				var projectstatus = '';
				if(items[i].status == 0){
					projectstatus = '<span class="mui-badge">未开始</span>';
				}else if(items[i].status == 1){
					projectstatus = '<span class="mui-badge mui-badge-success">运行中</span>';
				}else if(items[i].status == 2){
					projectstatus = '<span class="mui-badge mui-badge-warning">已暂停</span>';
				}else if(items[i].status == 3){
					projectstatus = '<span class="mui-badge mui-badge-primary">已结束</span>';
				}
				var createUserName=(items[i].createUserName==null||items[i].createUserName=='null'||items[i].createUserName=='') ? items[i].createUserId : items[i].createUserName;
				html += project_list_item_html.replace("{dataid}", items[i].id).replace("{name}", items[i].name).replace("{status}", projectstatus)
				.replace("{area}", items[i].area).replace("{customer}", items[i].customer).replace("{contractno}", items[i].contractno)
				.replace("{createUserName}", createUserName).replace("{createTime}", fmtDateTime(items[i].createTime))
				.replace("{importanceName}", items[i].importanceName).replace("{typeName}", items[i].typeName)
				.replace("{startTime}", fmtDateTime(items[i].startTime)).replace("{endTime}", fmtDateTime(items[i].endTime))
				.replace("{fzrNames}", items[i].fzrNames);
			}
			if(page == 1)$('#project-user-list').html(html); // 如果是第一页清空数据
			else $('#project-user-list').append(html);  
		}
	}, 'json');
}

// 查询项目列表 - 根据时间范围查询
function getProjectListByTime(page,self){
	var pagesize = 15;
	var params = {};
	params['offset'] = page;
	params['limit'] = pagesize;
	params['id']  = projectId;
	var starttime=$('#s_starttime').val(), endtime=$('#s_endtime').val();
	if(starttime!=null && $.trim(starttime)!='')starttime=starttime+' 00:00:00';
	if(endtime!=null && $.trim(endtime)!='')endtime=endtime+' 23:59:59';
	if(starttime!=null && $.trim(starttime)!='')params['starttime'] = starttime;
	if(endtime!=null && $.trim(endtime)!='')params['endtime'] = endtime;
	
	if(page == 1)$('#project-time-list').html('');
	$.post(ctxPath+'mobile/api/project/getList', params, function(result){
		if(result.total == 0 || result.total<=(page*pagesize) || page>20){ // 超过10页不加载了(加载数据太多页面容易崩)
			if(self)self.endPullUpToRefresh(true);	// 当为true时，底部出现没有更多数据，并且不能滑动
		}else{
			if(self)self.endPullUpToRefresh();	// 当为false或空时，底部出现正在加载，滑动到下一页
		}
		if(result.total > 0 && (result.rows).length>0){
			var items = result.rows;
			var html = '';
			for(var i in items){
				var projectstatus = '';
				if(items[i].status == 0){
					projectstatus = '<span class="mui-badge">未开始</span>';
				}else if(items[i].status == 1){
					projectstatus = '<span class="mui-badge mui-badge-success">运行中</span>';
				}else if(items[i].status == 2){
					projectstatus = '<span class="mui-badge mui-badge-warning">已暂停</span>';
				}else if(items[i].status == 3){
					projectstatus = '<span class="mui-badge mui-badge-primary">已结束</span>';
				}
				var createUserName=(items[i].createUserName==null||items[i].createUserName=='null'||items[i].createUserName=='') ? items[i].createUserId : items[i].createUserName;
				html += project_list_item_html.replace("{dataid}", items[i].id).replace("{name}", items[i].name).replace("{status}", projectstatus)
				.replace("{area}", items[i].area).replace("{customer}", items[i].customer).replace("{contractno}", items[i].contractno)
				.replace("{createUserName}", createUserName).replace("{createTime}", fmtDateTime(items[i].createTime))
				.replace("{importanceName}", items[i].importanceName).replace("{typeName}", items[i].typeName)
				.replace("{startTime}", fmtDateTime(items[i].startTime)).replace("{endTime}", fmtDateTime(items[i].endTime))
				.replace("{fzrNames}", items[i].fzrNames);
			}
			if(page == 1)$('#project-time-list').html(html); // 如果是第一页清空数据
			else $('#project-time-list').append(html);  
		}
	}, 'json');
}


(function ($) {
    $('.mui-scroll-wrapper').scroll({
        bounce: false,		// 是否启用回弹
        indicators: true, 	// 是否显示滚动条
        deceleration: mui.os.ios ? 0.003 : 0.0009 // 阻尼系数
    });
    
    mui('.mui-slider').slider().stopped = true; // 禁止底部选项卡左右滑动
    
    //因为是四个不同的区块，每一个页数不一样，所以要存不同的页数
    
    $.ready(function () {
        //循环初始化所有下拉刷新，上拉加载。
        $.each(document.querySelectorAll('.mui-slider-group .mui-scroll'), function (index, pullRefreshEl) {
            $(pullRefreshEl).pullToRefresh({
                up: {
                    auto: true, //自动执行一次上拉加载，可选；
                    show: false, //显示底部上拉加载提示信息，可选；      
                    contentrefresh: '正在加载...', //上拉进行中提示信息
                    contentnomore: '没有更多数据了', //上拉无更多信息时提示信息
                    callback:function () {
                  		var self = this;
                        setTimeout(function () {
                        	//获取四个不同的区块显示的位置
                            if(index == 0){//全部选项卡的index是0，当显示它的时候，滑动页面加1，调数据，以下以此类推
                                pageNum++;
                                getProjectList(pageNum, self);
                                tab1_self = self;
                            }else if(index == 1){
                           		pageNumArea++;
                           		getProjectListByArea(pageNumArea,self);
                           		tab2_self = self;
                            }else if(index == 2){
                             	pageNumUser++;
                             	getProjectListByUser(pageNumUser,self)
                             	tab3_self = self;
                            }else if(index == 3){
                            	pageNumTime++;
                            	getProjectListByTime(pageNumTime,self);
                            	tab4_self = self;
                            }
                        }, 1000);
                    }
                }
              	/* 
                ,down: {
                	// 从上往下拉刷新先不做，多个tab不兼容
					callback: function() {
						var self = this;
						setTimeout(function() {
							if(index == 0){//全部选项卡的index是0，当显示它的时候，滑动页面加1，调数据，以下以此类推
                        		pageNum = 1;
                          		getProjectList(pageNum, self);
                        		self.endPullDownToRefresh();
                            }else if(index == 1){
                          		console.log('mui-scroll down index='+index);
                            	pageNumArea = 1;
                          		getProjectListByArea(pageNumArea,self);
                            }
							
						}, 1000);
					}
				}
				*/
                
            });
        });

    });
})(mui);


$(function(){
	getJsConfig(); // 微信JS授权接口
	
	$('#searchInput')
	    .on('blur', function () {
		//	console.log('鼠标离开了...');
	        if(!this.value.length){
	        	
	        }
	    })
	    .on('input', function(){
	    //	console.log('input,value='+this.value);
	    	pageNum = 1;
			getProjectList(pageNum, null);
	    })
	;
	
	$('.mui-content').on('touchmove', '#slider', function(e) {
		// 不加这个，下拉加载滚动在ios不流畅
		e.preventDefault();
	});
	
	// 搜索栏点击x图标
	mui('#div-global-search').on('tap', '.mui-icon-clear', function(e) {
		pageNum = 1;
		getProjectList(pageNum, null);
	});
	
	// 弹出项目详情模态框(这能不能用jquery的click事件绑定，否则弹出层会事件穿透，在弹层上点击会响应遮挡层的事件)
//	$('#project-all-list').on('click','.p-title',function(){
	mui("#project-all-list, #project-area-list, #project-user-list, #project-time-list").on('tap','.p-title',function(){
		$('#modal_project_moreinfo').addClass('mui-active');
		var pid = this.getAttribute("dataid");
		getProjectDetail(pid);
	});
	 
	// 关闭项目详情模态框
	$('#btn_colse_modal').click(function(){ // 关闭模态框，其实不需要这个也会关闭，加这个可做些事件处理
		$('#modal_project_moreinfo').removeClass('mui-active');
		$('#project-content').html('');
		$('#btngroups').attr("dataid", '');
	});
	
	// 点击项目文档按钮
	$('#btn_projectfiles').click(function(){
		var dataid = $(this).parent().attr('dataid');
		if(dataid == null || $.trim(dataid)=='')return;
		window.location.href = ctxPath+'mobile/page/project/file/list?pid='+dataid;
	});
	
	// 点击任务进度按钮
	$('#btn_projecttasks').click(function(){
		var dataid = $(this).parent().attr('dataid');
		if(dataid == null || $.trim(dataid)=='')return;
		window.location.href = ctxPath+'mobile/page/project/task/list?pid='+dataid;
	});
	
	// 底部tab选项卡点击事件
		mui('#nav-bar-tab').on('tap', '.mui-tab-item', function(e) {
		var id = $(this).attr('id');
		if(id == 'tab1'){
			pageNum=1;
			getProjectList(pageNum, tab1_self);
		}else if(id == 'tab2'){
			pageNumArea=1;
			getProjectListByArea(pageNumArea,tab2_self);
		}else if(id == 'tab3'){
			pageNumUser=1;
			getProjectListByUser(pageNumUser,tab3_self)
		}else if(id == 'tab4'){
			pageNumTime=1;
			getProjectListByTime(pageNumTime,tab4_self);
		}else if(id == 'tab5'){
			
		}
	});
	
	// 按区域查找点击区域切换
	mui("#tab_type_area .mui-segmented-control").on('tap','.mui-control-item',function(){
		$('#tab_type_area .mui-segmented-control .mui-control-item').each(function(){
			$(this).removeClass('mui-active');
		});
		$(this).addClass('mui-active');
		pageNumArea = 1;
		getProjectListByArea(pageNumArea, null);
	});
	
	
	// 从企业通讯录选择部门或者联系人
	$('.selectqycontact').click(function(){
		var btnid = $(this).attr('id');
		var type = (btnid == 'btn_selectqydept') ? 'department' : 'user';
		selectEnterpriseContact(type);
	});
	
	// 清空已选择的部门或联系人
	$('.btn-clear').click(function(){
		var btnid = $(this).attr('id');
		if(btnid == 'btn_clearqydept'){
			$('#s_departmentid').val('');
			$('#s_departmentname').val('');
		}else if(btnid == 'btn_clearqyuser'){
			$('#s_userid').val('');
			$('#s_username').val('');
		}
	});
	
	// 按用户/部门查找搜索按钮
	$('#btn_tab_user_search').click(function(){
		pageNumUser=1;
		getProjectListByUser(pageNumUser,null);
	});
	
	// 按时间查找搜索按钮
	$('#btn_tab_time_search').click(function(){
		pageNumTime=1;
		getProjectListByTime(pageNumTime,null);
	});
	
	
	// 初始化时间控件
	var startDate=new Date();
//	startDate.setDate(startDate.getDate()-7);//设置天数 -7天
	startDate.setMonth(startDate.getMonth(),1); // 设置为当月1号为开始日期
	$('#s_starttime').val(formatDate(startDate.getTime(),'yyyy-MM-dd'));
	$('#s_endtime').val(formatDate((new Date()).getTime(),'yyyy-MM-dd'));
	mui("#tab_type_time").on('tap','#s_starttime',function(){
		var picker = new mui.DtPicker({
			"type":"date",
			beginDate: new Date(2018, 06, 01), //设置开始日期
			endDate: new Date()	// 设置结束日期
		});
		picker.show(function(rs) {
			$('#s_starttime').val(rs.value);
		});
	});
	mui("#tab_type_time").on('tap','#s_endtime',function(){
		var picker = new mui.DtPicker({
			"type":"date",
			beginDate: new Date(2018, 06, 01), //设置开始日期
			endDate: new Date()	// 设置结束日期
		});
		picker.show(function(rs) {
			$('#s_endtime').val(rs.value);
		});
	});
	
}); // end with $(function()


