var pers = []
var table, form, laydate
var yjIds,insMonths


// 静态数据
var tableData = [];
/**
 * 初始化数据
 */
function init() {
	// 渲染表格
	table.render({
		elem: '#table',
		// url: "/sys/achievement",
		// page: true,
		skin: 'line', // 表格样式
		cols: [
			[{
					title: '序号',
					field: 'zizeng',
					align: 'center',
					type: 'numbers',
					width: '5%'
				},
				{
					field: 'proName',
					title: '线路名称',
					align: 'center',
					width: '15%'
				},
				{
					field: '',
					title: '工作内容',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var workContent = d.workContent
						var yjId = d.yjId;
						var proName = d.proName;
						var insMonth = d.insMonth;
						var html =
							`<input class="workContent layui-input" maxlength="500" value="${workContent}" key="${id}" yjId="${yjId}" proName="${proName}" insMonth="${insMonth}"  type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				},
				{
					field: '',
					title: '计划开始时间',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var stateTime = d.stateTime
						var html =
							`<input class="planStartTime layui-input" value="${stateTime}" key="${id}" readonly type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				},
				{
					field: '',
					title: '计划结束时间',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var enTime = d.enTime
						var html =
							`<input class="planEndTime layui-input" value="${enTime}" key="${id}" readonly type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				},
				{
					field: '',
					title: '责任人（护线员）',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var dutyUser = d.dutyUser
						var html =
							`<input class="liablePerson layui-input" value="${dutyUser}" key="${id}" type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				},
				{
					field: '',
					title: '督办人（设备主人）',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var supervisor = d.supervisor
						var html =
							`<input class="proctorPerson layui-input" value="${supervisor}" key="${id}" type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				},
				{
					field: '',
					title: '完成标准',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var complete = d.complete
						var html =
							`<input class="standard layui-input" value="${complete}" key="${id}" type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				},
				{
					field: '',
					title: '备注',
					align: 'center',
					templet: function(d) {
						var id = d.id
						var remarks = d.remarks
						var html =
							`<input class="remark layui-input" value="${remarks}" key="${id}" type="text" style="width: 150px;height: 25px;"/>`;
						return html;
					},
				}
			]
		],
		data: tableData,
		done: function(res, curr, count, origin) {

			// 初始化开始时间和结束时间的变量
			var startDate = null;
			var endDate = null;
			laydate.render({
				elem: '.planStartTime',
				done: function(value, date, time) {
					// 将laydate的日期对象转换为原生Date对象
					startDate = new Date(date.year, date.month - 1, date.date, date.hours, date
						.minutes, date.seconds);

					// 确保结束时间不早于开始时间
					if (startDate && endDate) {
						if (endDate.getTime() < startDate.getTime()) {
							// 清空结束时间
							// 清除DOM元素的值
							$(this.elem).val('');
							// 重置endDate变量
							endDate = null;
							layer.msg('结束时间不能早于开始时间！');
						}
					}
				}
			});
			laydate.render({
				elem: '.planEndTime',
				done: function(value, date, time) {
					// 将laydate的日期对象转换为原生Date对象
					endDate = new Date(date.year, date.month - 1, date.date, date.hours, date
						.minutes, date.seconds);

					// 确保结束时间不早于开始时间
					if (startDate && endDate) {
						if (endDate.getTime() < startDate.getTime()) {
							// 清空结束时间
							// 清除DOM元素的值
							$(this.elem).val('');
							// 重置endDate变量
							endDate = null;
							layer.msg('结束时间不能早于开始时间！');
						}
					}
				}
			});
		},
	});

}
//提交月计划
function saveMonthPlan() {
	//获取工作内容 DOM
	var workContents = $(".workContent");
	//获取计划开始时间 DOM
	var planStartTimes = $(".planStartTime");
	//获取计划结束时间 DOM
	var planEndTimes = $(".planEndTime");
	//获取责任人（护线员） DOM
	var liablePersons = $(".liablePerson");
	//获取督办人（设备主人） DOM
	var proctorPersons = $(".proctorPerson");
	//获取完成标准 DOM
	var standards = $(".standard");
	//获取备注 DOM
	var remarks = $(".remark");

	var arr = [];
	//循环获取的 DOM，将数据整合
	for (var i = 0; i < workContents.length; i++) {
		//获取此行数据 的id
		var id = $(workContents[i]).attr("key");
		var yjId = $(workContents[i]).attr("yjId");
		var proName = $(workContents[i]).attr("proName");
		var insMonth = $(workContents[i]).attr("insMonth");
		
		//获取工作内容 
		var workContent = $(workContents[i]).val();
		//获取计划开始时间 
		var planStartTime = $(planStartTimes[i]).val();
		//获取计划结束时间 
		var planEndTime = $(planEndTimes[i]).val();
		//获取责任人（护线员） 
		var liablePerson = $(liablePersons[i]).val();
		//获取督办人（设备主人） 
		var proctorPerson = $(proctorPersons[i]).val();
		//获取完成标准 
		var standard = $(standards[i]).val();
		//获取备注
		var remark = $(remarks[i]).val();

		if (workContent == "") {
			layer.msg("请填写工作内容", {
				icon: 0
			});
			$(workContents[i]).focus();
			return;
		}
		if (planStartTime == "") {
			layer.msg("请填写计划开始时间", {
				icon: 0
			});
			$(planStartTimes[i]).focus();
			return;
		}
		if (planEndTime == "") {
			layer.msg("请填写计划结束时间", {
				icon: 0
			});
			$(planEndTimes[i]).focus();
			return;
		}
		if (liablePerson == "") {
			layer.msg("请填写责任人（护线员）", {
				icon: 0
			});
			$(liablePersons[i]).focus();
			return;
		}
		if (proctorPerson == "") {
			layer.msg("请填写督办人（设备主人）", {
				icon: 0
			});
			$(proctorPersons[i]).focus();
			return;
		}
		if (standard == "") {
			layer.msg("请填写完成标准", {
				icon: 0
			});
			$(standards[i]).focus();
			return;
		}
		if (remark == "") {
			layer.msg("请填写备注", {
				icon: 0
			});
			$(remarks[i]).focus();
			return;
		}

		var json = {
			"id": id,
			"yjId": yjId,
			"workContent": workContent,
			"stateTime": planStartTime,
			"enTime": planEndTime,
			"dutyUser": liablePerson,
			"supervisor": proctorPerson,
			"complete": standard,
			"remarks": remark
		}
		arr.push(json);
		console.log(arr)

	}
	
	// 加载提示
	let loadingMsg = layer.msg('数据上传中,请稍候...', {
		icon: 16,
		scrollbar: false,
		time: 0,
		shade: [0.8, '#393D49']
	});
	
	// form请求地址
	let formUrl = PATH_URL + "/inspectionPlan/updateInspectionPlan";
	$.ajax({
		type: 'POST',
		url: formUrl, // 请求地址
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(arr),
		success: function(data) {
			layer.close(loadingMsg); // 关闭提示层
			if (data.code == 200) {
				parent.layer.msg("修改成功", {
					icon: 1
				});
				var index = parent.layer.getFrameIndex(window.name); //先得到当前 iframe层的索引
				parent.layer.close(index); //再执行关闭
			} else {
				layer.alert(data.msg);
			}
		},
		error: function(XMLHttpRequest, textStatus, e) {
			layer.close(loadingMsg);
			layer.msg('数据请求发生异常,请稍后重试', {
				icon: 16,
				scrollbar: false
			});
		}
	});
}


//撤销月计划
function revokeMonthPlan() {
	let height = '63%';
	let width = '43%';
	var index = layer.open({
		title: ['计划撤销', 'color:#3B70A1;background-color:#E8ECEB;font-size:20px'],
		type: 2,
		content: './revokeMonthPlan.html',
		area: [width, height],
		maxmin: false,
		success: function(layero, index) {
			var myIframe = window[layero.find('iframe')[0]['name']];
			var fnc = myIframe.setData(yjIds,insMonths); //aaa()为子页面的方法
		},
		
	});
}

function setData(data, yjId, insMonth) {
	layui.use(['form', 'layer', 'table', 'laydate'], function() {
		table = layui.table;
		form = layui.form;
		laydate = layui.laydate


		yjIds = yjId;
		insMonths = insMonth;
		if (data.length > 0) {
			$('#fgsName').html(data[0].fgsName);
			$('#yjName').html(data[0].yjName);
			$('#insMonth').html(data[0].insMonth);

			setAiDitStatus(data[0].aiDitStatus);

			$('#createUser').html(data[0].createUser);
			$('#createTime').html(data[0].createTime);

			//分公司
			if (data[0].aiDitStatuses) {
				$('#aiDitStatuses').html(data[0].aiDitStatuses);
				$('#auditUserName').html(data[0].auditUserName);
				$('#auditTime').html(data[0].auditTime);
			} else {
				$('#aiDitStatuses').html("");
				$('#auditUserName').html("");
				$('#auditTime').html("");
			}

			//总公司
			if (data[0].aiDitStatusTotal) {
				$('#aiDitStatusTotal').html(data[0].aiDitStatusTotal);
				$('#auditUserNameTotal').html(data[0].auditUserNameTotal);
				$('#auditTimeTotal').html(data[0].auditTimeTotal);
			} else {
				$('#aiDitStatusTotal').html("");
				$('#auditUserNameTotal').html("");
				$('#auditTimeTotal').html("");
			}

			for (var i = 0; i < data.length; i++) {
				tableData.push({
					id: data[i].id,
					proName: data[i].proName,
					yjId: data[i].yjId,
					insMonth: data[i].insMonth,

					workContent: data[i].workContent,
					stateTime: data[i].stateTime,
					enTime: data[i].enTime,
					dutyUser: data[i].dutyUser,
					supervisor: data[i].supervisor,
					complete: data[i].complete,
					remarks: data[i].remarks,

				})
			}
			init();
		} else {
			layer.alert("无数据，请联系管理员", {
				icon: 2
			});
		}
		init();
	});
}


function setAiDitStatus(status) {
	$("#subComName").empty();
	var text;
	var color;
	var html = "";
	if (status == '2') {
		text = '已通过';
		color = '#19BE6B';
	}
	if (status == '0') {
		text = '待审核';
		color = '#FF9900';
	}
	if (status == '3') {
		text = '未通过';
		color = '#F56C6C';
	}
	if (status == '1') {
		text = '已撤销';
		color = '#999999';
	}
	html += "<span style='display: flex;align-items: center'>"
	html += `<span style='width: 5px;height: 5px;background: ${color};border-radius: 50%'></span>&nbsp;&nbsp;`
	html += `<span>${text}</span>`
	html += "</span>"

	$("#subComName").append(html);
}