<%@ 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()== "cn"){
                      var settleStatusList = $(".settleStatus");
                      if(settleStatusList!=null&&settleStatusList.length>0){
                          for(var i=0;i<settleStatusList.length;i++){
                              var html = $(settleStatusList[0]).html();
                              if("未付款"==html.trim()){
                                  top.layer.msg('请确认付款全部结算明细！', {icon: 0});
                                  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));
            }, "请填写正确的百分数");

		});

        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>
</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">
                            <thead>
                            <tr>
                                <th><font style="color: red">*</font>发票号</th>
                                <th>价税合计</th>
                                <th>税额</th>
                                <th>累计登记金额</th>
                                <th>结算比例</th>
                                <th>结算金额</th>
                                <th>项目名称</th>
                                <th>合同名称</th>
                                <th>所属部门</th>
                                <th>实际开票单位</th>
                                <th>确认付款</th>
                                <th>确认日期</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="settleDetailList">
                            <c:forEach items="${workReceiptsSettle.settleDetailList}" var="row" varStatus="varStatus">
                                <tr>
                                    <td style='text-align:center;'>
                                            ${row.invoice.number}
                                    </td>
                                    <td style='text-align:center;' id="total${varStatus.index}Money">
                                        <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;' id="income${varStatus.index}Money">
                                        <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;' id="settle${varStatus.index}Staus" class="settleStatus">
                                            ${fns:getDictLabel(row.status, 'settle_status', '未付款')}
                                    </td>
                                    <td style='text-align:center;' id="settle${varStatus.index}Date">
                                        <fmt:formatDate value="${row.settleDate}" pattern="yyyy-MM-dd"/>
                                    </td>
                                    <td class="text-center op-td" style="width:60px">
                                        <div id="confirm${varStatus.index}Button" <c:if test="${row.status == '1'}">hidden="hidden"</c:if>>
                                            <span class="op-btn op-btn-edit" onclick="confirmPay('${row.invoice.id}','${varStatus.index}');" ><i class="fa fa-edit"></i> 确认</span>
                                        </div>
                                        <div id="cancel${varStatus.index}Button" <c:if test="${row.status == null or row.status == '' or row.status == '0'}">hidden="hidden"</c:if>>
                                            <span class="op-btn op-btn-delete" onclick="cancelPay('${row.invoice.id}','${varStatus.index}');" ><i class="fa fa-trash"></i> 取消</span>
                                        </div>
                                    </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 confirmPay(invoiceId,idx) {
                                var totalAmt = "#total"+idx+"Money";
                                var incomeAmt = "#income"+idx+"Money";
                                if($(totalAmt).val().trim()!=$(incomeAmt).val().trim()){
                                    top.layer.msg("发票累计登记金额不等于价税合计，不能确认付款",{icon:2});
                                    return;
                                }
                                var confirmId = "#confirm"+idx+"Button";
                                var cancelId = "#cancel"+idx+"Button";
                                var statusId = "#settle"+idx+"Staus";
                                var settleDate = "#settle"+idx+"Date";
                                $.ajax({
                                    url:"${ctx}/workreceipts/workReceiptsSettle/confirmPay",
                                    data:{"invoiceId":invoiceId,"status":"1","settleId":'${workReceiptsSettle.id}'},
                                    type:"post",
                                    success:function(result){
                                        if(result.success){
                                            $(confirmId).hide();
                                            $(cancelId).show();
                                            $(statusId).html("已付款");
                                            $(settleDate).html(new Date().format("yyyy-MM-dd"));
                                            top.layer.msg("确认付款状态成功",{icon:1});
                                        }else {
                                            top.layer.msg(result.msg,{icon:1});
                                        }
                                    },
                                    error:function (data) {
                                        top.layer.msg("更新付款状态异常",{icon:1});
                                    }
                                })
                            }

                            function cancelPay(invoiceId,idx) {
                                var confirmId = "#confirm"+idx+"Button";
                                var cancelId = "#cancel"+idx+"Button";
                                var statusId = "#settle"+idx+"Staus";
                                var settleDate = "#settle"+idx+"Date";
                                $.ajax({
                                    url:"${ctx}/workreceipts/workReceiptsSettle/confirmPay",
                                    data:{"invoiceId":invoiceId,"status":"0","settleId":'${workReceiptsSettle.id}'},
                                    type:"post",
                                    success:function(result){
                                        if(result.success){
                                            $(confirmId).show();
                                            $(cancelId).hide();
                                            $(statusId).html("未付款");
                                            $(settleDate).html("");
                                            top.layer.msg("取消确认付款状态成功",{icon:1});
                                        }else {
                                            top.layer.msg(result.msg,{icon:1});
                                        }
                                    },
                                    error:function (data) {
                                        top.layer.msg("更新付款状态异常",{icon:1});
                                    }
                                })
                            }

                            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 layui-col-xs12 form-table-container" >
                        <table id="contentTable1" class="table table-bordered table-condensed">
                            <thead>
                            <tr>
                                <th><font style="color: red">*</font>发票代码</th>
                                <th><font style="color: red">*</font>发票号</th>
                                <th><font style="color: red">*</font>价税合计</th>
                                <th><font style="color: red">*</font>税额</th>
                            </tr>
                            </thead>
                            <tbody id="settleInvoiceList">
                            <c:forEach items="${workReceiptsSettle.settleInvoiceList}" var="row">
                                <tr>
                                    <td style='text-align:center;'>
                                            ${row.code}
                                    </td>
                                    <td style='text-align:center;'>
                                            ${row.num}
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatNumber value="${row.totalMoney}" pattern="#,##0.00#"/>
                                    </td>
                                    <td style='text-align:center;'>
                                        <fmt:formatNumber value="${row.taxRate}" pattern="#,##0.00#"/>
                                    </td>
                                </tr>
                            </c:forEach>
                            </tbody>
                        </table>
                    </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>