<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/webpage/include/taglib.jsp"%>
<html>
<head>
	<title>收入结算管理</title>
	<meta name="decorator" content="default"/>
	<script type="text/javascript">
		var validateForm;
		function doSubmit(obj){//回调函数，在编辑和保存动作时，供openDialog调用提交表单。
		  if(validateForm.form()){

              if(obj == 1){
                  $('#flag').val('yes');
                  if($(document.getElementById("act.taskDefKey")).val()== "fpgly" && $("#settleInvoiceList tr:visible").length==0){
                      top.layer.msg('请至少添加一条分所开票明细！', {icon: 5});
                      return false;
                  }
                  if(!validateSum()){
                      top.layer.msg("分所开票价税合计金额不等于结算明细结算金额", {icon: 5});
                      return false;
                  }
              }else{
                  $('#flag').val('no');
              }

			  $("#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);
					}
				}
			});
            jQuery.validator.addMethod("percent", function(value, element) {
                var length = value.length;
                var phone = /^(100|[1-9]?\d(\.\d\d?)?)%$/;
                return this.optional(element) || (phone.test(value));
            }, "请填写正确的百分数");
            jQuery.validator.addMethod("invoiceNum", function(value, element) {
                if(value.length!=8)return true;
                var invoiceNumArr = $("#settleInvoiceList tr:visible input.invoiceNum");
                var id = $(element).attr("id");
                for(var i=0;i<invoiceNumArr.length;i++){
                    if(id == $(invoiceNumArr[i]).attr("id")){
                        continue;
                    }
                    if(value==$(invoiceNumArr[i]).val()){
                        return false;
                    }
                }
                var flag = true;
                $.ajax({
                    url:"${ctx}/workreceipts/workReceiptsSettle/invoiceNum",
                    data:{
                        "invoiceNum":value,
                        "comId":'${workReceiptsSettle.company.id}',
                        "id":'${workReceiptsSettle.id}'
                    },
                    async:false,
                    type:"post",
                    success:function (result) {
                        if(result.success && !result.body.isUsed){
                            flag=true;
                        }else {
                            flag=false;
                        }
                    },
                    error:function (result) {
                        top.layer.msg('异步校验发票号异常！请稍后重试', {icon: 0});
                        flag=false;
                    }
                })
                return flag;
            }, "发票号重复，请填写正确的发票号");
		});

        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);
        }

        function validateSum() {
            var rgs = $("#settleInvoiceList tr:visible td:nth-child(4) :input");
            var totalInvoiceAmt = 0;
            for (var i=0;i<rgs.length;i++){
                totalInvoiceAmt += parseFloat($(rgs[i]).val().replace(/[^\d\.-]/g, ""));
            }
            if(totalInvoiceAmt!=totalAmt){
                return false;
            }
            return true;
        }
        function validateAmt(obj) {
            var thisVal = parseFloat($(obj).val());
            var rgs = $("#settleInvoiceList tr:visible td:nth-child(4) :input");
            var totalInvoiceAmt = 0;
            for (var i=0;i<rgs.length;i++){
                totalInvoiceAmt += parseFloat($(rgs[i]).val().replace(/[^\d\.-]/g, ""));
            }

            if(totalInvoiceAmt>totalAmt){
                parent.layer.msg("分所开票价税合计金额不能大于结算明细结算金额", {icon: 5});
                $(obj).val(thisVal-(totalInvoiceAmt-totalAmt));
            }
            formatNum(obj);
            return;
        }
	</script>
</head>
<body>
    <div class="single-form">
        <div class="container">
            <form:form id="inputForm" modelAttribute="workReceiptsSettle" action="${ctx}/workreceipts/workReceiptsSettle/saveAudit" method="post" class="form-horizontal">
            <form:hidden path="id"/>
            <form:hidden path="home"/>
            <form:hidden path="act.taskId"/>
            <form:hidden path="act.taskName"/>
            <form:hidden path="act.taskDefKey"/>
            <form:hidden path="act.procInsId"/>
            <form:hidden path="act.procDefId"/>
            <form:hidden id="flag" path="act.flag"/>
                <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">结算部门：</label>
                        <div class="layui-input-block">
                            <input name="office.name" type="text" readonly="true" class="form-control required layui-input" value="${workReceiptsSettle.office.topCompany}" />
                            <input name="office.id" type="hidden" readonly="true" class="form-control layui-input" value="${workReceiptsSettle.office.id}"/>
                        </div>
                    </div>
                    <div class="layui-item layui-col-sm6">
                        <label class="layui-form-label">结算单号：</label>
                        <div class="layui-input-block">
                            <div class="input-group">
                                <input name="num" type="text" readonly="true" class="form-control layui-input" value="${workReceiptsSettle.num}" />
                                <span class="input-group-btn">
                                        <label class="form-status"><c:choose><c:when test="${not empty workReceiptsSettle.state}">${fns:getDictLabel(workReceiptsSettle.state, 'audit_state', '')}</c:when><c:otherwise>新添</c:otherwise></c:choose></label>
                                     </span>
                            </div>
                        </div>
                    </div>
                    <div class="layui-item layui-col-sm6">
                        <label class="layui-form-label">结算人：</label>
                        <div class="layui-input-block">
                            <input name="createBy.name" type="text" readonly="true" class="form-control required layui-input" value="${workReceiptsSettle.createBy.name}" />
                            <input name="createBy.id" type="hidden" readonly="true" class="form-control layui-input" value="${workReceiptsSettle.createBy.id}"/>
                        </div>
                    </div>
                    <div class="layui-item layui-col-sm6">
                        <label class="layui-form-label">结算日期：</label>
                        <div class="layui-input-block">
                            <input name="createDate" type="text" readonly="true" class="form-control required layui-input" value="<fmt:formatDate value="${workReceiptsSettle.createDate}" pattern="yyyy-MM-dd"/>" />
                        </div>
                    </div>
                    <div class="layui-item layui-col-sm12 with-textarea">
                        <label class="layui-form-label">备注：</label>
                        <div class="layui-input-block">
                            <form:textarea path="remarks" htmlEscape="false" rows="3" readonly="true" class="form-control layui-area"/>
                        </div>
                    </div>
                </div>
                <div class="form-group layui-row">
                    <div class="form-group-label"><h2>结算明细</h2></div>
                    <div class="layui-item layui-col-xs12 form-table-container" >
                        <table id="contentTable" class="table table-bordered table-condensed details">
                            <thead>
                            <tr>
                                <th width="10%"><font style="color: red">*</font>发票号</th>
                                <th>价税合计</th>
                                <th>税额</th>
                                <th width="10%">累计登记金额</th>
                                <th>结算比例</th>
                                <th>结算金额</th>
                                <th>项目名称</th>
                                <th>合同名称</th>
                                <th>所属部门</th>
                                <th width="10%">实际开票单位</th>
                                <th>确认付款</th>
                                <th>确认日期</th>
                            </tr>
                            </thead>
                            <tbody id="settleDetailList">
                            <c:forEach items="${workReceiptsSettle.settleDetailList}" var="row">
                                <tr>
                                    <td style='text-align:center;'>
                                            ${row.invoice.number}
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatNumber value="${row.invoice.totalMoney}" pattern="#,##0.00#"/>
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatNumber value="${row.invoice.taxMoney}" pattern="#,##0.00#"/>
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatNumber value="${row.invoice.incomeMoney}" pattern="#,##0.00#"/>
                                    </td>
                                    <td style='text-align:center;'>
                                            ${row.settlePct}
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatNumber value="${row.settleAmt}" pattern="#,##0.00#"/>
                                    </td>
                                    <td style='text-align:center;'>
                                            ${row.invoice.workInvoice.project.projectName}
                                    </td>
                                    <td style='text-align:center;'>
                                            ${row.invoice.workInvoice.project.workContractInfo.name}
                                    </td>
                                    <td style='text-align:center;'>
                                            ${row.invoice.workInvoice.office.name}
                                    </td>
                                    <td style='text-align:center;'>
                                            ${row.invoice.workInvoice.client.name}
                                    </td>
                                    <td style='text-align:center;'>
                                            ${fns:getDictLabel(row.status, 'settle_status', '未确认')}
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatDate value="${row.settleDate}" pattern="yyyy-MM-dd"/>
                                    </td>
                                </tr>
                            </c:forEach>
                            </tbody>
                        </table>
                        <script type="text/javascript">
                            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 bornTemplete(list, idx, tpl, row, idx1){
                                $(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 id = $(prefix+"_id");
                                var delFlag = $(prefix+"_delFlag");
                                if (id.val() == ""){
                                    $(obj).parent().parent().remove();
                                }else {
                                    delFlag.val("1");
                                    $(obj).parent().parent().hide();
                                }
                            }
                        </script>
                    </div>
                </div>
                <div class="form-group layui-row">
                    <div class="form-group-label"><h2>分所开票明细</h2></div>
                    <div class="layui-item nav-btns" id="detailAddButton">
                        <a class="nav-btn nav-btn-add" onclick="addInvoiceRow('#settleInvoiceList', settleInvoiceIdx, settleInvoiceTpl,{});"><i class="fa fa-plus"></i>&nbsp;新增</a>
                    </div>
                    <div class="layui-item layui-col-xs12 form-table-container" >
                        <table id="contentTable1" class="table table-bordered table-condensed no-bottom-margin can-edit">
                            <thead>
                            <tr>
                                <th class="hide"></th>
                                <th width="20%"><font style="color: red">*</font>发票代码</th>
                                <th width="20%"><font style="color: red">*</font>发票号</th>
                                <th width="20%"><font style="color: red">*</font>价税合计</th>
                                <th width="20%"><font style="color: red">*</font>税额</th>
                                <th width="20%">操作</th>
                            </tr>
                            </thead>
                            <tbody id="settleInvoiceList">
                            </tbody>
                        </table>
                        <script type="text/template" id="settleInvoiceTpl">//<!--
                            <tr id="settleInvoiceList{{idx}}">
                            <td class="hide">
                            <input id="settleInvoiceList{{idx}}_id" name="settleInvoiceList[{{idx}}].id" type="hidden" value="{{row.id}}"/>
                            <input id="settleInvoiceList{{idx}}_delFlag" name="settleInvoiceList[{{idx}}].delFlag" type="hidden" value="0"/>
                            </td>
                            <td>
                                <input id="settleInvoiceList{{idx}}_code" type="text" name="settleInvoiceList[{{idx}}].code" value="{{row.code}}" minlength="10" maxlength="12" class="form-control digits required "/>
                            </td>
                            <td>
                                <input id="settleInvoiceList{{idx}}_num" type="text" name="settleInvoiceList[{{idx}}].num" value="{{row.num}}" minlength="8" maxlength="8" class="form-control digits required invoiceNum"/>
                            </td>
                            <td>
                                <input id="settleInvoiceList{{idx}}_invoiceAmt" name="settleInvoiceList[{{idx}}].totalMoney" type="text" value="{{row.totalMoney}}" onchange="validateAmt(this);" class="form-control number required money"/>
                            </td>
                            <td>
                                <input id="settleInvoiceList{{idx}}_taxRate" name="settleInvoiceList[{{idx}}].taxRate" type="text" value="{{row.taxRate}}" onchange="formatNum(this);" class="form-control number required money"/>
                            </td>
                            <td class="text-center op-td">
                            <span class="op-btn op-btn-delete" onclick="delRow(this, '#settleInvoiceList{{idx}}')" ><i class="fa fa-trash"></i> 取消</span>
                            </td>
                            </tr>//-->
                        </script>
                        <script type="text/javascript">
                            var settleInvoiceIdx = 0, settleInvoiceTpl = $("#settleInvoiceTpl").html().replace(/(\/\/\<!\-\-)|(\/\/\-\->)/g,"");
                            var data2;
                            var totalAmt=0;
                            $(document).ready(function() {
                                data2 = ${fns:toJson(workReceiptsSettle.settleInvoiceList)};
                                if(data2!=null) {
                                    for (var i = 0; i < data2.length; i++) {
                                        addInvoiceRow('#settleInvoiceList', settleInvoiceIdx, settleInvoiceTpl, data2[i]);
                                        $(":input.money").change();
                                    }
                                }

                                var detailList = ${fns:toJson(workReceiptsSettle.settleDetailList)};
                                if(detailList!=null){
                                    for (var i = 0; i < detailList.length; i++) {
                                        totalAmt+=detailList[i].settleAmt;
                                    }
                                }
                            });

                            function addInvoiceRow(list, idx, tpl, row){
                                var trArr = $("#settleInvoiceList tr:visible");
                                if(trArr !=undefined && trArr.length>0){
                                    if(row == undefined){
                                        row = {};
                                    }
                                    var id = $(trArr[trArr.length-1]).attr("id");
                                    row.code = $("#"+id+"_code").val();
                                }
                                var idx1 = $("#settleInvoiceList tr").length +1;
                                bornTemplete(list, idx, tpl, row, idx1);
                                settleInvoiceIdx +=1;
                            }

                        </script>
                    </div>
                </div>
                <div class="form-group layui-row">
                    <div class="form-group-label"><h2>审批意见</h2></div>
                    <div class="layui-item layui-col-xs12 with-textarea" >
                        <label class="layui-form-label">审批意见：</label>
                        <div class="layui-input-block">
                            <form:textarea path="act.comment" class="form-control" rows="4" maxlength="127" />
                            <input type="file" name="upload_files" style="display: none;">
                        </div>
                    </div>
                </div>
                <div class="form-group layui-row">
                    <div class="form-group-label"><h2>审批流程</h2></div>
                    <div class="layui-item layui-col-xs12 form-table-container" >
                        <act:flowChart procInsId="${workReceiptsSettle.act.procInsId}"/>
                        <act:histoicFlow procInsId="${workReceiptsSettle.act.procInsId}"/>
                    </div>
                </div>

                <div class="form-group layui-row page-end"></div>
        </form:form>
        </div>
    </div>
</body>
</html>