var yjId = $(window.parent.parent.document).find("input[id='taskSourceId']").attr("stationId");
var pers = []
var table,form,layer,laydate;
var times = getCurrentDateTimeArr();
layui.use(['form','layer','table','laydate'], function () {
    table = layui.table;
    form = layui.form;
	layer = layui.layer;
	laydate = layui.laydate;
	
	// 渲染时间选择器
	// laydate.render({
	//     elem: '#wagesMonth',
	//     type: 'month',
	//     format: 'yyyy-MM',
	//     fullPanel: true,
	// 	value: times[0] + "-" + times[1]
	// });
	
	//取消按钮点击
	$("#closeBt").click(() => {
		var index = parent.layer.getFrameIndex(window.name); //先得到当前 iframe层的索引
		parent.layer.close(index); //再执行关闭
	})
	//保存按钮点击
	$("#submitBt").click(() => {
		updateWages();
	})
	
    init();
});

//查询
function queryClick(){
	table.reload('layui_table', {
	    // //设定异步数据接口的额外参数
	    where: {
			'userName': $("#username").val(),
			'proName': $("#proName").val(),
			'yjId': yjId,
			'wagesMonth': $("#wagesMonth").val()
		}
	})
}
//重置
function resetClick(){
	$("#username").val('');
	$("#proName").val('');
	table.reload('layui_table', {
		where: {
			'userName': '',
			'proName': '',
			'yjId': yjId,
			'wagesMonth': times[0] + "-" + times[1]
		},
	})
}

//页面赋值
function setData(yjId,yjName,gsName,wagesMonth){
	localStorage.setItem("sx","")
	$("#wagesMonth").val(wagesMonth);
	$.ajax({
	    type: 'POST',
	    url: PATH_URL + '/wages/getWagesNum',
	    contentType: "application/json; charset=utf-8",
	    data: JSON.stringify({"yjId":yjId,"wagesMonth":wagesMonth,"userName": '', "proName": ''}),
	    success: function (data) {
			if(data.code == '200'){
				$("#inspectionStation").text(yjName);
				$("#subComName").text(gsName);
				$("#proNum").text(data.data.proNum);
				$("#lineProtector").text(data.data.userNum);
			}
			
	    }
	})
	
}    
/**
 * 初始化数据
 */
function init(){
      // 渲染表格
  table.render({
    id: 'layui_table',
    elem: '#table',
    url: PATH_URL + '/wages/getWagesById',
    where: {
  		'yjId': yjId,
  		'wagesMonth': $('#wagesMonth').val()
    },
  	page: true, //开启分页
  	method:'post',
  	skin: 'line', // 表格样式
    cols: [[
        {
            title: '序号',
            field: 'zizeng',
            align: 'center',
            type: 'numbers'
        },
        {field:'userName', title: '姓 名',align: 'center',},
        {field:'idCard', title: '身份证号',align: 'center',},
        {field:'proName', title: '管辖线路名称',align: 'center',},
        {field:'phone', title: '手机号',align: 'center',},
        {field:'bank', title: '开户行',align: 'center',},
        {field:'bankCard', title: '银行卡号',align: 'center'},
        {field:'unionpayNum', title: '银联号',align: 'center'},
        {field:'xsNum', title: '巡视工作量（基*次）',align: 'center', },
        {field:'xsPrice', title: '约定巡视工价（元/(基*次)）',align: 'center', },
  		{field:'txNum', title: '特巡工作量（人*天）',align: 'center', },
  		{field:'txPrice', title: '约定特巡工价（元/(人*天)）',align: 'center', },
  		{field:'allPrice', title: '合价（元）',align: 'center', },
  		{
  			field: '',
  			title: '通讯费',
  			align: 'center',
  			templet: function(d){
  				var id = d.id;
				var phonePrice = d.phonePrice;
  				var html = `<input value="${ phonePrice }" class="message layui-input" key="${id}" oninput="computemMessage(this)" type="number" min="0" value="0" lay-verify="required" style="width: 54px;height: 25px;"/>`;
  				return html;
  			},
  		},
  		{
  			field: '',
  			title: '奖惩',
  			align: 'center',
  			templet: function(d){
  				var id = d.id
				var reward = d.reward;
  				var html = `<input value="${ reward }" class="bonusPenalty layui-input" key="${id}" oninput="computeBonusPenalty(this)" type="number" value="0" lay-verify="required" style="width: 54px;height: 25px;"/>`;
  				return html;
  			},
  		},
  		{
  			field: '',
  			title: '备注',
  			align: 'center',
  			templet: function(d){
  				var id = d.id
				var remarks = d.remarks;
  				var html = `<input value="${ remarks }" class="remark layui-input" key="${id}" type="text" style="width: 76px;height: 25px;"/>`;
  				return html;
  			},
  		},
  		{
  			field: '',
  			title: '实发金额',
  			align: 'center',
  			templet: function(d){
				var wages = d.wages;
  				var html = `<span class="netSalary" style="color: #D9001B">${ wages }</span>`;
  				return html;
  			},
  		},
    ]],
  	done: function(res,curr,count){
  		//checkPermission();
  	}
  });
}

//通讯费input失去焦点事件
function computemMessage(enent){
	var thisValue = $(enent).val();
	//合价
	var totalPrice = $(enent).parent().parent().prev().children().children().text();
	//奖惩
	var bonusPenalty = $(enent).parent().parent().next().children().children().val();
	
	var value = ""
	//判断是否是数字
	if(isNumber(thisValue) && isNumber(totalPrice) && isNumber(bonusPenalty)){
		value = Number(thisValue) + Number(totalPrice) + Number(bonusPenalty);
	}else{
		value = "0"
	}
	
	$(enent).parent().parent().next().next().next().children().children().text(value);
}
//奖惩 input失去焦点事件
function computeBonusPenalty(enent){
	var thisValue = $(enent).val();
	//合价
	var totalPrice = $(enent).parent().parent().prev().prev().children().children().text();
	//通讯费
	var phonePrice = $(enent).parent().parent().prev().children().children().val();
	var value = ""
	//判断是否是数字
	if(isNumber(thisValue) && isNumber(totalPrice) && isNumber(phonePrice)){
		value = Number(thisValue) + Number(totalPrice) + Number(phonePrice);;
	}else{
		value = "0"
	}
	$(enent).parent().parent().next().next().children().children().text(value);
}


//修改
function updateWages(){
	// 获取表格的所有数据
	var data = table.cache['layui_table'];
	console.log("data:", data)
	
	//获取通讯费 DOM
	var messages = $(".message");
	//获取奖惩 DOM
	var bonusPenaltys = $(".bonusPenalty");
	//获取备注 DOM
	var remarks = $(".remark");
	//获取实发金额 DOM
	var netSalarys = $(".netSalary");
	
	var arr = [];
	
	//循环获取的 DOM，将数据整合
	for (var i = 0; i < messages.length; i++) {
		var id = data[i].id;
		//合价（元）
		var allPrice = data[i].allPrice
		//获取通讯费
		var phonePrice = $(messages[i]).val();
		//获取奖惩
		var reward = $(bonusPenaltys[i]).val();
		//获取备注
		var remark = $(remarks[i]).val();
		//获取实发金额
		var wages = $(netSalarys[i]).text();
		
		
		
		if(phonePrice == ""){
			layer.msg("请填写通讯费", {icon: 0});
			$(messages[i]).focus();
			return;
		}
		if(reward == ""){
			layer.msg("请填写奖惩", {icon: 0});
			$(bonusPenaltys[i]).focus();
			return;
		}
		if(remark == ""){
			layer.msg("请填写备注", {icon: 0});
			$(remarks[i]).focus();
			return;
		}
		
		if(!isInteger(Number(phonePrice))){
			layer.msg("通讯费必须为整数", {icon: 0});
			$(messages[i]).focus();
			return;
		}
		if(!isInteger(Number(reward))){
			layer.msg("奖惩必须为整数", {icon: 0});
			$(bonusPenaltys[i]).focus();
			return;
		}
		
		var json = {
			'id': id,
			'allPrice': allPrice,
			'phonePrice': phonePrice,
			'reward': reward,
			'remarks': remark,
			'wages': wages
		}
		arr.push(json);
		
	}
	console.log('arr:', arr)
	
	//将整合的数据传至后台
	// 加载提示
	let loadingMsg = layer.msg('数据上传中,请稍候...', {icon: 16, scrollbar: false, time: 0, shade: [0.8, '#393D49']});
	// form请求地址
	let formUrl = PATH_URL + "/wages/updateWages";
	

	
	$.ajax({
	    type: 'POST',
	    contentType: "application/json; charset=utf-8",
	    url: formUrl, // 请求地址
	    data: JSON.stringify(arr),
	    success: function (data) {
	        layer.close(loadingMsg); // 关闭提示层
	        if(data.code == 200){
				localStorage.setItem("sx","1")
	            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.msg('数据请求发生异常,请稍后重试', {icon: 16, scrollbar: false});
	    }
	});
}

//判断是否为数字
function isNumber(variable){
	return !isNaN(Number(variable));
}
//判断是不是整数
function isInteger(obj){
	return typeof obj === 'number' && obj % 1 === 0
}
