<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/webpage/include/taglib.jsp"%>
<html>
<head>
	<title>收入登记管理</title>
	<meta name="decorator" content="default"/>
    <%--<script src="${ctxStatic}/layer-v2.3/laydate/laydate.js"></script>--%>
	<script type="text/javascript">
		var validateForm;
		function doSubmit(){//回调函数，在编辑和保存动作时，供openDialog调用提交表单。
		  if(validateForm.form()){
			  $("#inputForm").submit();
			  return true;
		  }
	
		  return false;
		}
		$(document).ready(function() {
			validateForm = $("#inputForm").validate({
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
			
		});

        function formatNum(obj) {
            var val = $(obj).val();
            if(val==null||val==''|| isNaN(val))return;
            var money = parseFloat((val + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
            var l = money.split(".")[0].split("").reverse(),
                r = money.split(".")[1];
            t = "";
            for(i = 0; i < l.length; i ++ )
            {
                t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
            }
            $(obj).val(t.split("").reverse().join("") + "." + r);
        }
	</script>
	<style>
		/*超过5个汉字，调整label的长度，以下是配套的*/
		.layui-item .layui-form-label{
			width:90px;
		}
		.form-group .layui-item .layui-input-block,
		.query .layui-input-block {
			margin-left: 116px;
		}
	</style>
</head>
<body >
<div class="single-form">
	<div class="container">
		<form:form id="inputForm" modelAttribute="workReceiptsRegister" action="${ctx}/workreceiptsregister/workReceiptsRegister/saveDetail" method="post" class="form-horizontal">
		<form:hidden path="id"/>
			<div class="form-group layui-row first">
				<div class="form-group-label"><h2>登记信息</h2></div>
				<div class="layui-item layui-col-sm6">
					<label class="layui-form-label"><span class="require-item">*</span>到账时间：</label>
					<div class="layui-input-block">
						<input id="arrivalDate" name="arrivalDate" type="text" readonly="true" maxlength="20" class="form-control required layui-input"
							   value="<fmt:formatDate value="${workReceiptsRegister.arrivalDate}" pattern="yyyy-MM-dd"/>"  readonly="true"/>
					</div>
				</div>
                <div class="layui-item layui-col-sm6 td1">
                    <label class="layui-form-label"><span class="require-item">*</span>到账金额：</label>
                    <div class="layui-input-block">
                        <input id="arrivalAmt" htmlEscape="false"  readonly="true" value="<fmt:formatNumber value="${workReceiptsRegister.arrivalAmt}" pattern="#,##0.00#"/>" onchange="formatNum(this);" class="form-control required number layui-input"/>
                    </div>
                </div>
				<div class="layui-item layui-col-sm6 td1">
					<label class="layui-form-label"><span class="require-item">*</span>对方户名：</label>
					<div class="layui-input-block">
						<form:input path="clientAccname" htmlEscape="false" readonly="true"  class="form-control required layui-input"/>
					</div>
				</div>
                <div class="layui-item layui-col-sm6">
                    <label class="layui-form-label"><span class="require-item">*</span>对方账号：</label>
                    <div class="layui-input-block">
                        <form:input path="clientAccno" htmlEscape="false" readonly="true" class="form-control required layui-input"/>
                    </div>
                </div>
				<div class="layui-item layui-col-sm6 td1">
					<label class="layui-form-label">登记金额：</label>
					<div class="layui-input-block">
						<input id="registerAmt" name="registerAmt" htmlEscape="false"  readonly="true" value="<fmt:formatNumber pattern="#,##0.00#" value="${workReceiptsRegister.registerAmt}"/>" onchange="formatNum(this);" class="form-control number layui-input" />
					</div>
				</div>
				<div class="layui-item layui-col-sm6 td1">
					<label class="layui-form-label">收入状态：</label>
					<div class="layui-input-block">
						<input path="statuStr" htmlEscape="false" readonly="true" class="form-control layui-input"  <c:if test="${workReceiptsRegister.status eq '0'}">value="未登记"</c:if> <c:if test="${workReceiptsRegister.status eq '1'}">value="已登记"</c:if>/>
						<form:hidden path="status" htmlEscape="false" readonly="true"  class="form-control " />
					</div>
				</div>
				<div class="layui-item layui-col-sm6 td1">
					<label class="layui-form-label">所属分公司：</label>
					<div class="layui-input-block">
						<input type="hidden" value="${workReceiptsRegister.company.id}" name="company.id">
						<form:input path="company.name" htmlEscape="false" readonly="true" class="form-control layui-input"/>
					</div>
				</div>
			</div>
			<div class="form-group layui-row">
				<div class="form-group-label"><h2>发票明细</h2></div>
				<div class="layui-item nav-btns">
					<a class="nav-btn nav-btn-add" onclick="addRow('#registerDetailList', registerDetailIdx, registerDetailTpl,'1');"><i class="fa fa-plus"></i>&nbsp;新增</a>
				</div>
				<div class="layui-item layui-col-xs12 form-table-container" >
					<table id="contentTable" class="table table-bordered table-condensed no-bottom-margin can-edit">
						<thead>
						<tr>
							<th class="hide"></th>
							<th><font style="color: red">*</font>所属部门</th>
							<th><font style="color: red">*</font>发票号</th>
							<th>发票金额</th>
							<th>累计登记金额</th>
							<th>开票时间</th>
							<th><font style="color: red">*</font>登记金额</th>
							<th><font style="color: red">*</font>登记日期</th>
							<th width="90px">登记状态</th>
							<th width="90px">操作</th>
						</tr>
						</thead>
						<tbody id="registerDetailList">
						</tbody>
					</table>
				</div>
			</div>
			<div class="form-group layui-row page-end"></div>
        <script type="text/template" id="registerDetailTpl">//<!--
					<tr id="registerDetailList{{idx}}">
					<td class="hide">
                    <input id="registerDetailList{{idx}}_id" name="registerDetailList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
                    <input id="registerDetailList{{idx}}_delFlag" name="registerDetailList[{{idx}}].delFlag" type="hidden" value="0"/>
                </td>
                <td>
                    <sys:treeselect id="registerDetailList{{idx}}_office" name="registerDetailList[{{idx}}].office.id" value="{{row.office.id}}" labelName="office.name" labelValue="{{row.office.name}}"
					title="部门" url="/sys/office/treeDataBranchOffice?type=2" cssClass="form-control required" notAllowSelectParent="true"/>
                </td>
                <td>
                    <sys:gridselectInvoice url="${ctx}/workreceiptsregister/workReceiptsRegister/selectinvoice" type="" isTotal="1" id="registerDetailList{{idx}}_invoice" name="registerDetailList[{{idx}}].invoice.id"  value="{{row.invoice.id}}"  title="选择发票" labelName="registerDetailList[{{idx}}].invoice.number"
											idx="{{idx}}"	labelValue="{{row.invoice.number}}" cssClass="form-control required" fieldLabels="发票编号" fieldKeys="number" searchLabel="发票编号" searchKey="number" ></sys:gridselectInvoice>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_invoiceAmt" name="registerDetailList[{{idx}}].invoice.totalMoney" type="text" value="{{row.invoice.totalMoney}}" onchange="formatNum(this);" readOnly="true"  class="form-control money"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_incomeAmt" name="registerDetailList[{{idx}}].invoice.incomeMoney" type="text" value="{{row.invoice.incomeMoney}}" onchange="formatNum(this);" readOnly="true"  class="form-control required money"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_invoiceDate" name="registerDetailList[{{idx}}].invoice.date" type="text" value="<fmt:formatDate value="${row.invoice.date}" pattern="yyyy-MM-dd"/>"  readOnly="true"  class="form-control "/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_registerAmt" name="registerDetailList[{{idx}}].registerAmt" type="text" value="{{row.registerAmt}}" onchange="caculateAmt(this,{{idx}})"  class="form-control number required"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_registerDate" name="registerDetailList[{{idx}}].registerDate" type="text" maxlength="20" class="laydate-icon form-control layer-date required layui-input laydate-icondate"
							value="<fmt:formatDate value="${row.registerDate}" pattern="yyyy-MM-dd"/>" readOnly="true" />

                </td>
                <td>
                    <input id="registerDetailList{{idx}}_statusStr" name="registerDetailList[{{idx}}].statusStr" type="text" value="${fns:getDictLabel(row.status, 'register_type', '正常登记')}"  readOnly="true" class="form-control required"/>
                    <input type="hidden" id="registerDetailList{{idx}}_status" name="registerDetailList[{{idx}}].status" type="text" value="{{row.status}}" readOnly="true" class="form-control"/>
                </td>

                <td class="text-center op-td">
                <span class="op-btn op-btn-delete" onclick="delRow(this, '#registerDetailList{{idx}}')" ><i class="fa fa-trash"></i> 取消</span>
                </td>
				</tr>//-->
        </script>
            <script type="text/template" id="registerDetailTpl2">//<!--
					<tr id="registerDetailList{{idx}}">
					<td class="hide">
                    <input id="registerDetailList{{idx}}_id" name="registerDetailList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
                    <input id="registerDetailList{{idx}}_delFlag" name="registerDetailList[{{idx}}].delFlag" type="hidden" value="0"/>
                </td>
                <td>
                    <input type="hidden" id="registerDetailList{{idx}}_officeId" name="registerDetailList[{{idx}}].office.id" type="text" value="{{row.office.id}}"  readOnly="true"  class="form-control "/>
                    <input id="registerDetailList{{idx}}_officeName" name="registerDetailList[{{idx}}].office.name" type="text" value="{{row.office.name}}"  readOnly="true"  class="form-control "/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_invoiceId" name="registerDetailList[{{idx}}].invoice.id"  type="hidden" value="{{row.invoice.id}}"/>
                    <input id="registerDetailList{{idx}}_invoiceName" name="registerDetailList[{{idx}}].invoice.number" type="text" value="{{row.invoice.number}}"  readOnly="true"  class="form-control "/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_invoiceAmt" name="registerDetailList[{{idx}}].invoice.totalMoney" type="text" value="{{row.invoice.totalMoney}}"  onchange="formatNum(this);" readOnly="true"  class="form-control money"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_incomeAmt" name="registerDetailList[{{idx}}].invoice.incomeMoney" type="text" value="{{row.invoice.incomeMoney}}" onchange="formatNum(this);" readOnly="true"  class="form-control required money"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_invoiceDate" name="registerDetailList[{{idx}}].invoice.date" type="text" value="{{row.invoice.date}}"  readOnly="true"  class="form-control "/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_registerAmt" name="registerDetailList[{{idx}}].registerAmt" type="text" readOnly="true" value="{{row.registerAmt}}" onchange="formatNum(this);"  class="form-control required money"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_registerDate" name="registerDetailList[{{idx}}].registerDate" type="text" class="form-control required"
							value="{{row.registerDate}}" readOnly="true"/>
                </td>
                <td>
                    <input id="registerDetailList{{idx}}_statusStr" name="registerDetailList[{{idx}}].statusStr" type="text" value="{{row.statusStr}}"  readOnly="true" class="form-control required"/>
                    <input type="hidden" id="registerDetailList{{idx}}_status" name="registerDetailList[{{idx}}].status" type="text" value="{{row.status}}" readOnly="true" class="form-control"/>
                </td>

                <td class="text-center op-td">
                <span id="registerDetailList{{idx}}_button" class="op-btn op-btn-delete" onclick="delRow(this, '#registerDetailList{{idx}}','{{idx}}')" ><i class="fa fa-trash"></i> 取消</span>
                </td>
				</tr>//-->
            </script>
        <script type="text/javascript">
            var registerDetailIdx = 0, registerDetailTpl = $("#registerDetailTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
            var registerDetailTpl2 = $("#registerDetailTpl2").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
            var data;
            $(document).ready(function() {
                data = ${fns:toJson(workReceiptsRegister.registerDetailList)};
                    for (var i=0; i<data.length; i++){
                        addRow('#registerDetailList', registerDetailIdx, registerDetailTpl2,'2',data[i]);
                        if(data[i].status != '1'){
                            $("#registerDetailList"+i+"_button").hide();
                            $("#registerDetailList"+i+"_invoiceAmt").val(parseFloat($("#registerDetailList"+i+"_invoiceAmt").val()).toFixed(2));
                            $("#registerDetailList"+i+"_incomeAmt").val(parseFloat($("#registerDetailList"+i+"_incomeAmt").val()).toFixed(2));
                            $("#registerDetailList"+i+"_registerAmt").val(parseFloat($("#registerDetailList"+i+"_registerAmt").val()).toFixed(2));
                            $("#registerDetailList"+i+"_invoiceDate").val(new Date(data[i].invoice.date).format("yyyy-MM-dd"));
                        }
                        $("#registerDetailList"+i+"_invoiceDate").val(new Date(data[i].invoice.date).format("yyyy-MM-dd"));
                        $(":input.money").change();
                    }
            });

            Date.prototype.format = function(fmt) {
                var o = {
                    "M+" : this.getMonth()+1,                 //月份
                    "d+" : this.getDate(),                    //日
                    "h+" : this.getHours(),                   //小时
                    "m+" : this.getMinutes(),                 //分
                    "s+" : this.getSeconds(),                 //秒
                    "q+" : Math.floor((this.getMonth()+3)/3), //季度
                    "S"  : this.getMilliseconds()             //毫秒
                };
                if(/(y+)/.test(fmt)) {
                    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
                }
                for(var k in o) {
                    if(new RegExp("("+ k +")").test(fmt)){
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                    }
                }
                return fmt;
            }

            function addRow(list, idx, tpl,isNew, row){
                bornTemplete(list, idx, tpl, row, idx);
                registerDetailIdx +=1;
                if(isNew=="1") {
                    var dateId = "#registerDetailList"+idx+"_registerDate";
                    var stausId = "#registerDetailList"+idx+"_status";
                    laydate.render({
                        elem: dateId, //目标元素。由于laydate.js封装了一个轻量级的选择器引擎，因此elem还允许你传入class、tag但必须按照这种方式 '#id .class'
                        event: 'click', //响应事件。如果没有传入event，则按照默认的click
                        value:new Date(),
                        done:function(value,date){
                            validateTime(value,dateId);
                        }
                    });
                    $(stausId).val(1);
                }
            }

            function bornTemplete(list, idx, tpl, row, idx1){
                var idx1 = $("#registerDetailList tr").length +1;
                $(list).append(Mustache.render(tpl, {
                    idx: idx, delBtn: true, row: row,
                    order:idx1 + 1, idx1:idx1
                }));
                $(list+idx).find("select").each(function(){
                    $(this).val($(this).attr("data-value"));
                });
                $(list+idx).find("input[type='checkbox'], input[type='radio']").each(function(){
                    var ss = $(this).attr("data-value").split(',');
                    for (var i=0; i<ss.length; i++){
                        if($(this).val() == ss[i]){
                            $(this).attr("checked","checked");
                        }
                    }
                });
            }
            function delRow(obj, prefix,idx){
                //请求服务器判断是否已经付款
                var invoiceId = $(prefix+"_invoiceId").val();
                var id = $(prefix+"_id");
                var delFlag = $(prefix+"_delFlag");
                var status = $(prefix+"_status");
                if (id.val() == ""){
                    $(obj).parent().parent().remove();
                    totalRgAmt(obj);
                }else {
                    $.ajax({
                        url:"${ctx}/workreceiptsregister/workReceiptsRegister/checkpaystatus",
                        data:{"invoiceId":invoiceId},
                        type:"post",
                        success:function(result){
                            if(result.success ){
                                if(result.body.payFlag){
                                    top.layer.msg("发票已经结算付款，不能取消登记");
                                }else {
                                    delFlag.val("1");
                                    var today = new Date();
                                    var rgDate = strToDate($(prefix+"_registerDate").val());
                                    if(today.getFullYear() > rgDate.getFullYear()||(today.getFullYear() == rgDate.getFullYear() && today.getMonth()>rgDate.getMonth())){
                                        addRow('#registerDetailList', registerDetailIdx, registerDetailTpl2,'2',data[idx]);
                                        $(":input.money").change();
                                        $("#registerDetailList"+idx+"_statusStr").val("取消登记");
                                        status.val("2");
                                        $("#registerDetailList"+idx+"_button").hide();
                                        var newIdx = registerDetailIdx-1;
                                        $("#registerDetailList"+newIdx+"_statusStr").val("冲销登记");
                                        $("#registerDetailList"+newIdx+"_status").val("3");
                                        var rgAmt = $("#registerDetailList"+newIdx+"_registerAmt").val();
                                        $("#registerDetailList"+newIdx+"_registerAmt").val(("-"+rgAmt));
                                        $("#registerDetailList"+newIdx+"_registerAmt").change();
                                        $("#registerDetailList"+newIdx+"_registerDate").val(new Date().format("yyyy-MM-dd"));
                                        $("#registerDetailList"+newIdx+"_button").hide();
                                        $("#registerDetailList"+newIdx+"_id").val("");
                                        console.log(new Date(data[idx].invoice.date).format("yyyy-MM-dd"));
                                        $("#registerDetailList"+newIdx+"_invoiceDate").val(new Date(data[idx].invoice.date).format("yyyy-MM-dd"));
                                        totalRgAmt($("#registerDetailList"+newIdx+"_registerAmt"));
                                    }else {
                                        delFlag.val("1");
                                        status.val("2");
                                        $(obj).parent().parent().hide();
                                        totalRgAmt(obj)
                                    }
                                }
                            }else {
                                top.layer.msg("取消登记失败，查询发票结算付款状态异常:"+result.msg);
                            }
                        }
                    })
                }

            }

            function setInvoiceValue(obj,idx) {
                var pref = "#registerDetailList"+idx+"_";
                var amtId = pref+"invoiceAmt";
                var dateId = pref+"invoiceDate";
                var incomeId = pref+"incomeAmt"
                $(amtId).val(parseFloat(obj.invoiceAmt).toFixed(2));
                $(dateId).val(obj.invoiceDate);
                $(incomeId).val(parseFloat(obj.incomeMoney).toFixed(2));

                var ivcAmt = parseFloat(obj.invoiceAmt-obj.incomeMoney);
                $(amtId).change();
                $(incomeId).change();
                var exAmt = $(pref+"registerAmt").val()
                if(exAmt==null||exAmt==''){
                    exAmt = 0
                }else {
                    exAmt = parseFloat(exAmt.replace(/[^\d\.-]/g, ""));
                }
                var rgstAmt = parseFloat($("#arrivalAmt").val().replace(/[^\d\.-]/g, "")) - (parseFloat($("#registerAmt").val().replace(/[^\d\.-]/g, ""))-exAmt);
                rgstAmt = parseFloat(rgstAmt);

                var resAmt = (ivcAmt>=rgstAmt?rgstAmt:ivcAmt);
                if(exAmt == 0){
                    $(pref+"registerAmt").val(resAmt.toFixed(2));
                    $(pref+"registerAmt").change();
                }else {
                    $(pref+"registerAmt").val((resAmt>exAmt?exAmt:resAmt).toFixed(2));
                    $(pref+"registerAmt").change();
                }
                totalRgAmt($(pref+"registerAmt"));
            }

            function caculateAmt(obj,idx) {
                formatNum(obj);
                var pref = "#registerDetailList"+idx+"_";
                var invoiceAmtId = pref+"invoiceAmt";
                var incomeId = pref + "incomeAmt";
                var val = parseFloat(obj.value.replace(/[^\d\.-]/g, ""));
                var amt = (parseFloat($(invoiceAmtId).val().replace(/[^\d\.-]/g, "")) - parseFloat($(incomeId).val().replace(/[^\d\.-]/g, "")));
                if (amt<val){
                    parent.layer.msg("登记金额不能大于发票余额", {icon: 5});
                    $(obj).val(amt.toFixed(2));
                    $(obj).change();
                    return false;
                }
                totalRgAmt(obj);
            }
            
            function validateTime(val,dateId) {
                var regDate = strToDate(val);
                var now = new Date();
                var days = Math.ceil(Math.abs(regDate.getTime()-now.getTime())/(24*60*60*1000))
                if(days>10){
                    parent.layer.msg("登记日期与当前时间差不能超过10天", {icon: 5});
                    $(dateId).val(new Date().format("yyyy-MM-dd"));
                    return false;
                }
                var arrDate = strToDate($("#arrivalDate").val());
                if(regDate.getTime()<arrDate.getTime()){
                    parent.layer.msg("登记日期不能早于到账日期", {icon: 5});
                    $(dateId).val(new Date().format("yyyy-MM-dd"));
                    return false;
                }
            }

            function strToDate(dateStr){
                var dateStr = dateStr.replace(/-/g, "/");//现将yyyy-MM-dd类型转换为yyyy/MM/dd
                var dateTime = Date.parse(dateStr);//将日期字符串转换为表示日期的秒数
                //注意：Date.parse(dateStr)默认情况下只能转换：月/日/年 格式的字符串，但是经测试年/月/日格式的字符串也能被解析
                var data = new Date(dateTime);//将日期秒数转换为日期格式
                return data;
            }
            
            function getAllInvoice() {
                var invoices = $("#registerDetailList tr:visible .invoiceId");
                var invoiceIds ="";
                for (var i=0;i<invoices.length;i++){
                    if($(invoices[i]).val()!=null&&$(invoices[i]).val()!=''){
                        invoiceIds+=$(invoices[i]).val();
                        invoiceIds+=",";
                    }
                }
                invoiceIds = invoiceIds.slice(0,invoiceIds.length-1);
                return invoiceIds;
            }

            function totalRgAmt(obj) {
                var rgs = $("#registerDetailList tr:visible td:nth-child(7) :input");
                var totalAmt = 0;
                for (var i=0;i<rgs.length;i++){
                    totalAmt += parseFloat($(rgs[i]).val().replace(/[^\d\.-]/g, ""));
                }

                var amt = parseFloat($("#arrivalAmt").val().replace(/[^\d\.-]/g, ""));
                if(amt<(totalAmt)){
                    parent.layer.msg("收入登记金额不能大于到账金额", {icon: 5});
                    $(obj).val(0);
                    return false;
                }else {
                    $("#registerAmt").val((totalAmt).toFixed(2))
                    $("#registerAmt").change();
                }
                return true;
            }
        </script>
	</form:form>
	</div>
</div>
</body>
</html>