var currentDate = new Date();
// 获取当前月份的第一天
var firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
// 获取下一个月的第一天
var nextMonthFirstDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
// 获取当前月份的天数 //本月多少天
var daysInMonth = Math.floor((nextMonthFirstDay.getTime() - firstDay.getTime()) / (24 * 60 * 60 * 1000));
// console.log(daysInMonth);
var pers = []
var table,form,laydate,element;
var tabIndex = 0;
var tableType = 'layui_table1';
var times = getCurrentDateTimeArr();
layui.use(['form','layer','table','laydate','element'], function () {
    table = layui.table;
    form = layui.form;
    laydate = layui.laydate;
    element = layui.element;

    // 渲染时间选择器
    laydate.render({
        elem: '#makeMonth',
        type: 'month',
        format: 'yyyy-MM',
        fullPanel: true,
		value: times[0] + "-" + times[1]
    });

    //监听Tab切换，以改变地址hash值
    element.on('tab(chosenTab)', function(data){
        // console.log(data)
        tabIndex = data.index;
        //切换重置
        $('#userName').val('');
        $('#proName').val('');
        $('#yjName').val('');
        $('#makeMonth').val(times[0] + "-" + times[1]);
        if(tabIndex==0){
			tableType = 'layui_table1';
            initTable1();
        }else if(tabIndex==1){
			tableType = 'layui_table2';
            initTable2();
        }else if(tabIndex==2){
			tableType = 'layui_table3';
            initTable3("", "", "", times[0] + "-" + times[1]);
        }else{
			tableType = 'layui_table1';
            initTable1();
        }
    });

    table.on(`tool(${tableType})`, function (obj) {
        switch (obj.event) {
            case 'detail': 
                console.log('详情',obj) 
                checkView(obj)

            break;
        }
    });
 
    initTable1();
    
});


//查询
function queryClick(){
	var yjId = $(window.parent.document).find("input[id='taskSourceId']").attr("stationId"); 
	let userName = $('#userName').val();
	let proName = $('#proName').val();
	let yjName = $('#yjName').val();
	let startMakeMonth = $('#makeMonth').val();
	let endMakeMonth = $('#makeMonth').val();
	if(tabIndex == 2){
		initTable3(userName,proName,yjName,$('#makeMonth').val())
	}else{
		table.reload(tableType, {
			where: {
				userName: userName,
				proName: proName,
				yjName: yjName,
				startMakeMonth: startMakeMonth,
				endMakeMonth: endMakeMonth,
				yjId: yjId
			}
		})
	}
}
//重置
function resetClick(){
	var yjId = $(window.parent.document).find("input[id='taskSourceId']").attr("stationId"); 
	$('#userName').val("");
	$('#proName').val("");
	$('#yjName').val("");
	$('#makeMonth').val(times[0] + "-" + times[1]);
	
	if(tabIndex == 2){
		initTable3("","","",$('#makeMonth').val())
	}else{
		table.reload(tableType, {
			where: {
				userName: "",
				proName: "",
				yjName: "",
				startMakeMonth: '',
				endMakeMonth: $('#makeMonth').val(),
				yjId: yjId
			}
		})
	}
}



    
/**
 * 初始化数据 全部
 */
function initTable1(){
	var yjId = $(window.parent.document).find("input[id='taskSourceId']").attr("stationId"); 
	
    console.log('全部')
    table.render({
    	id: 'layui_table1',
		elem: '#table',
		url: PATH_URL + '/attendance/getAllInspectionList',
    	where: {
			startMakeMonth: $('#makeMonth').val(),
			endMakeMonth: $('#makeMonth').val(),
			yjId: yjId
    	},
    	page: true, //开启分页
    	method:'post',
		skin: 'line', // 表格样式
		  cols: [[
			  // {
			  //     type: 'checkbox'
			  // },
			  {
				  title: '序号',
				  field: 'zizeng',
				  align: 'center',
				  type: 'numbers'
			  },
			  {field:'userName', title: '姓名',align: 'center',},
			  {field:'idNumber', title: '身份证号',align: 'center',},
			  {field:'tel', title: '联系电话',align: 'center',},
			  {field:'makeMonth', title: '月份',align: 'center',},
			  
			  {field:'allMake', title: '正常巡视（基*次）',align: 'center',},
			  {field:'special', title: '特巡（天*人）',align: 'center',width:170},
			  {field:'proName', title: '管辖线路名称',align: 'center',width:170},
			  {field:'yjName', title: '所属运检站',align: 'center', },
			  {
				  title: '操作',
				  toolbar: '#opeator-bar',
				  align: 'center',
				  width: 200
			  }
		  ]],
    	done: function(res,curr,count){
    		//checkPermission();
    	}
    });
     
}

/**
 * 初始化数据 正常巡视统计
 */
function initTable2(){
    console.log('正常巡视统计')
	var yjId = $(window.parent.document).find("input[id='taskSourceId']").attr("stationId"); 
    // 渲染表格
    table.render({
    	id: 'layui_table2',
    	elem: '#table',
    	url: PATH_URL + '/attendance/getNormalInspectionList',
    	where: {
			startMakeMonth: $('#makeMonth').val(),
			endMakeMonth: $('#makeMonth').val(),
			yjId: yjId
    	},
    	page: true, //开启分页
    	method:'post',
    	skin: 'line', // 表格样式
    	  cols: [[
    		  // {
    		  //     type: 'checkbox'
    		  // },
    		  {
    			  title: '序号',
    			  field: 'zizeng',
    			  align: 'center',
    			  type: 'numbers'
    		  },
    		  {field:'userName', title: '姓名',align: 'center',},
    		  {field:'proName', title: '管辖线路名称',align: 'center',},
    		  {field:'yjName', title: '所属运检站',align: 'center',},
    		  {field:'oneMakeGtName', title: '巡1次区段（塔）',align: 'center',},
    		  {field:'oneMake', title: '巡1次张数',align: 'center',},
    		  {field:'twoMakeGtName', title: '巡2次区段（塔）',align: 'center'},
    		  {field:'twoMake', title: '巡2次张数',align: 'center'},
    		  {
    			  title: '操作',
    			  toolbar: '#opeator-bar',
    			  align: 'center',
    			  width: 200
    		  }
    	  ]],
    	done: function(res,curr,count){
    		//checkPermission();
    	}
    });
}

/**
 * 初始化数据 特巡统计
 */
function initTable3(userName,proName,yjName,makeMonth){
    console.log('特巡统计')
	var yjId = $(window.parent.document).find("input[id='taskSourceId']").attr("stationId"); 
	//保存数据
	var tableData = []
	
	//保存表头
	var col =
		[[
			{
				title: '序号',
				field: 'zizeng',
				align: 'center',
				type: 'numbers'
			},
			{field:'userId', style: 'display:none'},
			{field:'userName', title: '姓 名',align: 'center', width: '80'},
			{field:'proName', title: '管辖线路名称',align: 'center', width: '200'},
			{field:'yjName', title: '所属运检站',align: 'center', width: '200'},
			{field:'special', title: '总计（天）',align: 'center', width: '100'},
		]]
	
		$.ajax({
			type: 'POST',
			url: PATH_URL + '/attendance/getSpecialInspectionData', // 请求地址
			data: {
				userName: userName,
				proName: proName,
				yjName: yjName,
				makeMonth: $('#makeMonth').val(),
				yjId: yjId
			}, //获取提交的表单字段
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					var json = 
					{'userId': data[i].userId, 'userName': data[i].userName, 'proName': data[i].proName, 'yjName': data[i].yjName, 'special': data[i].special, 'makeMonth': data[i].makeMonth, 'proId': data[i].proId }
					var spMakeList = data[i].spMakeList;
					for (var j = 0; j < spMakeList.length; j++) {
						json[`${ spMakeList[j].currDay }`] = spMakeList[j].isAtt;
					}
					tableData.push(json)
				}
				console.log('tableData', tableData)
				
				if(data.length>0){
					for(var i = 0; i < data[0].spMakeList.length; i++){
						var spMake = data[0].spMakeList[i];
						var json = {field:`${ spMake.currDay }`, title: `${ spMake.currDay }`,align: 'center'}
						col[0].push(json);
					}
				}
				
				col[0].push({
					title: '操作',
					toolbar: '#opeator-bar',
					align: 'center',
					width: 200
				});
				console.log("col：", col);
				
				
				table.render({
					id: 'layui_table3',
					elem: '#table',
					page: true, //开启分页
					skin: 'line', // 表格样式
					cols: col,
					data: tableData
				});
			},
			error: function (XMLHttpRequest, textStatus, e) {
				layer.msg('数据请求发生异常,请稍后重试', {icon: 16, scrollbar: false});
				top.layer.close(addLoadingMsg); //再执行关闭
			}
		});
	
	
	
    
}


/**
 * 详情
 * */
function checkView(obj) {
	debugger
    let height = '98%';
    let width = '95%';
    $.ajax({
		type: 'POST',
		url: PATH_URL + '/attendance/getInspectionParticular',
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify({
			makeMonth: $("#makeMonth").val(),
			proId: obj.data.proId,
			userId: obj.data.userId
		}),
        success: function (data) {
			console.log("dataaaaaa:", data)
            var index = layer.open({
                title: ['详情'],
                type: 2,
                content: 'attendanceDetail.html',
                area: [width, height],
                maxmin: false,
                success: function (layero, index) {
                    // console.log(data);
                    var myIframe = window[layero.find('iframe')[0]['name']]; 
					var times = obj.data.makeMonth.split("-")
                    myIframe.setData(data); //aaa()为子页面的方法
					
					if(tabIndex == 1){
						//正常巡视点击详情，将特别巡视隐藏
						myIframe.normalHideDiv()
					}
					if(tabIndex == 2){
						//特巡点击详情，将正常巡视隐藏
						myIframe.specialHideDiv()
					}
                },
            });
        }
    })
}










//导出
function exportData() {
    // let search1 = $('#search1').val();
    // let search2 = $('#search2').val();
    window.location.href = oiPlanUrl + "/monthlyPlanSubmission/export?token=" + token;
         

}